Compare commits

..
3 Commits
Author SHA1 Message Date
ayurishchevandClaude Sonnet 5.5 56dae90ff5 Guard server setup behind an initialized PKI
- Profiler: server_files_missing/require_* helpers; 409 for
  /server/configure, start/restart and POST /profiles when the PKI is
  not initialized or server files (honouring fqdn_server) are missing;
  stop stays allowed; DELETE /system/pki returns 409 while OpenVPN runs;
  GET /system/init/status adds pki_ready, server_ready, missing.
- UI: shared usePkiStatus; VPN menu item locked until the PKI is ready,
  route guard for /config/vpn, Start/Restart and New Client disabled
  with hints, lock notice on the VPN page.
- Test: one pytest (test_pki_guard.py).
- Docs: plan and summary in DOCS/Changes, API reference, README, Index.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 21:52:40 +03:00
ayurishchevandClaude Sonnet 5.5 dcc3d7f2d5 UI: shared toast notifications in the bottom-right corner
- useToast composable and ToastContainer (mounted once in App.vue):
  stacked toasts with icon, close button and progress bar, hover pause,
  slide-in animation, aria roles, full width on phones.
- Light and dark theme colour tokens; old .toast-message styles removed.
- PKIConfig, VPNConfig, ServerManagement and Certificates use the shared
  toast through thin showMessage/showToast wrappers.
- Docs: plan and summary in DOCS/Changes, README, Index.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 21:05:41 +03:00
ayurishchevandClaude Sonnet 5.5 d251ec73d0 Certificates: profile modal with notes, note tooltip; async PKI init
- Profiler: UserProfile.note (nullable, startup migration), PUT
  /profiles/{id}/note (max 1000 chars); add missing `requests`
  dependency (client creation failed without Public IP set).
- UI: clickable rows on Certificates open a compact profile details
  modal with an editable note; tooltip with the note on the client
  name (v-note-tooltip) and a note icon.
- PKI init runs in a background thread: POST /system/init returns 202,
  GET /system/init/status, 409 for a second start, Clear PKI and client
  creation are blocked while it runs. A marker file identifies an
  interrupted run (only such a PKI is wiped on the next Init).
- PKI Configuration page: state from the server, progress spinner and
  step text, polling, Init/Clear/Save locked while running, Init locked
  once initialized.
- Tests: one pytest each for notes and async init (requirements-dev.txt).
- Docs: plans and summaries in DOCS/Changes, API reference, README, Index.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 20:56:36 +03:00
38 changed files with 1370 additions and 144 deletions

No files matched your search

+12 -1
View File
@@ -1,4 +1,4 @@
from sqlalchemy import create_engine
from sqlalchemy import create_engine, inspect, text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
@@ -22,3 +22,14 @@ def get_db():
yield db
finally:
db.close()
def ensure_columns():
"""Idempotent 'add column if missing' migration for existing databases.
create_all() creates new tables but never alters existing ones."""
insp = inspect(engine)
if "user_profiles" not in insp.get_table_names():
return
existing = {c["name"] for c in insp.get_columns("user_profiles")}
if "note" not in existing:
with engine.begin() as conn:
conn.execute(text("ALTER TABLE user_profiles ADD COLUMN note TEXT"))
+2 -1
View File
@@ -7,13 +7,14 @@ import os
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from database import engine, Base
from database import engine, Base, ensure_columns
from routers import system, server, profiles, server_process
from utils.logging import setup_logging
from fastapi.middleware.cors import CORSMiddleware
# Create Database Tables
Base.metadata.create_all(bind=engine)
ensure_columns()
setup_logging()
+2 -1
View File
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime, JSON
from sqlalchemy import Column, Integer, String, Boolean, DateTime, JSON, Text
from sqlalchemy.sql import func
from database import Base
from datetime import datetime
@@ -61,3 +61,4 @@ class UserProfile(Base):
is_revoked = Column(Boolean, default=False)
is_expired = Column(Boolean, default=False)
file_path = Column(String, nullable=True)
note = Column(Text, nullable=True)
+3
View File
@@ -0,0 +1,3 @@
-r requirements.txt
pytest
httpx
+1
View File
@@ -5,3 +5,4 @@ psutil
python-multipart
jinja2
pyjwt
requests
+19 -1
View File
@@ -5,7 +5,7 @@ from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
from models import UserProfile
from schemas import UserProfile as UserProfileSchema, UserProfileCreate
from schemas import UserProfile as UserProfileSchema, UserProfileCreate, UserProfileNoteUpdate
from services import pki, generator
from datetime import datetime
@@ -74,6 +74,13 @@ def create_profile(
profile_in: UserProfileCreate,
db: Session = Depends(get_db)
):
if pki.is_init_running():
raise HTTPException(status_code=409, detail="PKI initialization is running")
try:
pki.require_pki_ready()
except pki.PkiNotReady as e:
raise HTTPException(status_code=409, detail=str(e))
# Check existing
existing = db.query(UserProfile).filter(UserProfile.username == profile_in.username).first()
if existing:
@@ -116,6 +123,17 @@ def create_profile(
db.refresh(new_profile)
return new_profile
@router.put("/profiles/{profile_id}/note", response_model=UserProfileSchema)
def update_profile_note(profile_id: int, body: UserProfileNoteUpdate, db: Session = Depends(get_db)):
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
if not profile:
raise HTTPException(status_code=404, detail="Profile not found")
profile.note = body.note
db.commit()
db.refresh(profile)
return profile
@router.delete("/profiles/{profile_id}")
def revoke_profile(profile_id: int, db: Session = Depends(get_db)):
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
+4 -1
View File
@@ -4,7 +4,7 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from utils.auth import verify_token
from services import generator, process, config
from services import generator, process, config, pki
logger = logging.getLogger(__name__)
@@ -13,6 +13,7 @@ router = APIRouter(dependencies=[Depends(verify_token)])
@router.post("/server/configure")
def configure_server(db: Session = Depends(get_db)):
try:
pki.require_server_ready(db)
# Generate to a temporary location or standard location
# As per plan, we behave like srvconf
output_path = "/etc/openvpn/server.conf"
@@ -46,6 +47,8 @@ def configure_server(db: Session = Depends(get_db)):
return {"message": "Server configuration generated", "path": output_path}
except HTTPException:
raise
except pki.PkiNotReady as e:
raise HTTPException(status_code=409, detail=str(e))
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
+11 -2
View File
@@ -1,6 +1,8 @@
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from services import process
from services import process, pki
from database import get_db
from sqlalchemy.orm import Session
from utils.auth import verify_token
from typing import Optional
from fastapi import Depends
@@ -21,7 +23,7 @@ class ProcessStats(BaseModel):
uptime: Optional[str] = None
@router.post("/server/process/{action}", response_model=ProcessActionResponse)
def manage_process(action: str):
def manage_process(action: str, db: Session = Depends(get_db)):
"""
Control the OpenVPN server process.
Action: start, stop, restart
@@ -29,6 +31,13 @@ def manage_process(action: str):
if action not in ["start", "stop", "restart"]:
raise HTTPException(status_code=400, detail="Invalid action. Use start, stop, or restart")
# Stop stays allowed: it must work after Clear PKI or with a broken setup
if action in ("start", "restart"):
try:
pki.require_server_ready(db)
except pki.PkiNotReady as e:
raise HTTPException(status_code=409, detail=str(e))
result = process.control_service(action)
if result["status"] == "error":
+15 -6
View File
@@ -6,7 +6,7 @@ from schemas import (
ConfigResponse, SystemSettings, PKISetting,
SystemSettingsUpdate, PKISettingUpdate
)
from services import config, pki
from services import config, pki, process
router = APIRouter(dependencies=[Depends(verify_token)])
@@ -36,15 +36,24 @@ def update_pki_config(
):
return config.update_pki_settings(db, settings)
@router.post("/system/init")
@router.post("/system/init", status_code=202)
def init_system_pki(db: Session = Depends(get_db)):
try:
msg = pki.init_pki(db)
return {"message": msg}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
pki.start_init_async(db)
except pki.InitConflict as e:
raise HTTPException(status_code=409, detail=str(e))
return {"state": "running"}
@router.get("/system/init/status")
def get_init_status(db: Session = Depends(get_db)):
return pki.init_status(db)
@router.delete("/system/pki")
def clear_system_pki(db: Session = Depends(get_db)):
if pki.is_init_running():
raise HTTPException(status_code=409, detail="PKI initialization is running")
# Do not pull the keys from under a running server
if process.get_process_stats()["status"] == "running":
raise HTTPException(status_code=409, detail="Stop OpenVPN first")
msg = pki.clear_pki(db)
return {"message": msg}
+12
View File
@@ -224,6 +224,18 @@ class UserProfile(UserProfileBase):
is_revoked: bool = False
is_expired: bool = False
file_path: Optional[str] = None
note: Optional[str] = None
class Config:
from_attributes = True
class UserProfileNoteUpdate(BaseModel):
note: Optional[str] = Field(None, max_length=1000)
@field_validator("note")
@classmethod
def _empty_to_none(cls, val):
# Empty or whitespace-only note clears the field
if val is None or not val.strip():
return None
return val
+117 -6
View File
@@ -1,9 +1,12 @@
import os
import subprocess
import logging
from .config import get_pki_settings
import shutil
import threading
from .config import get_pki_settings, get_system_settings
from sqlalchemy.orm import Session
from datetime import datetime
from database import SessionLocal
logger = logging.getLogger(__name__)
@@ -120,37 +123,145 @@ def _get_easyrsa_env(db: Session):
}
return env
def init_pki(db: Session):
# --- Async PKI initialization -------------------------------------------
# Single Profiler process only: the job state lives in memory.
class InitConflict(Exception):
"""PKI init cannot start: a job is running or the PKI is already complete."""
_init_lock = threading.Lock()
_init_job = {"state": "idle", "step": None, "started_at": None, "finished_at": None, "error": None}
def _marker_path() -> str:
# Outside PKI_DIR: "easyrsa init-pki" recreates that directory
return os.path.join(os.path.dirname(PKI_DIR), ".pki-init-in-progress")
def is_initialized(db: Session = None) -> bool:
"""A CA exists and no init run was left unfinished. A PKI without the marker is never
wiped automatically, even if it was built by an older version."""
return os.path.isfile(os.path.join(PKI_DIR, "ca.crt")) and not os.path.exists(_marker_path())
def is_init_running() -> bool:
with _init_lock:
return _init_job["state"] == "running"
class PkiNotReady(Exception):
"""An operation needs keys that are not there (PKI absent, init running or server files missing)."""
NOT_INITIALIZED_MSG = "PKI is not initialized. Initialize PKI first."
def server_files_missing(db: Session) -> list:
"""Names (relative to PKI_DIR) of the files server.conf points to that do not exist.
Checks the real files: a changed fqdn_server leaves the old certificate behind."""
fqdn = get_pki_settings(db).fqdn_server
files = ["ca.crt", f"issued/{fqdn}.crt", f"private/{fqdn}.key", "dh.pem", "ta.key"]
if get_system_settings(db).crl_verify:
files.append("crl.pem")
return [f for f in files if not os.path.isfile(os.path.join(PKI_DIR, f))]
def require_pki_ready():
"""CA operations (client certificates): initialized PKI and no init job running."""
if is_init_running() or not is_initialized():
raise PkiNotReady(NOT_INITIALIZED_MSG)
def require_server_ready(db: Session):
"""Server operations (configure, start, restart): CA plus every file server.conf references."""
require_pki_ready()
missing = server_files_missing(db)
if missing:
raise PkiNotReady(f"PKI server files are missing: {', '.join(missing)}")
def init_status(db: Session) -> dict:
with _init_lock:
job = dict(_init_job)
job["initialized"] = is_initialized()
missing = server_files_missing(db)
running = job["state"] == "running"
job["missing"] = missing
job["pki_ready"] = job["initialized"] and not running
job["server_ready"] = job["pki_ready"] and not missing
return job
def _set_step(step: str):
with _init_lock:
_init_job["step"] = step
def _gen_ta_key():
# TLS auth key requires openvpn, not easyrsa
subprocess.run(["openvpn", "--genkey", "secret", os.path.join(PKI_DIR, "ta.key")], check=True)
def init_pki(db: Session, on_step=None):
env = _get_easyrsa_env(db)
pki_settings = get_pki_settings(db)
step = on_step or (lambda name: None)
if os.path.exists(os.path.join(PKI_DIR, "ca.crt")):
if is_initialized():
logger.warning("PKI already initialized")
return "PKI already initialized"
# Init PKI
step("init-pki")
_run_easyrsa(["init-pki"], env)
# Build CA
step("ca")
_run_easyrsa(["--req-cn=" + pki_settings.fqdn_ca, "build-ca", "nopass"], env)
# Build Server Cert
step("server-cert")
_run_easyrsa(["build-server-full", pki_settings.fqdn_server, "nopass"], env)
# Gen DH
step("dh")
_run_easyrsa(["gen-dh"], env)
# Gen TLS Auth Key (requires openvpn, not easyrsa)
ta_key_path = os.path.join(PKI_DIR, "ta.key")
subprocess.run(["openvpn", "--genkey", "secret", ta_key_path], check=True)
# Gen TLS Auth Key
step("ta-key")
_gen_ta_key()
# Gen CRL
step("crl")
_run_easyrsa(["gen-crl"], env)
_publish_crl()
return "PKI Initialized"
def _init_worker():
db = SessionLocal() # own session: the request session is closed after the 202
try:
init_pki(db, on_step=_set_step)
os.remove(_marker_path())
result = {"state": "done", "step": None, "error": None}
except Exception as e:
logger.exception("Async PKI init failed")
result = {"state": "error", "error": str(e)[:1000]}
finally:
db.close()
with _init_lock:
_init_job.update(result, finished_at=datetime.utcnow().isoformat() + "Z")
def start_init_async(db: Session):
with _init_lock:
if _init_job["state"] == "running":
raise InitConflict("PKI initialization is already running")
if is_initialized():
raise InitConflict("PKI is already initialized")
# Here the PKI is absent, has no CA, or carries the marker of an interrupted run:
# nothing usable in it, start from scratch
if os.path.exists(PKI_DIR):
shutil.rmtree(PKI_DIR)
os.makedirs(os.path.dirname(_marker_path()), exist_ok=True)
open(_marker_path(), "w").close()
_init_job.update(state="running", step=None, error=None, finished_at=None,
started_at=datetime.utcnow().isoformat() + "Z")
threading.Thread(target=_init_worker, daemon=True).start()
def clear_pki(db: Session):
with _init_lock:
if _init_job["state"] != "running":
_init_job.update(state="idle", step=None, started_at=None, finished_at=None, error=None)
if os.path.exists(_marker_path()):
os.remove(_marker_path())
# 1. Clear Database Users
from models import UserProfile
try:
+59
View File
@@ -0,0 +1,59 @@
import os
import tempfile
import threading
import time
# The DB path must be set before database.py is imported (via main)
_tmp = tempfile.TemporaryDirectory()
os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db")
from fastapi.testclient import TestClient
from main import app
from services import pki
from utils.auth import verify_token
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
client = TestClient(app)
def test_async_init_runs_once(monkeypatch):
pki_dir = os.path.join(_tmp.name, "pki")
release = threading.Event()
def touch(*parts):
path = os.path.join(pki_dir, *parts)
os.makedirs(os.path.dirname(path), exist_ok=True)
open(path, "w").close()
def fake_easyrsa(command, env):
if command[0] == "build-server-full":
touch("issued", command[1] + ".crt")
elif command[0] == "gen-dh":
release.wait(5) # keeps the job running until the test lets go
touch("dh.pem")
elif command[0] == "gen-crl":
touch("crl.pem")
elif "build-ca" in command:
touch("ca.crt")
monkeypatch.setattr(pki, "PKI_DIR", pki_dir)
monkeypatch.setattr(pki, "_run_easyrsa", fake_easyrsa)
monkeypatch.setattr(pki, "_gen_ta_key", lambda: touch("ta.key"))
monkeypatch.setattr(pki, "_publish_crl", lambda: True)
res = client.post("/api/system/init")
assert res.status_code == 202 and res.json() == {"state": "running"}
assert client.post("/api/system/init").status_code == 409
assert client.get("/api/system/init/status").json()["state"] == "running"
assert client.delete("/api/system/pki").status_code == 409
release.set()
deadline = time.time() + 5
while time.time() < deadline:
status = client.get("/api/system/init/status").json()
if status["state"] != "running":
break
time.sleep(0.05)
assert status["state"] == "done" and status["initialized"] is True
assert client.post("/api/system/init").status_code == 409
+52
View File
@@ -0,0 +1,52 @@
import os
import tempfile
# The DB path must be set before database.py is imported (via main)
_tmp = tempfile.TemporaryDirectory()
os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db")
from fastapi.testclient import TestClient
from main import app
from database import SessionLocal
from services import pki, config, process
from utils.auth import verify_token
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
client = TestClient(app)
def test_server_and_clients_need_pki(monkeypatch):
pki_dir = os.path.join(_tmp.name, "pki")
monkeypatch.setattr(pki, "PKI_DIR", pki_dir)
# Nothing here may start OpenVPN or write to /etc/openvpn
monkeypatch.setattr(pki, "build_client", lambda username, db: (_ for _ in ()).throw(RuntimeError("stub")))
monkeypatch.setattr(process, "control_service", lambda action: {"status": "success", "message": action})
# No PKI: everything that needs keys is refused
assert client.post("/api/server/configure").status_code == 409
assert client.post("/api/server/process/start").status_code == 409
assert client.post("/api/profiles", json={"username": "alice"}).status_code == 409
status = client.get("/api/system/init/status").json()
assert status["pki_ready"] is False and status["server_ready"] is False
assert status["missing"]
# Stub PKI with the names the settings ask for
db = SessionLocal()
try:
fqdn = config.get_pki_settings(db).fqdn_server
crl_verify = config.get_system_settings(db).crl_verify
finally:
db.close()
files = ["ca.crt", "dh.pem", "ta.key", f"issued/{fqdn}.crt", f"private/{fqdn}.key"]
if crl_verify:
files.append("crl.pem")
for name in files:
path = os.path.join(pki_dir, name)
os.makedirs(os.path.dirname(path), exist_ok=True)
open(path, "w").close()
status = client.get("/api/system/init/status").json()
assert status["pki_ready"] is True and status["server_ready"] is True and status["missing"] == []
assert client.post("/api/server/process/start").status_code == 200
# Past the guard: fails later in the stubbed build (500), but not with 409
assert client.post("/api/profiles", json={"username": "alice"}).status_code != 409
+32
View File
@@ -0,0 +1,32 @@
import os
import tempfile
# The DB path must be set before database.py is imported (via main)
_tmp = tempfile.TemporaryDirectory()
os.environ["OVPMON_PROFILER_DB_PATH"] = os.path.join(_tmp.name, "test.db")
from fastapi.testclient import TestClient
from main import app
from database import SessionLocal
from models import UserProfile
from utils.auth import verify_token
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
client = TestClient(app)
def test_put_note_is_stored_and_listed():
db = SessionLocal()
profile = UserProfile(username="note-user", status="active")
db.add(profile)
db.commit()
profile_id = profile.id
db.close()
res = client.put(f"/api/profiles/{profile_id}/note", json={"note": "hello"})
assert res.status_code == 200
assert res.json()["note"] == "hello"
res = client.get("/api/profiles")
assert res.status_code == 200
assert [p["note"] for p in res.json() if p["id"] == profile_id] == ["hello"]
+27 -3
View File
@@ -38,9 +38,13 @@
<router-link to="/config/pki" class="nav-link" active-class="active" title="PKI">
<i class="fas fa-fingerprint"></i> <span>PKI</span>
</router-link>
<router-link to="/config/vpn" class="nav-link" active-class="active" title="VPN">
<router-link v-if="pkiStatus.pki_ready" to="/config/vpn" class="nav-link" active-class="active" title="VPN">
<i class="fas fa-server"></i> <span>VPN</span>
</router-link>
<!-- Locked until the PKI is initialized: stays visible so the reason is clear -->
<a v-else href="/config/pki" class="nav-link nav-link-locked" title="Initialize PKI first" @click.prevent="onLockedVpnClick">
<i class="fas fa-lock"></i> <span>VPN</span>
</a>
<!-- SECTION: MANAGEMENT -->
<div class="nav-section-header mt-3">MANAGEMENT</div>
@@ -118,6 +122,9 @@
</div>
</main>
</div>
<!-- Shared toasts: outside the v-if/v-else pair so they also work on the Login page -->
<ToastContainer />
</template>
<script setup>
@@ -125,6 +132,9 @@ import { ref, onMounted, watch, computed } from 'vue';
import { useAppConfig } from './composables/useAppConfig';
import { useApi } from './composables/useApi';
import { useRoute, useRouter } from 'vue-router';
import ToastContainer from './components/ToastContainer.vue';
import { usePkiStatus } from './composables/usePkiStatus';
import { useToast } from './composables/useToast';
const { loadConfig, isLoaded } = useAppConfig();
const { apiClient } = useApi();
@@ -135,6 +145,8 @@ const isSidebarOpen = ref(false);
const isCompact = ref(false);
const route = useRoute();
const router = useRouter();
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
const toast = useToast();
const isAuthenticated = computed(() => route.name !== 'Login');
const username = ref(localStorage.getItem('ovpmon_user') || '');
@@ -156,6 +168,12 @@ const syncUsername = async () => {
};
const onUserChanged = () => { username.value = localStorage.getItem('ovpmon_user') || ''; };
// The locked VPN item points to the PKI page instead of the VPN page
const onLockedVpnClick = () => {
toast.show('Initialize PKI first', 'info');
if (route.name !== 'PKIConfig') router.push('/config/pki');
};
const handleLogout = () => {
localStorage.removeItem('ovpmon_token');
localStorage.removeItem('ovpmon_user');
@@ -181,13 +199,19 @@ const refreshPage = () => {
// Close sidebar on route change
watch(() => route.path, () => {
isSidebarOpen.value = false;
if (route.name !== 'Login') syncUsername();
if (route.name !== 'Login') {
syncUsername();
refreshPkiStatus();
}
});
onMounted(async () => {
await loadConfig();
window.addEventListener('ovpmon-user-changed', onUserChanged);
if (route.name !== 'Login') syncUsername();
if (route.name !== 'Login') {
syncUsername();
refreshPkiStatus();
}
// Init Theme
const savedTheme = localStorage.getItem('theme') || 'light';
+204 -25
View File
@@ -253,6 +253,16 @@ body {
flex-shrink: 0;
}
/* Section locked until the PKI is initialized */
.nav-link-locked {
opacity: 0.45;
cursor: not-allowed;
}
.nav-link-locked:hover {
opacity: 0.6;
}
.nav-section-header {
padding: 15px 15px 5px 15px;
font-size: 0.75rem;
@@ -1616,42 +1626,169 @@ input[type="number"].config-input {
appearance: textfield;
}
/* Messages / Toast */
.toast-message {
padding: 14px 22px;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
margin-bottom: 20px;
/* Toast notifications (ToastContainer.vue) */
:root {
--toast-success: #1a7f37;
--toast-warning: #9a6700;
--toast-error: #cf222e;
--toast-info: #0969da;
--toast-shadow: 0 8px 24px rgba(31, 35, 40, 0.14), 0 1px 3px rgba(31, 35, 40, 0.08);
}
[data-theme="dark"] {
--toast-success: #3fb950;
--toast-warning: #d29922;
--toast-error: #f85149;
--toast-info: #58a6ff;
--toast-shadow: 0 8px 24px rgba(1, 4, 9, 0.6), 0 0 0 1px rgba(240, 246, 252, 0.04);
}
.toast-stack {
position: fixed;
right: 20px;
bottom: 20px;
z-index: 2000; /* above Bootstrap modals (1055) and backdrop (1050) */
width: 380px;
max-width: calc(100vw - 32px);
pointer-events: none;
}
.toast-stack-list {
position: relative;
display: flex;
align-items: center;
flex-direction: column;
gap: 10px;
}
.app-toast {
--toast-color: var(--toast-info);
position: relative;
display: flex;
align-items: flex-start;
gap: 12px;
width: 100%;
padding: 12px 10px 14px 14px;
overflow: hidden;
background: var(--bg-card);
border: 1px solid var(--border-color);
border-left: 4px solid var(--toast-color);
border-radius: 8px;
box-shadow: var(--toast-shadow);
color: var(--text-main);
font-size: 14px;
line-height: 1.45;
pointer-events: auto;
}
.app-toast-success { --toast-color: var(--toast-success); }
.app-toast-warning { --toast-color: var(--toast-warning); }
.app-toast-error { --toast-color: var(--toast-error); }
.app-toast-info { --toast-color: var(--toast-info); }
.app-toast-icon {
flex: 0 0 auto;
margin-top: 2px;
font-size: 16px;
color: var(--toast-color);
}
.app-toast-text {
flex: 1 1 auto;
min-width: 0;
color: var(--text-heading);
font-weight: 500;
overflow-wrap: anywhere;
word-break: break-word;
}
.app-toast-close {
flex: 0 0 auto;
width: 24px;
height: 24px;
padding: 0;
display: inline-flex;
align-items: center;
justify-content: center;
background: transparent;
border: 0;
border-radius: 4px;
color: var(--text-muted);
font-size: 12px;
cursor: pointer;
transition: background-color 0.15s ease, color 0.15s ease;
}
.app-toast-close:hover,
.app-toast-close:focus-visible {
background: var(--bg-element-hover);
color: var(--text-heading);
}
.app-toast-progress {
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 3px;
background: var(--toast-color);
opacity: 0.55;
transform-origin: left center;
animation: toast-progress linear forwards;
}
.app-toast:hover .app-toast-progress {
animation-play-state: paused;
}
@keyframes toast-progress {
from { transform: scaleX(1); }
to { transform: scaleX(0); }
}
.toast-enter-active,
.toast-leave-active {
transition: transform 0.28s ease, opacity 0.28s ease;
}
.toast-leave-active {
position: absolute; /* keeps its place while siblings slide into the gap */
}
.toast-move {
transition: transform 0.28s ease;
}
.toast-enter-from {
opacity: 0;
transform: translateY(-10px);
transition: all 0.3s ease;
transform: translateX(40px);
}
.toast-message.show {
opacity: 1;
transform: translateY(0);
.toast-leave-to {
opacity: 0;
transform: translateX(20px);
}
.toast-success {
background-color: #d1fae5;
color: #065f46;
border-left: 4px solid #10b981;
@media (max-width: 576px) {
.toast-stack {
right: 16px;
left: 16px;
bottom: 16px;
width: auto;
max-width: none;
}
}
.toast-warning {
background-color: #fef3c7;
color: #92400e;
border-left: 4px solid #f59e0b;
@media (prefers-reduced-motion: reduce) {
.toast-enter-active,
.toast-leave-active,
.toast-move {
transition: opacity 0.15s ease;
}
.toast-error {
background-color: #fee2e2;
color: #991b1b;
border-left: 4px solid #ef4444;
.toast-enter-from,
.toast-leave-to {
transform: none;
}
}
/* Animations */
@@ -1802,6 +1939,48 @@ input[type="number"].config-input {
transform: scale(1.02);
}
/* Profile note tooltip (v-note-tooltip) */
.note-tooltip {
--bs-tooltip-max-width: 320px;
--bs-tooltip-bg: var(--bg-card);
--bs-tooltip-color: var(--text-main);
--bs-tooltip-opacity: 1;
}
.note-tooltip .tooltip-inner {
max-width: 320px;
white-space: pre-wrap;
text-align: left;
word-break: break-word;
background-color: var(--bg-card);
color: var(--text-main);
border: 1px solid var(--border-color);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
.note-tooltip .tooltip-arrow::before {
border-top-color: var(--border-color);
}
/* Compact label : value list (profile details modal) */
.profile-meta {
display: grid;
grid-template-columns: 5.5rem 1fr;
gap: 0.25rem 0.75rem;
margin: 0 0 1rem;
font-size: 0.9rem;
}
.profile-meta dt {
font-weight: 600;
color: var(--text-muted);
}
.profile-meta dd {
margin: 0;
text-align: left;
}
/* Shared Utilities */
.cursor-pointer {
cursor: pointer;
@@ -0,0 +1,86 @@
<template>
<BaseModal id="profileDetailsModal" title="Profile Details" ref="modal">
<template #header>
<div class="d-flex align-items-center gap-2 flex-wrap">
<h5 class="modal-title fw-bold mb-0" style="color: var(--text-heading);">{{ profile?.username }}</h5>
<span v-if="profile" class="status-badge" :class="status.cls">{{ status.label }}</span>
</div>
</template>
<template #body>
<div v-if="profile">
<dl class="profile-meta">
<dt>Created</dt>
<dd>{{ formatDate(profile.created_at) }}</dd>
<dt>Expires</dt>
<dd>{{ formatDate(profile.expiration_date) }}<span v-if="daysLabel" class="text-muted"> ({{ daysLabel }})</span></dd>
<template v-if="profile.revoked_at">
<dt>Revoked</dt>
<dd>{{ formatDate(profile.revoked_at) }}</dd>
</template>
<dt>File</dt>
<dd class="certificate-file text-muted small text-break mt-0">{{ profile.file_path || 'N/A' }}</dd>
</dl>
<label for="profileNote" class="form-label small text-muted text-uppercase fw-bold">Note</label>
<textarea class="form-control" id="profileNote" rows="3" maxlength="1000" v-model="note" placeholder="Add a note about this profile..."></textarea>
<div class="form-text text-end">{{ note.length }} / 1000</div>
</div>
</template>
<template #footer>
<button type="button" class="btn-action btn-action-secondary" @click="close">Close</button>
<button type="button" class="btn-action btn-action-save" @click="save" :disabled="!dirty">Save</button>
</template>
</BaseModal>
</template>
<script setup>
import { ref, computed } from 'vue';
import BaseModal from './BaseModal.vue';
const emit = defineEmits(['save']);
const modal = ref(null);
const profile = ref(null);
const note = ref('');
const dirty = computed(() => note.value !== (profile.value?.note || ''));
const status = computed(() => {
const p = profile.value;
if (p?.is_revoked) return { label: 'Revoked', cls: 'status-expired' };
if (p?.is_expired) return { label: 'Expired', cls: 'status-expired' };
if (p?.days_remaining != null && p.days_remaining <= 30) return { label: 'Expiring Soon', cls: 'status-warning' };
return { label: 'Active', cls: 'status-valid' };
});
const daysLabel = computed(() => {
const days = profile.value?.days_remaining;
if (days == null) return '';
return days > 0 ? `${days} d` : 'expired';
});
// YYYY-MM-DD HH:mm (local time)
const formatDate = (dateStr) => {
if (!dateStr) return 'N/A';
const d = new Date(dateStr);
if (isNaN(d)) return dateStr;
const pad = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
};
const open = (p) => {
profile.value = p;
note.value = p.note || '';
modal.value.show();
};
const close = () => {
modal.value.hide();
};
const save = () => {
emit('save', { id: profile.value.id, note: note.value });
close();
};
defineExpose({ open, close });
</script>
+33
View File
@@ -0,0 +1,33 @@
<template>
<div class="toast-stack">
<TransitionGroup name="toast" tag="div" class="toast-stack-list">
<div v-for="t in toasts" :key="t.id" class="app-toast" :class="'app-toast-' + t.type"
:role="t.type === 'error' ? 'alert' : 'status'"
:aria-live="t.type === 'error' ? 'assertive' : 'polite'" aria-atomic="true"
@mouseenter="pause(t.id)" @mouseleave="resume(t.id)">
<i class="fas app-toast-icon" :class="ICONS[t.type]" aria-hidden="true"></i>
<div class="app-toast-text">{{ t.text }}</div>
<button type="button" class="app-toast-close" aria-label="Close notification" @click="dismiss(t.id)">
<i class="fas fa-times" aria-hidden="true"></i>
</button>
<div v-if="t.timeout > 0" class="app-toast-progress" :style="{ animationDuration: t.timeout + 'ms' }"></div>
</div>
</TransitionGroup>
</div>
</template>
<script setup>
import { onBeforeUnmount } from 'vue';
import { useToast } from '../composables/useToast';
const { toasts, dismiss, pause, resume, clear } = useToast();
const ICONS = {
success: 'fa-check-circle',
warning: 'fa-exclamation-triangle',
error: 'fa-exclamation-circle',
info: 'fa-info-circle'
};
onBeforeUnmount(clear);
</script>
+28
View File
@@ -0,0 +1,28 @@
import { reactive } from 'vue';
import { useApi } from './useApi';
// Module-level state: sidebar, router guard and views share one PKI status.
// Optimistic defaults: nothing is locked until the first answer from GET /system/init/status.
const status = reactive({ pki_ready: true, server_ready: true, missing: [], state: 'idle' });
// Returns true when the status was updated. Safe on errors (keeps the previous values), and does
// nothing without a session, so the Login page never calls the API.
const refresh = async () => {
if (!localStorage.getItem('ovpmon_token')) return false;
try {
const { profilesApiClient } = useApi();
const res = await profilesApiClient.get('/system/init/status');
const d = res.data || {};
status.pki_ready = d.pki_ready !== false;
status.server_ready = d.server_ready !== false;
status.missing = d.missing || [];
status.state = d.state || 'idle';
return true;
} catch (e) {
return false;
}
};
export function usePkiStatus() {
return { status, refresh };
}
+64
View File
@@ -0,0 +1,64 @@
import { reactive } from 'vue';
const MAX_VISIBLE = 4;
const DEFAULT_TIMEOUT = 5000;
const ERROR_TIMEOUT = 8000;
// Module-level state: every caller (views, ToastContainer) shares the same list
const toasts = reactive([]);
const timers = new Map(); // id -> { handle, startedAt, remaining }
let nextId = 1;
const clearTimer = (id) => {
const t = timers.get(id);
if (t) clearTimeout(t.handle);
timers.delete(id);
};
const dismiss = (id) => {
clearTimer(id);
const idx = toasts.findIndex((t) => t.id === id);
if (idx !== -1) toasts.splice(idx, 1);
};
const startTimer = (id, ms) => {
clearTimer(id);
timers.set(id, { handle: setTimeout(() => dismiss(id), ms), startedAt: Date.now(), remaining: ms });
};
// Stop the countdown (mouse over the toast); the progress bar is paused by CSS
const pause = (id) => {
const t = timers.get(id);
if (!t) return;
clearTimeout(t.handle);
t.remaining = Math.max(0, t.remaining - (Date.now() - t.startedAt));
t.handle = null;
};
const resume = (id) => {
const t = timers.get(id);
if (!t || t.handle !== null) return;
startTimer(id, t.remaining);
};
const show = (text, type = 'success', timeout) => {
const kind = ['success', 'warning', 'error', 'info'].includes(type) ? type : 'info';
const duration = timeout ?? (kind === 'error' ? ERROR_TIMEOUT : DEFAULT_TIMEOUT);
const id = nextId++;
toasts.push({ id, text: String(text ?? ''), type: kind, timeout: duration });
while (toasts.length > MAX_VISIBLE) dismiss(toasts[0].id);
if (duration > 0) startTimer(id, duration);
return id;
};
// Drop everything and release all timers (container unmount)
const clear = () => {
timers.forEach((t) => clearTimeout(t.handle));
timers.clear();
toasts.splice(0, toasts.length);
};
export function useToast() {
return { toasts, show, dismiss, pause, resume, clear };
}
+37
View File
@@ -0,0 +1,37 @@
import { Tooltip } from 'bootstrap';
// v-note-tooltip="text": Bootstrap tooltip with the profile note.
// No tooltip for an empty value; plain text only (html: false).
const create = (el, text) => {
el._noteTooltip = new Tooltip(el, {
title: text,
placement: 'top',
container: 'body',
html: false,
trigger: 'hover',
customClass: 'note-tooltip'
});
};
const destroy = (el) => {
el._noteTooltip?.dispose();
el._noteTooltip = null;
};
// Hide on click: the row click opens the details modal
const hideOnClick = (el) => el._noteTooltip?.hide();
export default {
mounted(el, binding) {
el.addEventListener('click', () => hideOnClick(el));
if (binding.value) create(el, binding.value);
},
updated(el, binding) {
if (binding.value === binding.oldValue) return;
destroy(el);
if (binding.value) create(el, binding.value);
},
unmounted(el) {
destroy(el);
}
};
+15 -2
View File
@@ -1,6 +1,8 @@
import { createRouter, createWebHistory } from 'vue-router';
import Clients from '../views/Clients.vue';
import Login from '../views/Login.vue';
import { usePkiStatus } from '../composables/usePkiStatus';
import { useToast } from '../composables/useToast';
const routes = [
{
@@ -27,7 +29,8 @@ const routes = [
{
path: '/config/vpn',
name: 'VPNConfig',
component: () => import('../views/VPNConfig.vue')
component: () => import('../views/VPNConfig.vue'),
meta: { requiresPki: true }
},
{
path: '/server',
@@ -52,13 +55,23 @@ const router = createRouter({
routes
});
router.beforeEach((to, from, next) => {
router.beforeEach(async (to, from, next) => {
const isAuthenticated = !!localStorage.getItem('ovpmon_token');
if (!to.meta.public && !isAuthenticated) {
next({ name: 'Login' });
} else if (to.name === 'Login' && isAuthenticated) {
next({ name: 'Analytics' });
} else if (to.meta.requiresPki) {
// A failed status request does not block navigation: the backend still enforces the rule
const { status, refresh } = usePkiStatus();
const ok = await refresh();
if (ok && !status.pki_ready) {
useToast().show('Initialize PKI before configuring the server', 'warning');
next({ name: 'PKIConfig' });
} else {
next();
}
} else {
next();
}
+41 -23
View File
@@ -24,7 +24,8 @@
<span class="input-group-text"><i class="fas fa-search"></i></span>
<input type="text" class="form-control" placeholder="Search by client name..." v-model="searchQuery">
</div>
<button class="btn-action btn-action-save btn-sm" @click="showNewClientModal">
<button class="btn-action btn-action-save btn-sm" @click="showNewClientModal"
:disabled="!pkiStatus.pki_ready" :title="pkiStatus.pki_ready ? '' : 'Initialize PKI first'">
<i class="fas fa-plus me-1"></i> New Client
</button>
</div>
@@ -88,9 +89,12 @@
<tr v-if="activeCerts.length > 0" class="section-divider">
<td colspan="6">Active Certificates ({{ activeCerts.length }})</td>
</tr>
<tr v-for="cert in activeCerts" :key="cert.id + '_active'">
<td>
<div class="fw-semibold" style="color: var(--text-heading);">{{ cert.username }}</div>
<tr v-for="cert in activeCerts" :key="cert.id + '_active'" style="cursor: pointer;" @click="showDetails(cert)">
<td v-note-tooltip="cert.note">
<div class="fw-semibold" style="color: var(--text-heading);">
{{ cert.username }}
<i v-if="cert.note" class="fas fa-note-sticky text-muted ms-1 small"></i>
</div>
<div class="certificate-file text-muted small">{{ cert.file_path || 'N/A' }}</div>
</td>
<td><span class="status-badge status-client">Client</span></td>
@@ -100,10 +104,10 @@
</td>
<td v-html="getStatusBadgeHTML(cert)"></td>
<td>
<button class="btn btn-sm btn-link text-warning p-0 me-2" title="Download Config" @click="downloadConfig(cert)">
<button class="btn btn-sm btn-link text-warning p-0 me-2" title="Download Config" @click.stop="downloadConfig(cert)">
<i class="fas fa-download"></i>
</button>
<button class="btn btn-sm btn-link text-danger p-0" title="Revoke" @click="revokeClient(cert)">
<button class="btn btn-sm btn-link text-danger p-0" title="Revoke" @click.stop="revokeClient(cert)">
<i class="fas fa-ban"></i>
</button>
</td>
@@ -114,9 +118,12 @@
<tr class="section-divider">
<td colspan="6">Expired / Revoked ({{ expiredCerts.length }})</td>
</tr>
<tr v-for="cert in expiredCerts" :key="cert.id + '_expired'">
<td>
<div class="fw-semibold" style="color: var(--text-heading);">{{ cert.username }}</div>
<tr v-for="cert in expiredCerts" :key="cert.id + '_expired'" style="cursor: pointer;" @click="showDetails(cert)">
<td v-note-tooltip="cert.note">
<div class="fw-semibold" style="color: var(--text-heading);">
{{ cert.username }}
<i v-if="cert.note" class="fas fa-note-sticky text-muted ms-1 small"></i>
</div>
<div class="certificate-file text-muted small">{{ cert.file_path || 'N/A' }}</div>
</td>
<td><span class="status-badge status-client">Client</span></td>
@@ -126,7 +133,7 @@
</td>
<td v-html="getStatusBadgeHTML(cert)"></td>
<td>
<button class="btn btn-sm btn-link text-danger p-0" title="Revoke" @click="revokeClient(cert)" :disabled="cert.is_revoked">
<button class="btn btn-sm btn-link text-danger p-0" title="Revoke" @click.stop="revokeClient(cert)" :disabled="cert.is_revoked">
<i class="fas fa-ban"></i>
</button>
</td>
@@ -140,11 +147,7 @@
<NewClientModal ref="newClientModal" @create="createClient" />
<ConfirmModal ref="confirmModal" @confirm="confirmRevoke" />
<div v-if="toastMessage" class="toast-message show" :class="'toast-' + toastType" style="position: fixed; bottom: 20px; right: 20px; z-index: 9999;">
<i class="fas" :class="toastType === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'"></i>
{{ toastMessage }}
</div>
<ProfileDetailsModal ref="detailsModal" @save="saveNote" />
</template>
<script setup>
@@ -152,8 +155,14 @@ import { ref, computed, onMounted } from 'vue';
import { useApi } from '../composables/useApi';
import NewClientModal from '../components/NewClientModal.vue';
import ConfirmModal from '../components/ConfirmModal.vue';
import ProfileDetailsModal from '../components/ProfileDetailsModal.vue';
import vNoteTooltip from '../directives/noteTooltip';
import { useToast } from '../composables/useToast';
import { usePkiStatus } from '../composables/usePkiStatus';
const { profilesApiClient } = useApi();
const toast = useToast();
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
const loading = ref(true);
const allProfiles = ref([]);
@@ -162,14 +171,8 @@ const hideExpired = ref(false);
const newClientModal = ref(null);
const confirmModal = ref(null);
const toastMessage = ref('');
const toastType = ref('success');
const showToast = (msg, type = 'success') => {
toastMessage.value = msg;
toastType.value = type;
setTimeout(() => toastMessage.value = '', 3000);
};
const detailsModal = ref(null);
const showToast = (msg, type = 'success') => toast.show(msg, type);
const formatDate = (dateStr) => {
if (!dateStr) return 'N/A';
@@ -276,6 +279,20 @@ const createClient = async (username) => {
}
};
const showDetails = (cert) => {
detailsModal.value.open(cert);
};
const saveNote = async ({ id, note }) => {
try {
await profilesApiClient.put(`/profiles/${id}/note`, { note });
showToast('Note saved.', 'success');
loadCerts();
} catch(e) {
showToast(e.response?.data?.detail || e.message, 'error');
}
};
const downloadConfig = async (cert) => {
if (!cert.id) return;
try {
@@ -325,6 +342,7 @@ const confirmRevoke = async (cert) => {
};
onMounted(() => {
refreshPkiStatus();
loadCerts();
});
</script>
+78 -30
View File
@@ -5,10 +5,6 @@
<h1>PKI Infrastructure Configuration</h1>
</div>
<div v-if="message.text" :class="['toast-message', 'toast-' + message.type, 'show']">
<i :class="['fas', message.icon]"></i> {{ message.text }}
</div>
<form @submit.prevent="handleSave">
<div class="config-row">
<div class="config-col">
@@ -149,21 +145,23 @@
<div class="btn-action-group">
<button type="button" class="btn-action btn-action-save" @click="handleSave" :disabled="isLoading">
<button type="button" class="btn-action btn-action-save" @click="handleSave" :disabled="isBusy">
<i class="fas fa-save"></i>
Save PKI
</button>
<button type="button" class="btn-action btn-action-primary" @click="handleInit" :disabled="isLoading">
<i v-if="isLoading && action==='init'" class="fas fa-spinner fa-spin"></i>
<button type="button" class="btn-action btn-action-primary" @click="handleInit" :disabled="isBusy || initStatus.initialized"
:title="initStatus.initialized ? 'PKI is already initialized. Use Clear PKI to start over' : ''">
<i v-if="isInitRunning" class="fas fa-spinner fa-spin"></i>
<i v-else class="fas fa-play-circle"></i>
Init PKI
</button>
<button type="button" class="btn-action btn-action-danger" @click="handleClear" :disabled="isLoading">
<button type="button" class="btn-action btn-action-danger" @click="handleClear" :disabled="isBusy">
<i v-if="isLoading && action==='clear'" class="fas fa-spinner fa-spin"></i>
<i v-else class="fas fa-trash-alt"></i>
Clear PKI
</button>
</div>
<div v-if="isInitRunning" class="config-label">{{ stepText }}</div>
</form>
</div>
@@ -171,11 +169,15 @@
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ref, computed, onMounted, onUnmounted, reactive } from 'vue';
import { useApi } from '../composables/useApi';
import { useToast } from '../composables/useToast';
import { usePkiStatus } from '../composables/usePkiStatus';
const { profilesApiClient } = useApi();
const toast = useToast();
const { refresh: refreshPkiStatus } = usePkiStatus();
// State
const form = reactive({
@@ -196,26 +198,28 @@ const form = reactive({
easyrsa_batch: true
});
const message = reactive({
text: '',
type: 'success', // success, warning, error (mapped to css classes)
icon: 'fa-check-circle'
});
const isLoading = ref(false);
const action = ref(''); // 'save', 'init', 'clear'
// Methods
const showMessage = (text, type = 'success') => {
message.text = text;
message.type = type;
message.icon = type === 'success' ? 'fa-check-circle' : type === 'warning' ? 'fa-exclamation-triangle' : 'fa-exclamation-circle';
// PKI init job state, taken from the server (GET /system/init/status)
const initStatus = reactive({ state: 'idle', step: null, initialized: false, error: null });
const isInitRunning = computed(() => initStatus.state === 'running' || action.value === 'init');
const isBusy = computed(() => isLoading.value || isInitRunning.value);
// Auto hide
setTimeout(() => {
message.text = '';
}, 4000);
const STEP_TEXTS = {
'init-pki': 'Initializing PKI...',
'ca': 'Building CA...',
'server-cert': 'Building server certificate...',
'dh': 'Generating DH parameters (this can take several minutes)...',
'ta-key': 'Generating TLS key...',
'crl': 'Generating CRL...'
};
const stepText = computed(() => STEP_TEXTS[initStatus.step] || 'Initializing PKI...');
let pollTimer = null;
// Methods
const showMessage = (text, type = 'success') => toast.show(text, type);
// API Fetch Wrapper
// API Wrapper removed, using profilesApiClient directly
@@ -238,6 +242,40 @@ const loadConfig = async () => {
}
};
const stopPolling = () => {
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
};
const startPolling = () => {
if (!pollTimer) pollTimer = setInterval(() => loadStatus(), 3000);
};
const loadStatus = async (initial = false) => {
const wasRunning = initStatus.state === 'running';
try {
const res = await profilesApiClient.get('/system/init/status');
Object.assign(initStatus, res.data);
} catch (err) {
console.error(err);
return; // keep polling, the next tick may succeed
}
if (initStatus.state === 'running') {
startPolling();
return;
}
stopPolling();
if (wasRunning) refreshPkiStatus(); // unlock the sidebar without a reload
// Report the result once: a job seen running on this page, or a failure found on page load
if (wasRunning && initStatus.state === 'done') {
showMessage('PKI initialized successfully!', 'success');
} else if ((wasRunning || initial) && initStatus.state === 'error') {
showMessage(`Error initializing: ${initStatus.error}`, 'error');
}
};
const handleSave = async () => {
isLoading.value = true;
action.value = 'save';
@@ -256,13 +294,18 @@ const handleInit = async () => {
if (!confirm('Are you sure you want to Initialize system? This will start the PKI initialization process.')) return;
isLoading.value = true;
action.value = 'init';
action.value = 'init'; // locks the button until the server confirms the job state
try {
const res = await profilesApiClient.post('/system/init');
const data = res.data;
showMessage(data.message || 'System initialized successfully!', 'success');
await profilesApiClient.post('/system/init');
initStatus.state = 'running'; // 202: the job is running in the background
startPolling();
} catch (err) {
showMessage(`Error initializing: ${err.message}`, 'error');
if (err.response && err.response.status === 409) {
// Already running (second tab) or already initialized: attach to the server state
await loadStatus();
} else {
showMessage(`Error initializing: ${err.response?.data?.detail || err.message}`, 'error');
}
} finally {
isLoading.value = false;
action.value = '';
@@ -278,8 +321,10 @@ const handleClear = async () => {
const res = await profilesApiClient.delete('/system/pki');
const data = res.data;
showMessage(data.message || 'PKI cleared successfully!', 'warning');
await loadStatus();
refreshPkiStatus();
} catch (err) {
showMessage(`Error clearing PKI: ${err.message}`, 'error');
showMessage(`Error clearing PKI: ${err.response?.data?.detail || err.message}`, 'error');
} finally {
isLoading.value = false;
action.value = '';
@@ -288,5 +333,8 @@ const handleClear = async () => {
onMounted(() => {
loadConfig();
loadStatus(true);
});
onUnmounted(stopPolling);
</script>
+19 -22
View File
@@ -5,10 +5,6 @@
<h1>Server Process Management</h1>
</div>
<div v-if="message.text" :class="['toast-message', 'toast-' + message.type, 'show']">
<i :class="['fas', message.icon]"></i> {{ message.text }}
</div>
<!-- Stats Grid -->
<!-- User requested specific order: CPU (full), Status, PID, Memory, Uptime -->
@@ -60,7 +56,8 @@
<!-- Start -->
<button type="button" class="btn-action btn-action-primary"
@click="handleControl('start')"
:disabled="isLoading || stats.status === 'running'">
:disabled="isLoading || stats.status === 'running' || !pkiStatus.server_ready"
:title="startHint">
<i v-if="isLoading && action==='start'" class="fas fa-spinner fa-spin"></i>
<i v-else class="fas fa-play"></i>
Start Service
@@ -69,7 +66,8 @@
<!-- Restart -->
<button type="button" class="btn-action btn-action-save"
@click="handleControl('restart')"
:disabled="isLoading">
:disabled="isLoading || !pkiStatus.server_ready"
:title="startHint">
<i v-if="isLoading && action==='restart'" class="fas fa-spinner fa-spin"></i>
<i v-else class="fas fa-sync-alt"></i>
Restart Service
@@ -90,10 +88,22 @@
</template>
<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { useApi } from '../composables/useApi';
import { useToast } from '../composables/useToast';
import { usePkiStatus } from '../composables/usePkiStatus';
const { profilesApiClient } = useApi();
const toast = useToast();
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
// Start/Restart need the PKI server files (Stop stays available)
const startHint = computed(() => {
if (pkiStatus.server_ready) return '';
return pkiStatus.pki_ready && pkiStatus.missing.length
? `Missing server files: ${pkiStatus.missing.join(', ')}`
: 'Initialize PKI first';
});
// State
const stats = reactive({
@@ -104,26 +114,12 @@ const stats = reactive({
uptime: null
});
const message = reactive({
text: '',
type: 'success',
icon: 'fa-check-circle'
});
const isLoading = ref(false);
const action = ref(''); // 'start', 'stop', 'restart'
let pollInterval = null;
// Methods
const showMessage = (text, type = 'success') => {
message.text = text;
message.type = type;
message.icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
setTimeout(() => {
message.text = '';
}, 4000);
};
const showMessage = (text, type = 'success') => toast.show(text, type);
const fetchStats = async () => {
try {
@@ -157,6 +153,7 @@ const handleControl = async (cmd) => {
};
onMounted(() => {
refreshPkiStatus();
fetchStats();
// Poll every 5 seconds
pollInterval = setInterval(fetchStats, 5000);
+17 -16
View File
@@ -1,12 +1,17 @@
<template>
<div class="config-wrapper">
<div class="config-card">
<!-- PKI cleared while the page is open (e.g. in another tab) -->
<div v-if="!pkiStatus.pki_ready" class="config-card">
<div class="config-header">
<h1>Server Infrastructure Configuration</h1>
</div>
<p><i class="fas fa-lock me-2"></i>The server cannot be configured until the PKI is initialized.</p>
<router-link to="/config/pki">Go to PKI configuration</router-link>
</div>
<div v-if="message.text" :class="['toast-message', 'toast-' + message.type, 'show']">
<i :class="['fas', message.icon]"></i> {{ message.text }}
<div v-else class="config-card">
<div class="config-header">
<h1>Server Infrastructure Configuration</h1>
</div>
<form @submit.prevent="handleSave">
@@ -257,8 +262,12 @@
<script setup>
import { ref, onMounted, reactive, watch } from 'vue';
import { useApi } from '../composables/useApi';
import { useToast } from '../composables/useToast';
import { usePkiStatus } from '../composables/usePkiStatus';
const { profilesApiClient } = useApi();
const toast = useToast();
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
// State
const form = reactive({
@@ -285,11 +294,6 @@ const form = reactive({
const isSplitTunnel = ref(false);
const message = reactive({
text: '',
type: 'success',
icon: 'fa-check-circle'
});
const isLoading = ref(false);
const action = ref('');
@@ -309,12 +313,7 @@ function maskToCidr(mask) {
}
// Methods
const showMessage = (text, type = 'success') => {
message.text = text;
message.type = type;
message.icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
setTimeout(() => message.text = '', 5000);
};
const showMessage = (text, type = 'success') => toast.show(text, type);
const addRoute = () => form.split_routes.push('');
const removeRoute = (idx) => form.split_routes.splice(idx, 1);
@@ -368,7 +367,7 @@ const handleSave = async () => {
await profilesApiClient.put('/config/server', payload);
showMessage('Server configuration saved!', 'success');
} catch (err) {
showMessage(`Error saving: ${err.message}`, 'error');
showMessage(`Error saving: ${err.response?.data?.detail || err.message}`, 'error');
} finally {
isLoading.value = false;
action.value = '';
@@ -383,7 +382,8 @@ const handleApply = async () => {
const data = res.data;
showMessage(data.message || 'Configuration applied!', 'success');
} catch (err) {
showMessage(`Error applying: ${err.message}`, 'error');
showMessage(`Error applying: ${err.response?.data?.detail || err.message}`, 'error');
refreshPkiStatus();
} finally {
isLoading.value = false;
action.value = '';
@@ -391,6 +391,7 @@ const handleApply = async () => {
};
onMounted(() => {
refreshPkiStatus();
loadConfig();
});
</script>
+35
View File
@@ -0,0 +1,35 @@
# Async PKI initialization (2026-10-04)
Goal: `Init PKI` can take minutes (DH parameters); it no longer holds an HTTP request. Plan: [Async_PKI_Init_PLAN](2026-10-04_Async_PKI_Init_PLAN.md).
## Changes
| Area | Change |
|---|---|
| API (`APP_PROFILER/routers/system.py`) | `POST /system/init` returns `202 {"state":"running"}` and runs the init in a background thread; `409` if a job is running or the PKI is initialized. New `GET /system/init/status` (`state`, `step`, `initialized`, `started_at`, `finished_at`, `error`). `DELETE /system/pki` and `POST /profiles` return `409` while a job is running |
| Service (`APP_PROFILER/services/pki.py`) | In-memory job state under a lock; the thread uses its own DB session; steps `init-pki`, `ca`, `server-cert`, `dh`, `ta-key`, `crl`; EasyRSA error text is stored in `error` |
| Interrupted runs | A marker file `<easy-rsa>/.pki-init-in-progress` (outside the PKI directory) exists while a job runs and is removed on success. A leftover marker (restart, crash, failed job) means the PKI is incomplete: it is wiped and rebuilt on the next Init. A PKI without the marker and with `ca.crt` counts as initialized and is **never** wiped automatically |
| UI (`APP_UI/src/views/PKIConfig.vue`) | State comes from the server on page load; spinner and step text while running, polling every 3 s; Init, Clear and Save disabled while running; Init disabled with a hint once initialized; success or error message at the end; a `409` on start attaches to the running job; the button locks on click |
| Docs | `DOCS/Profiler_Management/API_Reference.md` |
| Test | `APP_PROFILER/test_async_pki_init.py` (one test with EasyRSA stubs): 202, second start 409, status `running`, Clear 409, then `done` and a further start 409 |
## Verification (containers)
| Check | Result |
|---|---|
| `pytest test_async_pki_init.py` and `test_profile_note.py` in `python:3.12-alpine` | 2 passed |
| Existing complete PKI | status `initialized: true`, Init is a no-op |
| Clear, then Init | `202`, second start `409`, steps `init-pki` → `dh` → `done` (3 s and 54 s in two runs) |
| Partial PKI with the marker (simulated interrupted run) | wiped, rebuilt, marker removed, `initialized: true` |
| Create a client during the run / after it | `409` / `200` |
| UI bundle | `app-ui` builds and contains the status polling; the page behaviour is checked manually |
## Notes
- The Profiler must run as a single process (in-memory job state): `python main.py` in Docker, one `uvicorn` in the native unit. Do not add workers.
- Initialization is not cancelled by a page reload; the page reattaches to the running job.
- Not implemented: cancelling a run, progress percentage, async Clear PKI.
## Existing installations
No manual steps. Rebuild and restart the Profiler (native: `ovpmon-profiler`; Docker: `app-profiler`, `app-ui`). An already initialized PKI is detected as before.
@@ -0,0 +1,46 @@
# Async PKI initialization: implementation plan (2026-10-04)
Goal: `Init PKI` can take minutes (DH parameters). Run it in the background; the PKI Configuration page shows progress, survives a page reload and prevents a second start.
## Current state
- `POST /system/init` (`APP_PROFILER/routers/system.py`) runs `pki.init_pki()` synchronously: init-pki, build-ca, server cert, gen-dh, ta.key, gen-crl, CRL publish. The HTTP request stays open until it ends.
- `pki.init_pki()` treats the PKI as initialized if `ca.crt` exists, so a PKI interrupted after the CA step (restart, crash) would be reported as ready.
- `PKIConfig.vue`: `isLoading` is local to the page, so a reload loses the state and the button becomes active again.
- The Profiler runs as a single process (`python main.py` in Docker, one `uvicorn` in the native unit), so in-memory job state is valid.
## Steps
### 1. Backend (`APP_PROFILER/`)
- `services/pki.py`
- `is_initialized()`: true only when the PKI is complete (`ca.crt`, `dh.pem`, `ta.key`, `crl.pem` and the server certificate exist). Existing complete PKIs are detected without migration.
- Job state `init_job` (module level, guarded by a lock): `state` = `idle | running | done | error`, `step` (init-pki, CA, server certificate, DH, TLS key, CRL), `started_at`, `finished_at`, `error`.
- `start_init_async()`: refuses to start when a job is running or the PKI is complete; removes an incomplete PKI left by an interrupted run; starts a daemon thread with its **own** DB session; the thread updates `step` and ends in `done` or `error` (error text from EasyRSA, no secrets).
- `routers/system.py`
- `POST /system/init` returns `202 {"state": "running"}` immediately; `409` if a job is running or the PKI is already initialized.
- `GET /system/init/status` returns `{state, step, initialized, started_at, finished_at, error}`.
- `DELETE /system/pki` returns `409` while an init job is running.
- `POST /profiles` returns `409` while an init job is running (the PKI is not complete).
- After an application restart the state is `idle`; an interrupted PKI is reported as `initialized: false`, and Init PKI cleans it up and starts again.
### 2. UI (`APP_UI/src/views/PKIConfig.vue`)
- On mount call `GET /system/init/status`; state is taken from the server, not from the page.
- `running`: spinner on the Init PKI button, the current step text ("Generating DH parameters..."), polling every 3 s, Init / Clear / Save disabled.
- `done` or `initialized: true`: Init PKI is disabled with the hint "PKI is already initialized. Use Clear PKI to start over"; a success message is shown once when the job finishes while the page is open.
- `error`: error message, Init PKI is enabled again.
- After Clear PKI the status is reloaded and the button is enabled again.
- A double click or a second tab cannot start a second job (button locked immediately on click, backend answers `409` anyway; the UI treats `409 running` as "attach to the running job").
- Polling stops on unmount.
### 3. Tests (minimal)
- One pytest in `APP_PROFILER`: with the EasyRSA steps replaced by fast stubs, `POST /system/init` returns `202`, a second `POST` returns `409`, `GET /system/init/status` ends in `done` and `initialized: true`, a third `POST` returns `409`. No UI tests.
### 4. Verification (containers, stand `ovpmon-test`, port 8089)
- Rebuild `app-profiler` and `app-ui`. Clear PKI, press Init PKI: spinner appears, the page can be reloaded and still shows progress, buttons are locked, the result appears on completion, Init PKI stays locked afterwards, Clear PKI unlocks it.
- Restart `ovp-profiler` during the run: status is `idle` and `initialized: false`, Init PKI cleans up and completes.
- Existing PKI from the current stand is detected as initialized.
### 5. Documentation
- `DOCS/Profiler_Management/API_Reference.md` (new endpoints and `409` cases), `README.md`, `DOCS/General/Index.md`, summary `DOCS/Changes/2026-10-04_Async_PKI_Init.md`. Note for operators: single Profiler process is required (do not run several uvicorn workers).
## Out of scope
Cancelling a running init, progress percentage, async Clear PKI, job history.
@@ -0,0 +1,48 @@
# PKI dependency guard (2026-10-04)
Goal: while the PKI is not initialized the VPN (server) section is closed, and nothing that needs keys can run. Plan: [PKI_Dependency_Guard_PLAN](2026-10-04_PKI_Dependency_Guard_PLAN.md).
## Rules (backend is the source of truth)
| Operation | Rule |
|---|---|
| `POST /server/configure`, `POST /server/process/start`, `restart` | `409` unless the PKI is initialized, no init job runs and every file `server.conf` points to exists (`ca.crt`, `issued/<fqdn_server>.crt`, `private/<fqdn_server>.key`, `dh.pem`, `ta.key`, `crl.pem` when `crl_verify` is on). The message names the missing files, so a changed `fqdn_server` is caught too |
| `POST /server/process/stop` | always allowed |
| `POST /profiles` | `409` unless the PKI is initialized and no init job runs |
| `DELETE /system/pki` | `409` while an init job runs and `409 "Stop OpenVPN first"` while OpenVPN runs |
| `PUT /config/server`, `GET /config`, monitoring | open (no key operation) |
| `GET /system/init/status` | new fields `pki_ready`, `server_ready`, `missing` |
## UI
| Area | Change |
|---|---|
| `composables/usePkiStatus.js` | Shared status, refreshed on login, on every route change and by the PKI page (init finished, Clear PKI) |
| Sidebar (`App.vue`) | VPN item is locked (lock icon, muted, tooltip "Initialize PKI first") until the PKI is ready; a click goes to the PKI page |
| Router (`router/index.js`) | `/config/vpn` requires a ready PKI; otherwise redirect to the PKI page with a toast (also for a typed URL). A failed status request does not block navigation |
| `ServerManagement.vue` | Start / Restart disabled with a hint (missing files); Stop stays enabled |
| `Certificates.vue` | New Client disabled with a hint |
| `VPNConfig.vue` | Lock notice with a link to the PKI page instead of the form when the PKI is not ready; backend error text in toasts |
## Verification (containers)
| Check | Result |
|---|---|
| pytest (`test_pki_guard`, `test_async_pki_init`, `test_profile_note`) in `python:3.12-alpine` | 3 passed |
| After Clear PKI: status | `pki_ready: false`, `server_ready: false`, missing files listed |
| After Clear PKI: configure, start, restart, create client | `409`; stop `200` |
| Init PKI, then configure, start | `200`, `200` |
| Clear PKI while OpenVPN runs | `409 Stop OpenVPN first` |
| `fqdn_server` renamed after init: configure, start | `409`, names `issued/renamed-srv.crt` and `private/renamed-srv.key` |
| Create a client after init | `200` |
| UI bundle contains the guard texts | yes; behaviour in the browser is checked manually |
## Notes
- The status is refreshed on navigation and by the PKI page, not by polling: an open VPN page notices a cleared PKI on its next refresh (navigation or a failed Apply).
- After a rename of `fqdn_server` the VPN page stays reachable (the PKI itself is intact); configure, start and restart are blocked and name the missing certificate.
- `DELETE /system/pki` takes about a second longer while OpenVPN runs (process statistics).
## Existing installations
No manual steps. Rebuild and restart the Profiler and the UI. A running server is not affected until it is restarted.
@@ -0,0 +1,59 @@
# Logical protection: server setup depends on PKI (plan, 2026-10-04)
Goal: while the PKI is not initialized, the VPN (server) section is closed, and nothing that needs keys can run. The rule is enforced in the backend (the source of truth) and reflected in the UI.
## Dependency analysis
What the server needs: `ca.crt`, server certificate and key (`issued/<fqdn_server>.crt`, `private/<fqdn_server>.key`), `dh.pem`, `ta.key`, `crl.pem` (used when `crl_verify` is on). `server.conf.j2` points to all of them.
| Operation | Needs PKI? | Today | Planned |
|---|---|---|---|
| `POST /server/configure` (build and install `server.conf`) | yes, all server files | renders paths to files that do not exist and installs the config | `409` with the list of missing files |
| `POST /server/process/start`, `restart` | yes (config + keys) | tries to start; may start with a stale `server.conf` from an earlier PKI | `409` unless the server files exist; `stop` stays allowed |
| `POST /profiles` (create client) | yes (CA) | blocked only while an init job runs | `409` unless the PKI is initialized |
| `DELETE /profiles/{id}` (revoke), download | CA / existing file | no PKI means no profiles (Clear PKI wipes them) | unchanged |
| `PUT /config/server` (save settings), `GET /config` | no (only DB values) | open | open at API level (see decision 1) |
| `PUT /config/pki` | no | open | open; UI warns that changing the server name after init makes the server certificate name stale |
| Monitoring (`APP_CORE`: Analytics, Clients) | no | open | unchanged |
Hidden dependencies found:
1. Server name: `fqdn_server` is used to build the certificate path. If it is edited after init, `server.conf` would point to a missing certificate. The check must test the actual files, not just "PKI exists".
2. Clear PKI leaves `/etc/openvpn/server.conf` and possibly a running OpenVPN that has lost its keys. After Clear the server must not be startable, and Clear should not pull the keys from under a running server (decision 2).
3. An init job in progress counts as "not ready".
## Steps
### 1. Backend (`APP_PROFILER/`)
- `services/pki.py`: `server_files_missing(db)` returns the list of missing server files (honours `fqdn_server`; `crl.pem` required only when `crl_verify` is on); `require_pki_ready()` helpers raising a `PkiNotReady` exception with a clear message.
- `routers/server.py` (`/server/configure`), `routers/server_process.py` (`start`, `restart`), `routers/profiles.py` (`POST /profiles`): return `409 {"detail": "PKI is not initialized. Initialize PKI first."}` (or the list of missing files).
- `GET /system/init/status` gets two fields: `pki_ready` (initialized, no job running) and `server_ready` (all server files present) plus `missing` (file names). One endpoint feeds the whole UI.
- Decision 2: `DELETE /system/pki` returns `409 "Stop OpenVPN first"` while the OpenVPN process runs.
### 2. UI (`APP_UI/`)
- `composables/usePkiStatus.js`: shared reactive status (`pki_ready`, `server_ready`, `missing`, `state`), `refresh()`; loaded after login, on every route change and by `PKIConfig.vue` when init finishes or PKI is cleared (the sidebar updates without reload).
- Sidebar (`App.vue`): the **VPN** item stays visible but locked (lock icon, muted, tooltip "Initialize PKI first"); click redirects to the PKI page.
- Router guard (`router/index.js`): `/config/vpn` is `meta.requiresPki`; without a ready PKI the navigation is redirected to `/config/pki` with a toast "Initialize PKI before configuring the server". Direct URL entry is covered by the same guard.
- `ServerManagement.vue`: Start/Restart disabled with the hint when `server_ready` is false (Stop stays enabled).
- `Certificates.vue`: "New Client" disabled with the hint when the PKI is not initialized.
- `VPNConfig.vue`: if the status changes while the page is open (PKI cleared in another tab), the page shows the lock notice instead of the form.
- Backend `409` messages are shown through the existing toast.
### 3. Tests (minimal)
- One pytest in `APP_PROFILER` with PKI absent: `POST /server/configure`, `POST /server/process/start` and `POST /profiles` return `409`; `GET /system/init/status` shows `pki_ready: false`, `server_ready: false`. With the PKI files created (stub directory) the three calls are no longer `409` for this reason. No UI tests.
### 4. Verification (containers, stand port 8089)
- Clear PKI: VPN menu locked, `/config/vpn` redirects, Start/Restart and New Client disabled; the same calls through the API return `409`.
- Init PKI: after it finishes the menu unlocks without a page reload; configure, start, create client work.
- Edit the server name after init: configure answers `409` naming the missing certificate.
- Clear PKI with OpenVPN running: `409` (decision 2).
### 5. Documentation
- `API_Reference.md` (409 cases, new status fields), summary `DOCS/Changes/2026-10-04_PKI_Dependency_Guard.md`, README row, Index link.
## Decisions for the owner
1. `PUT /config/server` stays open at the API level (it touches only DB values and is not a key operation); the page itself is locked in the UI. Alternative: also answer `409` there.
2. Block Clear PKI while OpenVPN is running (recommended) or allow it and only warn.
3. VPN menu item: visible and locked (recommended, the user sees why) or hidden.
## Out of scope
Automatic stop of OpenVPN, certificate expiry checks, locking the Server Process page as a whole.
@@ -0,0 +1,29 @@
# Compact profile modal and note tooltip: implementation plan (2026-10-04)
Goal: (1) make the profile details modal compact with a balanced layout, (2) show the profile note in a tooltip when hovering over the client name in the Certificates list. UI only; no API or DB changes.
## Steps
### 1. Compact modal (`APP_UI/src/components/ProfileDetailsModal.vue`)
- Remove `modal-lg`: use the default Bootstrap width (500 px) and `modal-dialog-centered`; on phones it stays full width minus margins.
- Layout of the details block: a compact two-column "label : value" list (fixed narrow label column, value left-aligned right next to it) instead of two wide columns. Rows: Status, Created, Expires (with days remaining next to the date, e.g. `2027-01-10 (98 d)`), Revoked (only if set), File.
- Header: client name as the title with the status badge next to it; the separate "Client Name" and "Status" rows are removed.
- File path: single line, `text-break`, small muted font.
- Note: textarea with 3 rows, counter under it on the right; Save / Close buttons stay in the footer.
- Dates: one short format (`YYYY-MM-DD HH:mm`) instead of locale date plus time.
### 2. Note tooltip (`APP_UI/src/views/Certificates.vue`)
- Hovering the username cell (both active and expired/revoked rows) shows a tooltip with the note text. No note: no tooltip.
- Implementation: Bootstrap Tooltip (already a dependency) via a small directive `v-note-tooltip="cert.note"` in `APP_UI/src/directives/` (create on mount, update the text when the note changes after saving, dispose on unmount). Options: `placement: 'top'`, `container: 'body'`, `html: false` (note is plain text, so no XSS), long text wrapped to a max width of about 320 px, line breaks preserved.
- Small note marker (`fa-note-sticky` icon, muted) next to the username when a note exists, so it is visible which clients have a note.
- Styles in `assets/main.css`: tooltip max width, `white-space: pre-wrap`, dark theme colours via existing variables.
### 3. Verification (containers, no new tests)
- No new automated tests (UI only, no UI test infrastructure).
- Rebuild `app-ui` in the existing stand (`ovpmon-test`, port 8089) and check manually: modal width and layout in light and dark themes and on a narrow window; tooltip on active and revoked rows; tooltip text updates right after saving a note; no tooltip for clients without a note; long and multi-line notes.
### 4. Documentation
- Summary appended to `DOCS/Changes/2026-10-04_Profile_Notes.md`; one line in the `README.md` changes table.
## Out of scope
Showing the note as a table column, editing the note from the list, API changes.
+55
View File
@@ -0,0 +1,55 @@
# Profile details modal and notes (2026-10-04)
Goal: make rows on the **Certificates** page clickable; a click opens a modal with the main profile details and a note that can be saved. Plan: [Profile_Notes_PLAN](2026-10-04_Profile_Notes_PLAN.md).
## Changes
| Area | Change |
|---|---|
| Model (`APP_PROFILER/models.py`) | `UserProfile.note` (nullable `Text`) |
| Schemas (`APP_PROFILER/schemas.py`) | `note` in the profile response; `UserProfileNoteUpdate` (max 1000 chars, empty or whitespace-only becomes `null`) |
| Migration (`APP_PROFILER/database.py`, `main.py`) | `ensure_columns()` runs after `create_all` and adds `note` to an existing `user_profiles` table if missing (idempotent) |
| API (`APP_PROFILER/routers/profiles.py`) | `PUT /profiles/{id}/note` returns the updated profile; `404` if missing; JWT required. PUT is used because CORS does not allow PATCH |
| UI (`APP_UI/src/components/ProfileDetailsModal.vue`) | New modal on `BaseModal`: name, status, created, expiration, days remaining, revoked date, file path, note textarea with counter; Save is enabled only after a change |
| UI (`APP_UI/src/views/Certificates.vue`) | Rows (active and expired/revoked) open the modal; download/revoke buttons use `@click.stop`; `saveNote()` calls the API, shows a toast and reloads the list |
| Fix (`APP_PROFILER/requirements.txt`) | Added `requests`: `services/utils.py` imports it to detect the public IP, and creating a client failed with `No module named 'requests'` (HTTP 500, "Config Generation failed") when Public IP was not set in server settings. The failed attempts had already issued the certificate in PKI |
| Docs | `DOCS/Profiler_Management/API_Reference.md`: new endpoint and `note` field |
| Tests | `APP_PROFILER/test_profile_note.py` (one test), `APP_PROFILER/requirements-dev.txt` |
## Verification (in containers)
| Check | Result |
|---|---|
| `pytest test_profile_note.py` in `python:3.12-alpine` | 1 passed |
| `docker compose` build of all four images | OK |
| New DB: `note` column present | OK |
| Old-schema DB (no `note`): column added on start, data kept, second start is a no-op | OK |
| `PUT /profiles/{id}/note` with JWT | 200, note returned by `GET /profiles` |
| Without token / note over 1000 chars / unknown id | 401 / 422 / 404 |
| Whitespace-only note | stored as `null` |
| Browser check of the UI | manual (see below) |
## Notes
- Run the new test on its own (`cd APP_PROFILER && pip install -r requirements-dev.txt && pytest test_profile_note.py`): the older `test_server_process.py` also imports `main` with the default DB path.
- On a revoked row the Revoke button is disabled; some browsers do not pass a click on a disabled button to the row, so the modal may not open from that spot. Click elsewhere in the row.
- The modal closes right after Save; if the request fails the text is not kept.
## Existing installations
Rebuild the Profiler image so that `requests` is installed. A client name whose certificate was already issued by a failed attempt cannot be created again (Easy-RSA: certificate exists, HTTP 500); use another name or revoke/clear it in PKI.
No manual steps: the `note` column is added on the next Profiler start (native: restart `ovpmon-profiler`; Docker: rebuild `app-profiler` and `app-ui`). Back up `ovpn_profiler.db` first.
## Follow-up: compact modal and note tooltip (2026-10-04)
Plan: [Profile_Modal_Polish_PLAN](2026-10-04_Profile_Modal_Polish_PLAN.md). UI only.
| Area | Change |
|---|---|
| `ProfileDetailsModal.vue` | Default modal width (no `modal-lg`); name and status badge in the header; compact label : value list (Created, Expires with days remaining, Revoked, File); dates as `YYYY-MM-DD HH:mm`; 3-row note field |
| `directives/noteTooltip.js` | `v-note-tooltip`: Bootstrap Tooltip with the note text (plain text, hover, hidden on click); recreated when the note changes, disposed on unmount |
| `Certificates.vue` | Tooltip on the client cell in active and expired/revoked rows; muted note icon next to the name when a note exists |
| `main.css` | `.note-tooltip` (max width 320 px, line breaks kept, light/dark theme variables), `.profile-meta` grid |
Verification: `app-ui` image builds, the note icon and tooltip styles are in the bundle; layout and tooltip behaviour are checked manually.
@@ -0,0 +1,29 @@
# Profile details modal and notes: implementation plan (2026-10-04)
Goal: on the **Certificates** page, rows become clickable. A click opens a modal with the main profile details and a free-text **note** that can be saved. Profiles have no note field today, so a minimal Profiler change is required to store it.
## Steps
### 1. Profiler backend (`APP_PROFILER/`)
- `models.py`: `UserProfile.note = Column(Text, nullable=True)`.
- `schemas.py`: `note: Optional[str]` in the response schema; new `UserProfileNoteUpdate` (max 1000 chars, empty string becomes `None`).
- Startup migration: idempotent "add column if missing" step (pattern from `APP_CORE/db.py`), so existing databases do not fail with `no such column`.
- `routers/profiles.py`: `PUT /profiles/{profile_id}/note` returns the updated profile; 404 if not found; JWT required (router-level `verify_token`). PUT is used because CORS does not allow PATCH.
### 2. UI (`APP_UI/`)
- New `src/components/ProfileDetailsModal.vue` built on `BaseModal.vue` (pattern: `NewClientModal.vue`): username, status badge, created, expiration, days remaining, revoked date, file path, note textarea, Save / Close.
- `src/views/Certificates.vue`: clickable rows (active and expired/revoked), `@click.stop` on the download/revoke buttons, `saveNote()` via `profilesApiClient.put`, reload and toast.
### 3. Tests (minimal)
- One pytest test in `APP_PROFILER`: `PUT /profiles/{id}/note` stores the note and `GET /profiles` returns it (temporary DB, auth dependency overridden).
- No UI tests (no test infrastructure in `APP_UI`).
### 4. Build and verification (containers)
- Tests and build run in containers; the result is deployed with `docker-compose` on this host for manual checks.
### 5. Documentation
- `DOCS/Profiler_Management/API_Reference.md`, `DOCS/General/Index.md`, `README.md` (Changes table).
- Summary of the work: `DOCS/Changes/2026-10-04_Profile_Notes.md` (written at the end).
## Out of scope
Note history, per-user permissions, search by note, other pages.
@@ -0,0 +1,28 @@
# Toast notifications (2026-10-04)
Goal: pop-up notifications in the bottom-right corner of the screen, readable in the light and the dark theme. Plan: [Toast_Notifications_PLAN](2026-10-04_Toast_Notifications_PLAN.md). UI only.
## Changes
| Area | Change |
|---|---|
| `composables/useToast.js` | Shared state: `show(text, type, timeout)`, `dismiss`, `pause`, `resume`; types `success`, `warning`, `error`, `info`; 5 s (errors 8 s); at most 4 on screen |
| `components/ToastContainer.vue` | Mounted once in `App.vue` (also on the Login page): icon, text, close button, progress bar; slide-in from the right; hover pauses the timer; `role="alert"` for errors, `role="status"` otherwise |
| `assets/main.css` | Fixed bottom-right stack above modals; surface from the theme variables, coloured stripe/icon/progress bar per type; separate colour tokens for the light and the dark theme; full width on phones; reduced motion supported. Old `.toast-message` styles removed |
| Views | `PKIConfig.vue`, `VPNConfig.vue`, `ServerManagement.vue`, `Certificates.vue` use the shared toast; their `showMessage` / `showToast` helpers are one-line wrappers, call sites unchanged; inline markup and local timers removed |
Not changed: SweetAlert2 dialogs in `Account.vue` and inline alerts on the Login page.
## Verification
`app-ui` image builds (Vite), the toast styles are in the bundle and the old ones are gone; appearance and behaviour (both themes, several toasts, hover pause, narrow window, toast over a modal) are checked manually.
## Notes
- Durations are unified: 5 s, errors 8 s (was 3 to 5 s).
- Toasts are global, so a message raised right before a route change stays visible after it.
- Touch devices have no hover: toasts there simply time out.
## Existing installations
Rebuild the UI image (`app-ui`); no configuration or data changes.
@@ -0,0 +1,20 @@
# Toast notifications: implementation plan (2026-10-04)
Goal: pop-up notifications appear in the bottom-right corner of the screen, are not lost, and look good in the light and dark themes. UI only.
## Current state
- Four views implement their own notification: `PKIConfig.vue`, `VPNConfig.vue`, `ServerManagement.vue` render `.toast-message` inside the page card (top of the page, scrolls away, one message at a time); `Certificates.vue` has its own fixed bottom-right copy with inline styles.
- Styles (`assets/main.css`, `.toast-message`, `.toast-success|warning|error`) use fixed light colours, no dark theme.
- `Account.vue` uses SweetAlert2 dialogs and `Login.vue` inline alerts: these are dialogs, not toasts, and stay as they are.
## Steps
1. `src/composables/useToast.js`: shared reactive list of toasts; `show(text, type = 'success', timeout)` with types `success | warning | error | info`; `dismiss(id)`. Default timeout 5 s (errors 8 s); max 4 on screen (oldest dropped).
2. `src/components/ToastContainer.vue`, mounted once in `App.vue`: fixed bottom-right (`z-index` above modals), stacked column, `TransitionGroup` slide-in from the right and fade-out; each toast has an icon, text, close button, thin progress bar; the timer pauses on hover; `role="status"` (`role="alert"` for errors) with `aria-live`; on phones full width at the bottom.
3. Design (`main.css`): card surface from existing variables (`--bg-card`, `--border-color`, `--text-main`), a coloured accent stripe and icon per type, soft shadow; separate colour tokens for the light and the dark theme (`[data-theme="dark"]`) so contrast stays readable in both. Old `.toast-message` styles are removed.
4. Views: `PKIConfig.vue`, `VPNConfig.vue`, `ServerManagement.vue`, `Certificates.vue` call `useToast().show(...)` (their `showMessage` / `showToast` helpers stay as thin wrappers, call sites are not changed); inline toast markup and local timers are removed.
5. Tests: none (no UI test infrastructure; no logic on the server side).
6. Verification: rebuild `app-ui` on the stand (port 8089) and check manually: all four pages, success / warning / error, several toasts at once, hover pause, close button, light and dark theme, narrow window, toast above an open modal (Certificates note save).
7. Documentation: summary `DOCS/Changes/2026-10-04_Toast_Notifications.md`, row in `README.md`, link in `DOCS/General/Index.md`.
## Out of scope
SweetAlert2 dialogs in `Account.vue`, inline login alerts, sound, persistent notification history.
+4
View File
@@ -19,6 +19,10 @@ Welcome to the documentation for the OpenVPN Monitor suite.
- [Settings validation (2026-09-30)](../Changes/2026-09-30_Settings_Validation.md)
- [Privilege separation (2026-09-30)](../Changes/2026-09-30_Privilege_Separation.md)
- [Egress via Hysteria2 (2026-09-30)](../Changes/2026-09-30_Egress_via_Hysteria2.md)
- [Profile notes (2026-10-04)](../Changes/2026-10-04_Profile_Notes.md)
- [Async PKI init (2026-10-04)](../Changes/2026-10-04_Async_PKI_Init.md)
- [Toast notifications (2026-10-04)](../Changes/2026-10-04_Toast_Notifications.md)
- [PKI dependency guard (2026-10-04)](../Changes/2026-10-04_PKI_Dependency_Guard.md)
## 🔍 Core Monitoring (`APP_CORE`)
The core module responsible for log parsing, real-time statistics, and the primary API.
+23 -4
View File
@@ -18,17 +18,23 @@ Manage OpenVPN Client profiles (`.ovpn` configs and certificates).
### `GET /profiles`
List all user profiles.
- **Response**: Array of profile objects (id, username, status, expiration_date, etc.).
- **Response**: Array of profile objects (id, username, status, expiration_date, note, etc.).
### `POST /profiles`
Create a new user profile.
- **Body**: `{"username": "jdoe"}`
- **Action**: Generates keys, requests certificate, builds `.ovpn` file.
- **Response `409`**: PKI initialization is running, or the PKI is not initialized (`"PKI is not initialized. Initialize PKI first."`).
### `DELETE /profiles/{id}`
Revoke a user profile.
- **Action**: Revokes certificate in CRL and marks profile as revoked in DB.
### `PUT /profiles/{id}/note`
Set or clear the free-text note of a profile.
- **Body**: `{"note": "text"}` (max 1000 characters; empty or `null` clears the note)
- **Response**: Updated profile object (including `note`). `404` if the profile does not exist.
### `GET /profiles/{id}/download`
Download the `.ovpn` configuration file for a user.
- **Response**: File stream (application/x-openvpn-profile).
@@ -53,11 +59,22 @@ Update PKI settings (e.g., Key Size, Certificate Expiry).
- **Body**: JSON object matching `PKISetting` schema.
### `POST /system/init`
Initialize the PKI infrastructure (InitCA, GenDH, BuildServerCert).
- **Note**: Only runs if PKI is empty.
Start PKI initialization (init-pki, CA, server certificate, DH, TLS key, CRL) as a background job. Returns immediately.
- **Response `202`**: `{"state": "running"}`
- **Response `409`**: a job is already running, or the PKI is already complete (`ca.crt`, `dh.pem`, `ta.key`, `crl.pem` and the server certificate). An incomplete PKI left by an interrupted run is removed and initialization starts again.
- **Note**: Job state is kept in memory; the Profiler must run as a single process (one uvicorn worker). After a restart the state is `idle`.
### `GET /system/init/status`
Current state of the initialization job.
- **Response**: `{ "state": "idle|running|done|error", "step": "init-pki|ca|server-cert|dh|ta-key|crl|null", "initialized": true, "started_at": "2026-10-04T10:00:00Z", "finished_at": null, "error": null, "pki_ready": true, "server_ready": true, "missing": [] }`
- `initialized` reflects the files on disk (complete PKI), independent of `state`.
- `pki_ready`: the PKI is initialized and no job is running (client certificates can be issued).
- `server_ready`: `pki_ready` and every file `server.conf` references exists; `missing` lists the absent ones (relative to the PKI directory: `ca.crt`, `issued/<fqdn_server>.crt`, `private/<fqdn_server>.key`, `dh.pem`, `ta.key`, and `crl.pem` only when `crl_verify` is on). The check uses the current `fqdn_server`, so renaming the server after init makes it not ready.
- `error` contains the EasyRSA message when `state` is `error`.
### `DELETE /system/pki`
**DANGER**: Completely wipes the PKI directory.
**DANGER**: Completely wipes the PKI directory and resets the job state.
- **Response `409`**: an initialization job is running, or OpenVPN is running (`"Stop OpenVPN first"`).
---
@@ -66,11 +83,13 @@ Initialize the PKI infrastructure (InitCA, GenDH, BuildServerCert).
### `POST /server/configure`
Generate the `server.conf` file based on current database settings.
- **Response**: `{"message": "Server configuration generated", "path": "/etc/openvpn/server.conf"}`
- **Response `409`**: the PKI is not initialized or an init job is running (`"PKI is not initialized. Initialize PKI first."`), or server files are missing (`"PKI server files are missing: ..."`).
### `POST /server/process/{action}`
Control the OpenVPN system service.
- **Path Param**: `action` (start, stop, restart)
- **Response**: Status of the command execution.
- **Response `409`**: for `start` and `restart` only, same conditions as `POST /server/configure`. `stop` is always allowed.
### `GET /server/process/stats`
Get telemetry for the OpenVPN process.
+4
View File
@@ -61,6 +61,10 @@ No default user is created. Seed the initial admin with `OVPMON_INITIAL_ADMIN_US
| 2026-09-30 | Validation of server/PKI settings (config injection into the root-written OpenVPN config) | [Settings validation](DOCS/Changes/2026-09-30_Settings_Validation.md) |
| 2026-09-30 | API services run as an unprivileged user; root helper validates and installs the OpenVPN config, publishes the CRL | [Privilege separation](DOCS/Changes/2026-09-30_Privilege_Separation.md) (includes CRL publishing for `crl_verify`) |
| 2026-09-30 | Route OpenVPN clients through a Hysteria2 tunnel to an exit node | [Egress via Hysteria2](DOCS/Changes/2026-09-30_Egress_via_Hysteria2.md) |
| 2026-10-04 | Certificates page: clickable rows, profile details modal with a saved note (`PUT /profiles/{id}/note`) | [Profile notes](DOCS/Changes/2026-10-04_Profile_Notes.md) (includes the compact modal and the note tooltip on the client name) |
| 2026-10-04 | PKI initialization runs in the background: status endpoint, progress on the PKI page, protection against a second start | [Async PKI init](DOCS/Changes/2026-10-04_Async_PKI_Init.md) |
| 2026-10-04 | Toast notifications moved to the bottom-right corner, shared component, light/dark themes | [Toast notifications](DOCS/Changes/2026-10-04_Toast_Notifications.md) |
| 2026-10-04 | Server setup is closed until the PKI is initialized (VPN menu lock, 409 for configure/start/create client, Clear PKI blocked while OpenVPN runs) | [PKI dependency guard](DOCS/Changes/2026-10-04_PKI_Dependency_Guard.md) |
## Notes