Compare commits
18
Commits
3fac8d70d8
..
main
No files matched your search
@@ -37,6 +37,9 @@ def main(argv=None):
|
||||
if st.too_new:
|
||||
raise migrations._too_new_error(st)
|
||||
print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)"))
|
||||
if not st.exists and not args.db:
|
||||
print("Hint: the default database was used; for an installed system set OVPMON_OPENVPN_MONITOR_DB_PATH "
|
||||
"(see /etc/ovpmon/env) or pass --db PATH")
|
||||
if args.check:
|
||||
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
|
||||
if not st.pending:
|
||||
|
||||
@@ -29,6 +29,29 @@ app = Flask(__name__)
|
||||
# Cross-origin access is off by default (the UI is same-origin behind Nginx); allow extra origins via OVPMON_CORS_ORIGINS (comma-separated)
|
||||
CORS(app, resources={r"/api/*": {"origins": [o.strip() for o in os.getenv("OVPMON_CORS_ORIGINS", "").split(",") if o.strip()]}}, supports_credentials=True)
|
||||
|
||||
# Length of one bucket of the aggregate tables, seconds. The aggregates hold only bytes, so for periods
|
||||
# longer than a day the speed is the bucket average: bytes * 8 / 1e6 / bucket duration.
|
||||
BUCKET_SECONDS = {
|
||||
'stats_5min': 300,
|
||||
'stats_15min': 900,
|
||||
'stats_hourly': 3600,
|
||||
'stats_6h': 21600,
|
||||
'stats_daily': 86400,
|
||||
}
|
||||
|
||||
|
||||
def avg_rate_sql(table, bytes_expr, ts_expr):
|
||||
"""SQL expression of the average speed (Mbps) of a bucket of an aggregate table.
|
||||
|
||||
The current (incomplete) bucket lasts min(bucket length, time since its start), at least 1 second;
|
||||
timestamps of the aggregates are UTC. `table` is taken only from BUCKET_SECONDS (never user input),
|
||||
the other arguments are fixed column expressions of the caller.
|
||||
"""
|
||||
seconds = BUCKET_SECONDS[table]
|
||||
return (f"({bytes_expr}) * 8.0 / 1000000.0 / "
|
||||
f"MAX(1, MIN({seconds}, CAST(strftime('%s', 'now') AS INTEGER) - CAST(strftime('%s', {ts_expr}) AS INTEGER)))")
|
||||
|
||||
|
||||
class OpenVPNAPI:
|
||||
def get_config_value(self, section, key, fallback=None):
|
||||
try:
|
||||
@@ -194,6 +217,31 @@ class OpenVPNAPI:
|
||||
for row in cursor.fetchall():
|
||||
data.append(dict(zip(columns, row)))
|
||||
|
||||
# Active sessions per CN (the table may be absent on an old database)
|
||||
sessions_by_cn = {}
|
||||
try:
|
||||
cursor.execute('''
|
||||
SELECT common_name, real_address, connected_since, bytes_received, bytes_sent
|
||||
FROM active_sessions
|
||||
ORDER BY connected_since, real_address
|
||||
''')
|
||||
for cn, addr, since, rx, tx in cursor.fetchall():
|
||||
sessions_by_cn.setdefault(cn, []).append({
|
||||
'real_address': addr,
|
||||
'connected_since': since,
|
||||
'bytes_received': rx or 0,
|
||||
'bytes_sent': tx or 0,
|
||||
'received_mb': round((rx or 0) / (1024 * 1024), 2),
|
||||
'sent_mb': round((tx or 0) / (1024 * 1024), 2),
|
||||
})
|
||||
except sqlite3.Error:
|
||||
sessions_by_cn = {}
|
||||
|
||||
for client in data:
|
||||
sessions = sessions_by_cn.get(client['common_name'], []) if client['status'] == 'Active' else []
|
||||
client['sessions_count'] = len(sessions)
|
||||
client['sessions'] = sessions
|
||||
|
||||
return data
|
||||
|
||||
except Exception as e:
|
||||
@@ -322,8 +370,8 @@ class OpenVPNAPI:
|
||||
t.timestamp,
|
||||
t.bytes_received,
|
||||
t.bytes_sent,
|
||||
0 as bytes_received_rate_mbps,
|
||||
0 as bytes_sent_rate_mbps
|
||||
{avg_rate_sql(target_table, 't.bytes_received', 't.timestamp')} as bytes_received_rate_mbps,
|
||||
{avg_rate_sql(target_table, 't.bytes_sent', 't.timestamp')} as bytes_sent_rate_mbps
|
||||
FROM {target_table} t
|
||||
JOIN clients c ON t.client_id = c.id
|
||||
WHERE c.common_name = ? AND t.timestamp BETWEEN ? AND ?
|
||||
@@ -477,7 +525,8 @@ class OpenVPNAPI:
|
||||
if target_table == 'usage_history':
|
||||
rate_cols = "SUM(bytes_received_rate_mbps) as total_rx_rate, SUM(bytes_sent_rate_mbps) as total_tx_rate,"
|
||||
else:
|
||||
rate_cols = "0 as total_rx_rate, 0 as total_tx_rate,"
|
||||
rate_cols = (f"{avg_rate_sql(target_table, 'SUM(bytes_received)', 'timestamp')} as total_rx_rate, "
|
||||
f"{avg_rate_sql(target_table, 'SUM(bytes_sent)', 'timestamp')} as total_tx_rate,")
|
||||
|
||||
# Aggregation Query
|
||||
# Group by interval_seconds
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
Flask>=3.0.0
|
||||
Flask-Cors>=4.0.0
|
||||
PyJWT>=2.10.0
|
||||
pyotp>=2.9.0
|
||||
qrcode>=7.4.2
|
||||
bcrypt>=4.2.0
|
||||
|
||||
Flask>=3.0.0,<4
|
||||
Flask-Cors>=4.0.0,<7
|
||||
PyJWT>=2.10.0,<3
|
||||
pyotp>=2.9.0,<3
|
||||
qrcode>=7.4.2,<9
|
||||
bcrypt>=4.2.0,<6
|
||||
@@ -0,0 +1,45 @@
|
||||
import importlib
|
||||
import sqlite3
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
MB = 1_000_000
|
||||
FMT = '%Y-%m-%d %H:%M:%S'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api(tmp_path, monkeypatch):
|
||||
"""OpenVPNAPI on a temporary migrated database (the module creates a global instance on import)."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", str(tmp_path / "api.db"))
|
||||
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
|
||||
module = importlib.import_module("openvpn_api_v3")
|
||||
return module.OpenVPNAPI()
|
||||
|
||||
|
||||
def test_aggregated_history_speed_is_bucket_average(api):
|
||||
now = datetime.utcnow()
|
||||
full = (now - timedelta(hours=5)).replace(minute=0, second=0, microsecond=0) # complete hourly bucket
|
||||
current = now - timedelta(seconds=1800) # bucket started 30 minutes ago: lasts 1800 s, not 3600 s
|
||||
conn = sqlite3.connect(api.db_manager.db_path)
|
||||
conn.execute("INSERT INTO clients (common_name) VALUES ('alice')")
|
||||
cid = conn.execute("SELECT id FROM clients WHERE common_name='alice'").fetchone()[0]
|
||||
for ts in (full, current):
|
||||
conn.execute("INSERT INTO stats_hourly (timestamp, client_id, bytes_received, bytes_sent) VALUES (?,?,?,?)",
|
||||
(ts.strftime(FMT), cid, 450 * MB, 90 * MB))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
res = api.get_client_history('alice', now - timedelta(days=7), now, resolution='hourly')
|
||||
full_row, current_row = res['data']
|
||||
# 450 MB over 3600 s = 1.0 Mbps (rx), 90 MB over 3600 s = 0.2 Mbps (tx)
|
||||
assert full_row['bytes_received_rate_mbps'] == pytest.approx(1.0)
|
||||
assert full_row['bytes_sent_rate_mbps'] == pytest.approx(0.2)
|
||||
# the same volume over 1800 s: twice as fast
|
||||
assert current_row['bytes_received_rate_mbps'] == pytest.approx(2.0, rel=0.01)
|
||||
assert current_row['bytes_sent_rate_mbps'] == pytest.approx(0.4, rel=0.01)
|
||||
|
||||
# Analytics 7d reads the same table: the sum of clients per timestamp, speed is non-zero
|
||||
history = api.get_analytics_data('7d')['global_history_24h']
|
||||
assert max(p['total_rx_rate'] for p in history) == pytest.approx(2.0, rel=0.01)
|
||||
@@ -0,0 +1,41 @@
|
||||
import importlib
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
|
||||
FMT_SINCE = '2026-11-12 10:00:00'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api(tmp_path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", str(tmp_path / "api.db"))
|
||||
monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False)
|
||||
module = importlib.import_module("openvpn_api_v3")
|
||||
return module.OpenVPNAPI()
|
||||
|
||||
|
||||
def test_stats_include_sessions(api):
|
||||
conn = sqlite3.connect(api.db_manager.db_path)
|
||||
for cn, status in (('alice', 'Active'), ('bob', 'Active'), ('carol', 'Disconnected')):
|
||||
conn.execute("INSERT INTO clients (common_name, status, real_address) VALUES (?,?,?)",
|
||||
(cn, status, '1.1.1.1:1000'))
|
||||
ids = {cn: i for i, cn in conn.execute("SELECT id, common_name FROM clients")}
|
||||
mb = 1024 * 1024
|
||||
for cn, addr, rx, tx in (('alice', '1.1.1.1:1000', 2 * mb, mb), ('alice', '2.2.2.2:2000', 0, 0),
|
||||
('bob', '3.3.3.3:3000', mb, mb)):
|
||||
conn.execute("INSERT INTO active_sessions (client_id, common_name, real_address, bytes_received,"
|
||||
" bytes_sent, connected_since, last_seen, session_id) VALUES (?,?,?,?,?,?,?,?)",
|
||||
(ids[cn], cn, addr, rx, tx, FMT_SINCE, FMT_SINCE, None))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
by_cn = {c['common_name']: c for c in api.get_current_stats()}
|
||||
assert by_cn['alice']['sessions_count'] == 2
|
||||
assert {s['real_address'] for s in by_cn['alice']['sessions']} == {'1.1.1.1:1000', '2.2.2.2:2000'}
|
||||
first = next(s for s in by_cn['alice']['sessions'] if s['real_address'] == '1.1.1.1:1000')
|
||||
assert (first['received_mb'], first['sent_mb'], first['connected_since']) == (2.0, 1.0, FMT_SINCE)
|
||||
assert by_cn['bob']['sessions_count'] == 1
|
||||
assert by_cn['carol']['sessions_count'] == 0 and by_cn['carol']['sessions'] == []
|
||||
# existing fields are unchanged
|
||||
assert by_cn['alice']['real_address'] == '1.1.1.1:1000' and by_cn['alice']['status'] == 'Active'
|
||||
@@ -37,6 +37,9 @@ def main(argv=None):
|
||||
if st.too_new:
|
||||
raise migrations._too_new_error(st)
|
||||
print(f"Database: {db_path}" + ("" if st.exists else " (does not exist yet)"))
|
||||
if not st.exists and not args.db:
|
||||
print("Hint: the default database was used; for an installed system set OVPMON_PROFILER_DB_PATH "
|
||||
"(see /etc/ovpmon/env) or pass --db PATH")
|
||||
if args.check:
|
||||
print(f"Schema version: {st.current} (latest known: {migrations.latest_version()})")
|
||||
if not st.pending:
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
fastapi
|
||||
uvicorn
|
||||
fastapi==0.143.3
|
||||
starlette==1.8.0
|
||||
uvicorn==0.54.0
|
||||
pydantic==2.14.1
|
||||
sqlalchemy
|
||||
psutil
|
||||
python-multipart
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from typing import Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from database import get_db
|
||||
@@ -13,7 +15,7 @@ router = APIRouter(dependencies=[Depends(verify_token)])
|
||||
|
||||
@router.get("/config", response_model=ConfigResponse)
|
||||
def get_config(
|
||||
section: str = Query(None, enum=["server", "pki"]),
|
||||
section: Optional[Literal["server", "pki"]] = Query(None),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
response = ConfigResponse()
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
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 utils.auth import verify_token
|
||||
|
||||
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_config_section_values():
|
||||
r = client.get("/api/config", params={"section": "server"})
|
||||
assert r.status_code == 200 and r.json()["server"] and not r.json().get("pki")
|
||||
assert client.get("/api/config", params={"section": "pki"}).status_code == 200
|
||||
assert client.get("/api/config").status_code == 200
|
||||
assert client.get("/api/config", params={"section": "bogus"}).status_code == 422
|
||||
@@ -1,33 +1,27 @@
|
||||
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
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Add project root to sys.path
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
from utils.auth import verify_token
|
||||
|
||||
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_get_stats():
|
||||
response = client.get("/server/process/stats")
|
||||
print(f"Stats response status: {response.status_code}")
|
||||
print(f"Stats response body: {response.json()}")
|
||||
response = client.get("/api/server/process/stats")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "pid" in data
|
||||
assert "cpu_percent" in data
|
||||
assert "memory_mb" in data
|
||||
|
||||
def test_control_invalid():
|
||||
response = client.post("/server/process/invalid_action")
|
||||
print(f"Invalid action response: {response.status_code}")
|
||||
assert response.status_code == 400
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Running API tests...")
|
||||
try:
|
||||
test_get_stats()
|
||||
test_control_invalid()
|
||||
print("Tests passed!")
|
||||
except Exception as e:
|
||||
print(f"Tests failed: {e}")
|
||||
def test_control_invalid():
|
||||
response = client.post("/api/server/process/invalid_action")
|
||||
assert response.status_code == 400
|
||||
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
dist
|
||||
.vscode
|
||||
.git
|
||||
*.bak
|
||||
*.log
|
||||
+12
-4
@@ -2,14 +2,22 @@
|
||||
FROM node:20-alpine AS build-stage
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
# Stage 2: Serve
|
||||
FROM nginx:alpine
|
||||
# nginx runs as the unprivileged user "nginx" (uid 101) and listens on 8080 (OVP_UI_PORT); docker-compose publishes
|
||||
# it as the host port (OVPMON_HTTP_PORT, default 80). The image entrypoint renders the template into
|
||||
# /etc/nginx/conf.d. Behind another proxy or Kubernetes: target port 8080.
|
||||
FROM nginxinc/nginx-unprivileged:alpine
|
||||
COPY --from=build-stage /app/dist /usr/share/nginx/html
|
||||
COPY default.conf.template /etc/nginx/templates/default.conf.template
|
||||
EXPOSE 80
|
||||
# Validates OVP_CSP_CONNECT_EXTRA before the template is rendered (20-envsubst-on-templates.sh)
|
||||
COPY check-csp-connect-extra.sh /docker-entrypoint.d/15-check-csp-connect-extra.sh
|
||||
# envsubst replaces only variables that are defined, so the defaults must exist.
|
||||
# OVP_CSP_CONNECT_EXTRA: extra connect-src origins of the CSP, separated by spaces (empty: same origin only)
|
||||
ENV OVP_UI_PORT=8080 \
|
||||
OVP_CSP_CONNECT_EXTRA=""
|
||||
EXPOSE 8080
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
|
||||
+21
-9
@@ -1,25 +1,37 @@
|
||||
# OpenVPN Dashboard UI (`APP_UI`)
|
||||
# OpenVPN Controller UI (`APP_UI`)
|
||||
|
||||
A Single Page Application (SPA) built with **Vue 3** and **Vite**. It serves as the unified dashboard for monitoring and management.
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `src/views/`: Page components (Dashboard, Login, Profiles, etc.).
|
||||
- `src/components/`: Reusable widgets (Charts, Sidebar).
|
||||
- `src/stores/`: Pinia state management (Auth, Client Data).
|
||||
- `src/views/`: Pages (Analytics, Clients, Certificates, PKI and VPN configuration, Server Process, Backup and Restore, Account, Login).
|
||||
- `src/components/`: Reusable widgets (`BaseModal`, `ConfirmModal`, `StatusBadge`, toasts, dialogs).
|
||||
- `src/composables/`: Shared logic: `useApi` (axios clients: monitoring API, profiler API, `/api/auth`), `useTrafficChart` (charts), `useTheme`, `useToast`, `useFormatters`, `usePkiStatus`.
|
||||
- `src/utils/`: Helpers without Vue (CIDR parsing).
|
||||
- `default.conf.template`: nginx configuration of the container image (security headers, one CSP, gzip, cache, API proxy).
|
||||
- `Dockerfile`: build and `nginxinc/nginx-unprivileged:alpine` image (user `nginx`, port 8080); `check-csp-connect-extra.sh`: validation of `OVP_CSP_CONNECT_EXTRA`, runs at container start.
|
||||
|
||||
## Configuration
|
||||
|
||||
Runtime configuration is loaded from `/config.json` (in `public/`) to allow environment-independent builds.
|
||||
Runtime configuration is loaded from `/config.json` (in `public/`) to allow environment-independent builds. With the container nginx the CSP allows requests to the page origin only (`connect-src 'self'`): keep the API paths proxied (`/api/v1`, `/profiles-api`). To call an API on another origin, set `OVPMON_CSP_CONNECT_EXTRA` (origins separated by spaces; see [Containers reference](../DOCS/Deployment/Containers/Reference.md)). The `app-ui` container listens on 8080 (`OVP_UI_PORT`) as the unprivileged user `nginx`; compose publishes it as `OVPMON_HTTP_PORT` (default 80).
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev
|
||||
# Access at http://localhost:5173
|
||||
npm ci # exact versions from package-lock.json (npm install after changing package.json)
|
||||
npm run dev # http://localhost:5173
|
||||
npm run build
|
||||
npm test # Vitest: formatters, CIDR parsing, 401 handling
|
||||
npm run lint # ESLint (minimal Vue rules)
|
||||
```
|
||||
|
||||
Node 20.19 or newer is required (Vite 7).
|
||||
|
||||
## Notes
|
||||
|
||||
- The session token is kept in `localStorage` (accepted risk, see `DOCS/General/Security_Architecture.md`).
|
||||
- Confirmations use `ConfirmModal`, notices use toasts (`useToast`); the native `confirm()` and SweetAlert2 are not used.
|
||||
- After changing the UI sources, refresh the committed build for system-service installs: `deploy/native/build-ui.sh --publish` (`deploy/native/check-ui.sh` shows whether it is stale).
|
||||
|
||||
## Documentation
|
||||
See `DOCS/UI/Architecture.md` for detailed architecture notes.
|
||||
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/bin/sh
|
||||
# Validates OVP_CSP_CONNECT_EXTRA: extra origins for the connect-src directive of the Content-Security-Policy
|
||||
# (compose: OVPMON_CSP_CONNECT_EXTRA). The value ends up in a response header, so only origins are accepted:
|
||||
# empty, or https://host[:port] and http://host[:port] separated by spaces (host: letters, digits, dots, hyphens;
|
||||
# no path, quotes, ; or commas). Anything else could inject another CSP directive.
|
||||
#
|
||||
# Runs as /docker-entrypoint.d/15-check-csp-connect-extra.sh in the app-ui image (before the template is
|
||||
# rendered by 20-envsubst-on-templates.sh) and from the all-in-one entrypoint. Exit code 1 stops the container.
|
||||
# The same rule is in deploy/docker/lib.sh and deploy/native/lib.sh (csp_extra_problem): keep them in step.
|
||||
set -eu
|
||||
|
||||
csp_extra_problem() {
|
||||
local _t _rest _host _port
|
||||
[ -n "$1" ] || return 0
|
||||
case "$1" in
|
||||
*[!A-Za-z0-9.:/\ -]*)
|
||||
printf 'contains characters that are not allowed (only letters, digits, . - : / and spaces; no quotes, ; or commas)'; return 1 ;;
|
||||
" "*|*" ")
|
||||
printf 'starts or ends with a space'; return 1 ;;
|
||||
esac
|
||||
set -f
|
||||
for _t in $1; do
|
||||
case "$_t" in
|
||||
https://*) _rest=${_t#https://} ;;
|
||||
http://*) _rest=${_t#http://} ;;
|
||||
*) set +f; printf "'%s' is not an origin (use https://host[:port] or http://host[:port])" "$_t"; return 1 ;;
|
||||
esac
|
||||
_host=${_rest%%:*}
|
||||
_port=""
|
||||
case "$_rest" in *:*) _port=${_rest#*:} ;; esac
|
||||
case "$_host" in
|
||||
""|*[!A-Za-z0-9.-]*) set +f; printf "'%s' has an invalid host (letters, digits, dots and hyphens; no path)" "$_t"; return 1 ;;
|
||||
esac
|
||||
if [ -n "$_port" ]; then
|
||||
case "$_port" in
|
||||
*[!0-9]*) set +f; printf "'%s' has an invalid port (digits only, no path)" "$_t"; return 1 ;;
|
||||
esac
|
||||
if [ "${#_port}" -gt 5 ] || [ "$_port" -lt 1 ] || [ "$_port" -gt 65535 ]; then
|
||||
set +f; printf "'%s' has a port out of range" "$_t"; return 1
|
||||
fi
|
||||
fi
|
||||
case "$_rest" in *:) set +f; printf "'%s' has an empty port" "$_t"; return 1 ;; esac
|
||||
done
|
||||
set +f
|
||||
return 0
|
||||
}
|
||||
|
||||
if ! _reason=$(csp_extra_problem "${OVP_CSP_CONNECT_EXTRA:-}"); then
|
||||
echo "check-csp-connect-extra: OVPMON_CSP_CONNECT_EXTRA is invalid: $_reason. Use origins https://host[:port] or http://host[:port] separated by spaces, or leave it empty" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,21 +1,58 @@
|
||||
server {
|
||||
listen 80;
|
||||
listen ${OVP_UI_PORT};
|
||||
server_name localhost;
|
||||
server_tokens off;
|
||||
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Security headers. add_header in a location replaces the ones inherited from the server block,
|
||||
# so the /assets/ location below repeats them. CSP: the bundle is served from this origin only;
|
||||
# style-src 'unsafe-inline' is needed by Bootstrap and Chart.js (inline style attributes).
|
||||
# connect-src is 'self' plus OVP_CSP_CONNECT_EXTRA (origins separated by spaces, empty by default): set it
|
||||
# only when config.json points the UI to an API on another origin (the defaults /api/v1 and /profiles-api are
|
||||
# proxied below, same origin). The value is validated by the deploy scripts and by the all-in-one entrypoint.
|
||||
# One policy ($csp) for both places.
|
||||
set $csp "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' ${OVP_CSP_CONNECT_EXTRA}; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'";
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "no-referrer" always;
|
||||
add_header Content-Security-Policy $csp always;
|
||||
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_types text/plain text/css text/javascript application/javascript application/json image/svg+xml;
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# Hashed build files never change under the same name
|
||||
location /assets/ {
|
||||
try_files $uri =404;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "no-referrer" always;
|
||||
add_header Content-Security-Policy $csp always;
|
||||
}
|
||||
|
||||
# The entry page and the runtime configuration must be revalidated after an update
|
||||
# (expires -1 sends "Cache-Control: no-cache" and keeps the server-level headers)
|
||||
location = /index.html {
|
||||
expires -1;
|
||||
}
|
||||
location = /config.json {
|
||||
expires -1;
|
||||
}
|
||||
|
||||
# Модуль 1: Мониторинг (Flask, порт 5001)
|
||||
location /api/ {
|
||||
proxy_pass http://${OVP_API_HOST}:${OVP_API_PORT};
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_pass_header Authorization;
|
||||
}
|
||||
|
||||
# Модуль 2: Управление профилями (FastAPI, порт 8000)
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import js from '@eslint/js';
|
||||
import pluginVue from 'eslint-plugin-vue';
|
||||
import globals from 'globals';
|
||||
|
||||
// Minimal rules: recommended JS + essential Vue (real errors only, no style rules)
|
||||
export default [
|
||||
{ ignores: ['dist/**', 'node_modules/**'] },
|
||||
js.configs.recommended,
|
||||
...pluginVue.configs['flat/essential'],
|
||||
{
|
||||
files: ['**/*.{js,vue}'],
|
||||
languageOptions: {
|
||||
globals: { ...globals.browser }
|
||||
},
|
||||
rules: {
|
||||
'vue/multi-word-component-names': 'off', // views are named after their route
|
||||
'no-unused-vars': ['warn', { args: 'none', caughtErrors: 'none' }]
|
||||
}
|
||||
},
|
||||
{
|
||||
files: ['**/*.test.js', 'eslint.config.js', 'vite.config.js'],
|
||||
languageOptions: {
|
||||
globals: { ...globals.node }
|
||||
}
|
||||
}
|
||||
];
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<link rel="icon" type="image/svg+xml" href="/logo.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>OpenVPN Controller</title>
|
||||
</head>
|
||||
|
||||
Generated
+1594
-16
File diff suppressed because it is too large.
Load diff
+9
-4
@@ -6,7 +6,9 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"lint": "eslint src"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fortawesome/fontawesome-free": "^7.1.0",
|
||||
@@ -14,13 +16,16 @@
|
||||
"bootstrap": "^5.3.8",
|
||||
"chart.js": "^4.5.1",
|
||||
"qrcode.vue": "^3.6.0",
|
||||
"sass": "^1.97.2",
|
||||
"sweetalert2": "^11.26.17",
|
||||
"vue": "^3.5.24",
|
||||
"vue-router": "^4.6.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"vite": "^7.2.4"
|
||||
"eslint": "^10.12.0",
|
||||
"eslint-plugin-vue": "^10.11.1",
|
||||
"globals": "^17.13.0",
|
||||
"vite": "^7.2.4",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
+12
-23
@@ -13,7 +13,7 @@
|
||||
<aside v-if="isAuthenticated" class="sidebar" :class="{ 'compact': isCompact }">
|
||||
<div class="sidebar-header">
|
||||
<img src="./assets/logo.svg" alt="OpenVPN" class="sidebar-brand-icon">
|
||||
<span class="brand-text">VPN Controller</span>
|
||||
<span class="brand-text">OpenVPN Controller</span>
|
||||
|
||||
<button class="btn btn-link text-muted d-md-none ms-auto" @click="isSidebarOpen = false">
|
||||
<i class="fas fa-times"></i>
|
||||
@@ -24,7 +24,6 @@
|
||||
|
||||
<!-- SECTION: MONITORING -->
|
||||
<div class="nav-section-header">MONITORING</div>
|
||||
<p></p>
|
||||
<router-link to="/" class="nav-link" active-class="active" title="Analytics">
|
||||
<i class="fas fa-chart-line"></i> <span>Analytics</span>
|
||||
</router-link>
|
||||
@@ -34,7 +33,6 @@
|
||||
|
||||
<!-- SECTION: CONFIGURATION -->
|
||||
<div class="nav-section-header mt-3">CONFIGURATION</div>
|
||||
<p></p>
|
||||
<router-link to="/config/pki" class="nav-link" active-class="active" title="PKI">
|
||||
<i class="fas fa-fingerprint"></i> <span>PKI</span>
|
||||
</router-link>
|
||||
@@ -48,7 +46,6 @@
|
||||
|
||||
<!-- SECTION: MANAGEMENT -->
|
||||
<div class="nav-section-header mt-3">MANAGEMENT</div>
|
||||
<p></p>
|
||||
<router-link to="/certificates" class="nav-link" active-class="active" title="Certificates">
|
||||
<i class="fas fa-certificate"></i> <span>Certificates</span>
|
||||
</router-link>
|
||||
@@ -61,7 +58,6 @@
|
||||
|
||||
<!-- SECTION: ACCOUNT -->
|
||||
<div class="nav-section-header mt-3">ACCOUNT</div>
|
||||
<p></p>
|
||||
<router-link to="/account" class="nav-link" active-class="active" title="Account Settings">
|
||||
<i class="fas fa-user-cog"></i> <span>Account Settings</span>
|
||||
</router-link>
|
||||
@@ -96,10 +92,10 @@
|
||||
<i class="fas fa-globe me-1 text-muted"></i>{{ timezoneAbbr }}
|
||||
</span>
|
||||
<button class="btn-header" @click="toggleTheme" title="Toggle Theme">
|
||||
<i class="fas" :class="isDark ? 'fa-sun' : 'fa-moon'" id="themeIcon"></i>
|
||||
<i class="fas" :class="isDark ? 'fa-sun' : 'fa-moon'"></i>
|
||||
</button>
|
||||
<button class="btn-header me-2" @click="refreshPage" title="Refresh">
|
||||
<i class="fas fa-sync-alt" id="refreshIcon"></i>
|
||||
<i class="fas fa-sync-alt"></i>
|
||||
</button>
|
||||
|
||||
<div class="header-divider d-none d-md-block"></div>
|
||||
@@ -138,11 +134,12 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import ToastContainer from './components/ToastContainer.vue';
|
||||
import { usePkiStatus } from './composables/usePkiStatus';
|
||||
import { useToast } from './composables/useToast';
|
||||
import { useTheme } from './composables/useTheme';
|
||||
|
||||
const { loadConfig, isLoaded } = useAppConfig();
|
||||
const { apiClient } = useApi();
|
||||
const timezoneAbbr = ref(new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2] || 'UTC');
|
||||
const isDark = ref(false);
|
||||
const { isDark, toggleTheme } = useTheme();
|
||||
const refreshKey = ref(0);
|
||||
const isSidebarOpen = ref(false);
|
||||
const isCompact = ref(false);
|
||||
@@ -151,7 +148,11 @@ const router = useRouter();
|
||||
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
|
||||
const toast = useToast();
|
||||
|
||||
const isAuthenticated = computed(() => route.name !== 'Login');
|
||||
// Signed in: a stored token on a non-public page (the token is not reactive: it is re-read on every navigation)
|
||||
const isAuthenticated = computed(() => {
|
||||
void route.fullPath;
|
||||
return !route.meta.public && !!localStorage.getItem('ovpmon_token');
|
||||
});
|
||||
const username = ref(localStorage.getItem('ovpmon_user') || '');
|
||||
|
||||
// Keep the header name in sync with the server (login, rename, stale session)
|
||||
@@ -183,13 +184,6 @@ const handleLogout = () => {
|
||||
router.push('/login');
|
||||
};
|
||||
|
||||
const toggleTheme = () => {
|
||||
isDark.value = !isDark.value;
|
||||
const theme = isDark.value ? 'dark' : 'light';
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
localStorage.setItem('theme', theme);
|
||||
};
|
||||
|
||||
const toggleSidebar = () => {
|
||||
isCompact.value = !isCompact.value;
|
||||
localStorage.setItem('sidebarCompact', isCompact.value);
|
||||
@@ -202,7 +196,7 @@ const refreshPage = () => {
|
||||
// Close sidebar on route change
|
||||
watch(() => route.path, () => {
|
||||
isSidebarOpen.value = false;
|
||||
if (route.name !== 'Login') {
|
||||
if (isAuthenticated.value) {
|
||||
syncUsername();
|
||||
refreshPkiStatus();
|
||||
}
|
||||
@@ -211,16 +205,11 @@ watch(() => route.path, () => {
|
||||
onMounted(async () => {
|
||||
await loadConfig();
|
||||
window.addEventListener('ovpmon-user-changed', onUserChanged);
|
||||
if (route.name !== 'Login') {
|
||||
if (isAuthenticated.value) {
|
||||
syncUsername();
|
||||
refreshPkiStatus();
|
||||
}
|
||||
|
||||
// Init Theme
|
||||
const savedTheme = localStorage.getItem('theme') || 'light';
|
||||
isDark.value = savedTheme === 'dark';
|
||||
document.documentElement.setAttribute('data-theme', savedTheme);
|
||||
|
||||
// Init Sidebar
|
||||
const savedCompact = localStorage.getItem('sidebarCompact');
|
||||
isCompact.value = savedCompact === 'true';
|
||||
|
||||
@@ -272,6 +272,11 @@ body {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* Space between a section header and its first link (also kept when the header is hidden in compact mode) */
|
||||
.nav-section-header + .nav-link {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
/* Compact Mode Styles */
|
||||
.sidebar.compact {
|
||||
width: 64px;
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, onUnmounted } from 'vue';
|
||||
import { ref, computed, onMounted, onUnmounted } from 'vue';
|
||||
import { Modal } from 'bootstrap';
|
||||
|
||||
const props = defineProps({
|
||||
@@ -40,11 +40,11 @@ const props = defineProps({
|
||||
}
|
||||
});
|
||||
|
||||
const emit = defineEmits(['close', 'opened', 'closed']);
|
||||
const emit = defineEmits(['opened', 'closed']);
|
||||
|
||||
const modalRef = ref(null);
|
||||
let bsModal = null;
|
||||
const sizeClass = props.size || '';
|
||||
const sizeClass = computed(() => props.size || '');
|
||||
|
||||
const show = () => {
|
||||
bsModal?.show();
|
||||
@@ -63,7 +63,6 @@ onMounted(() => {
|
||||
|
||||
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
||||
emit('closed');
|
||||
emit('close');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<BaseModal id="confirmModal" :title="title" ref="modal">
|
||||
<BaseModal :id="modalId" :title="title" ref="modal">
|
||||
<template #body>
|
||||
<p class="text-main" style="white-space: pre-line;">{{ message }}</p>
|
||||
</template>
|
||||
@@ -13,9 +13,11 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue';
|
||||
import { ref, useId } from 'vue';
|
||||
import BaseModal from './BaseModal.vue';
|
||||
|
||||
// Unique element id: several ConfirmModal instances may live on one page
|
||||
const modalId = `confirm-${useId()}`;
|
||||
const emit = defineEmits(['confirm']);
|
||||
const modal = ref(null);
|
||||
|
||||
|
||||
@@ -54,15 +54,12 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
|
||||
import Chart from 'chart.js/auto';
|
||||
import { ref, onMounted, onUnmounted } from 'vue';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import { useFormatters } from '../composables/useFormatters';
|
||||
import { useTrafficChart } from '../composables/useTrafficChart';
|
||||
import { Modal } from 'bootstrap';
|
||||
|
||||
const props = defineProps(['modelValue']); // If we wanted v-model control, but using manual open method for now
|
||||
const { fetchClientHistory } = useApi();
|
||||
const { parseServerDate } = useFormatters();
|
||||
|
||||
const modalRef = ref(null);
|
||||
const chartCanvas = ref(null);
|
||||
@@ -71,10 +68,10 @@ const range = ref('24h');
|
||||
const isSpeedMode = ref(false);
|
||||
const loading = ref(false);
|
||||
let bsModal = null;
|
||||
let chartInstance = null;
|
||||
let cachedData = null;
|
||||
let requestId = 0; // the latest request wins: a slow answer for an old range or client is dropped
|
||||
|
||||
const MAX_CHART_POINTS = 48;
|
||||
const chart = useTrafficChart(chartCanvas, { maxPoints: 48 });
|
||||
|
||||
const open = (name) => {
|
||||
clientName.value = name;
|
||||
@@ -90,159 +87,52 @@ const close = () => {
|
||||
|
||||
const loadHistory = async () => {
|
||||
if (!clientName.value) return;
|
||||
const id = ++requestId;
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await fetchClientHistory(clientName.value, range.value);
|
||||
if (id !== requestId) return;
|
||||
if (res.success && res.data.history) {
|
||||
cachedData = res.data.history;
|
||||
// Map the raw fields to the point format of useTrafficChart
|
||||
cachedData = res.data.history.map(p => ({
|
||||
timestamp: p.timestamp,
|
||||
bytes_received: p.bytes_received,
|
||||
bytes_sent: p.bytes_sent,
|
||||
rx_rate_mbps: p.bytes_received_rate_mbps,
|
||||
tx_rate_mbps: p.bytes_sent_rate_mbps
|
||||
}));
|
||||
renderChart();
|
||||
} else {
|
||||
cachedData = [];
|
||||
if (chartInstance) chartInstance.destroy();
|
||||
chart.destroy();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
if (id === requestId) console.error(e);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (id === requestId) loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const renderChart = () => {
|
||||
if (!chartCanvas.value || !cachedData) return;
|
||||
if (chartInstance) chartInstance.destroy();
|
||||
|
||||
const ctx = chartCanvas.value.getContext('2d');
|
||||
const downsampled = downsampleData(cachedData, MAX_CHART_POINTS);
|
||||
|
||||
const labels = [];
|
||||
const dataRx = [];
|
||||
const dataTx = [];
|
||||
|
||||
downsampled.forEach(point => {
|
||||
const d = parseServerDate(point.timestamp);
|
||||
let label = '';
|
||||
|
||||
if(range.value.includes('h') || range.value === '1d') {
|
||||
label = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
} else {
|
||||
label = d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' +
|
||||
d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
labels.push(label);
|
||||
|
||||
if (!isSpeedMode.value) {
|
||||
dataRx.push(point.bytes_received / (1024 * 1024)); // MB
|
||||
dataTx.push(point.bytes_sent / (1024 * 1024)); // MB
|
||||
} else {
|
||||
dataRx.push(point.bytes_received_rate_mbps);
|
||||
dataTx.push(point.bytes_sent_rate_mbps);
|
||||
}
|
||||
});
|
||||
|
||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
const gridColor = isDark ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0,0,0,0.05)';
|
||||
const textColor = isDark ? '#8b949e' : '#6c757d';
|
||||
|
||||
chartInstance = new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: !isSpeedMode.value ? 'Received (MB)' : 'RX Mbps',
|
||||
data: dataRx,
|
||||
borderColor: '#1652B8', // OpenVPN Blue
|
||||
backgroundColor: 'rgba(22, 82, 184, 0.15)',
|
||||
borderWidth: 2,
|
||||
fill: true,
|
||||
tension: 0.3,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 4
|
||||
},
|
||||
{
|
||||
label: !isSpeedMode.value ? 'Sent (MB)' : 'TX Mbps',
|
||||
data: dataTx,
|
||||
borderColor: '#EC7C31', // OpenVPN Orange
|
||||
backgroundColor: 'rgba(236, 124, 49, 0.15)',
|
||||
borderWidth: 2,
|
||||
fill: true,
|
||||
tension: 0.3,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 4
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
interaction: {
|
||||
mode: 'index',
|
||||
intersect: false,
|
||||
},
|
||||
plugins: {
|
||||
legend: { labels: { color: textColor } }
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
ticks: { color: textColor, maxTicksLimit: 8 },
|
||||
grid: { color: gridColor }
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: { color: textColor },
|
||||
grid: { color: gridColor }
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!cachedData) return;
|
||||
chart.render(cachedData, { range: range.value, speedMode: isSpeedMode.value });
|
||||
};
|
||||
|
||||
const downsampleData = (data, maxPoints) => {
|
||||
if (!data || data.length === 0) return [];
|
||||
if (data.length <= maxPoints) return data;
|
||||
|
||||
const blockSize = Math.ceil(data.length / maxPoints);
|
||||
const result = [];
|
||||
|
||||
for (let i = 0; i < data.length; i += blockSize) {
|
||||
const chunk = data.slice(i, i + blockSize);
|
||||
if (chunk.length === 0) continue;
|
||||
|
||||
let sumRx = 0, sumTx = 0;
|
||||
let maxRxRate = 0, maxTxRate = 0;
|
||||
|
||||
chunk.forEach(pt => {
|
||||
sumRx += (pt.bytes_received || 0);
|
||||
sumTx += (pt.bytes_sent || 0);
|
||||
maxRxRate = Math.max(maxRxRate, pt.bytes_received_rate_mbps || 0);
|
||||
maxTxRate = Math.max(maxTxRate, pt.bytes_sent_rate_mbps || 0);
|
||||
});
|
||||
|
||||
result.push({
|
||||
timestamp: chunk[0].timestamp,
|
||||
bytes_received: sumRx,
|
||||
bytes_sent: sumTx,
|
||||
bytes_received_rate_mbps: maxRxRate,
|
||||
bytes_sent_rate_mbps: maxTxRate
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
bsModal = new Modal(modalRef.value);
|
||||
|
||||
// Clean up chart on close
|
||||
// Clean up the chart on close and drop answers that are still on the way
|
||||
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
||||
if (chartInstance) {
|
||||
chartInstance.destroy();
|
||||
chartInstance = null;
|
||||
}
|
||||
requestId++;
|
||||
loading.value = false;
|
||||
cachedData = null;
|
||||
chart.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
if (chartInstance) chartInstance.destroy();
|
||||
requestId++;
|
||||
bsModal?.dispose();
|
||||
});
|
||||
|
||||
defineExpose({ open, close });
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
<template>
|
||||
<BaseModal id="newClientModal" title="Create New Client" ref="modal">
|
||||
<BaseModal id="newClientModal" title="Create New Client" ref="modal" @opened="inputRef?.focus()">
|
||||
<template #body>
|
||||
<div class="mb-3">
|
||||
<label for="clientName" class="form-label small text-muted text-uppercase fw-bold">Client Name</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
||||
<input type="text" class="form-control" id="clientName" v-model="clientName" placeholder="e.g. laptop-user" @keyup.enter="confirm" ref="inputRef">
|
||||
<input type="text" class="form-control" :class="{ 'is-invalid': clientName && !isValid }" id="clientName"
|
||||
v-model="clientName" placeholder="e.g. laptop-user" maxlength="64" autocomplete="off" @keyup.enter="confirm" ref="inputRef">
|
||||
</div>
|
||||
<div v-if="clientName && !isValid" class="text-danger small mt-2">
|
||||
Letters, digits, dashes and underscores only; the first character must be a letter or a digit.
|
||||
</div>
|
||||
<div class="form-text mt-2 text-muted small">
|
||||
<i class="fas fa-info-circle me-1"></i> Use only alphanumeric characters, dashes, or underscores.
|
||||
@@ -14,7 +18,7 @@
|
||||
</template>
|
||||
<template #footer>
|
||||
<button type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
|
||||
<button type="button" class="btn-action btn-action-save" @click="confirm" :disabled="!clientName">
|
||||
<button type="button" class="btn-action btn-action-save" @click="confirm" :disabled="!isValid">
|
||||
Create Client
|
||||
</button>
|
||||
</template>
|
||||
@@ -22,7 +26,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue';
|
||||
import { ref, computed } from 'vue';
|
||||
import BaseModal from './BaseModal.vue';
|
||||
|
||||
const emit = defineEmits(['create']);
|
||||
@@ -30,10 +34,13 @@ const modal = ref(null);
|
||||
const clientName = ref('');
|
||||
const inputRef = ref(null);
|
||||
|
||||
// Same rule as the profiler API (without dots): 1-64 characters, no leading dash or underscore
|
||||
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
||||
const isValid = computed(() => NAME_RE.test(clientName.value));
|
||||
|
||||
const open = () => {
|
||||
clientName.value = '';
|
||||
modal.value.show();
|
||||
setTimeout(() => inputRef.value?.focus(), 500);
|
||||
modal.value.show(); // the input is focused on the opened event
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
@@ -41,7 +48,7 @@ const close = () => {
|
||||
};
|
||||
|
||||
const confirm = () => {
|
||||
if (clientName.value) {
|
||||
if (isValid.value) {
|
||||
emit('create', clientName.value);
|
||||
close();
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<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>
|
||||
<StatusBadge v-if="profile" :profile="profile" />
|
||||
</div>
|
||||
</template>
|
||||
<template #body>
|
||||
@@ -36,6 +36,7 @@
|
||||
<script setup>
|
||||
import { ref, computed } from 'vue';
|
||||
import BaseModal from './BaseModal.vue';
|
||||
import StatusBadge from './StatusBadge.vue';
|
||||
|
||||
const emit = defineEmits(['save']);
|
||||
const modal = ref(null);
|
||||
@@ -44,14 +45,6 @@ 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 '';
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<template>
|
||||
<span class="status-badge" :class="badge.cls">
|
||||
<i class="fas me-1" :class="badge.icon"></i>{{ badge.label }}
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed } from 'vue';
|
||||
|
||||
const props = defineProps({
|
||||
// Profile as returned by GET /profiles
|
||||
profile: {
|
||||
type: Object,
|
||||
required: true
|
||||
}
|
||||
});
|
||||
|
||||
const badge = computed(() => {
|
||||
const p = props.profile;
|
||||
if (p.is_revoked) return { label: 'Revoked', cls: 'status-expired', icon: 'fa-ban' };
|
||||
if (p.is_expired) return { label: 'Expired', cls: 'status-expired', icon: 'fa-times-circle' };
|
||||
if (p.days_remaining != null && p.days_remaining <= 30) {
|
||||
return { label: 'Expiring Soon', cls: 'status-warning', icon: 'fa-exclamation-triangle' };
|
||||
}
|
||||
return { label: 'Active', cls: 'status-valid', icon: 'fa-check-circle' };
|
||||
});
|
||||
</script>
|
||||
@@ -4,13 +4,35 @@ import { useAppConfig } from './useAppConfig';
|
||||
// Singleton instances
|
||||
const apiClient = axios.create();
|
||||
const profilesApiClient = axios.create();
|
||||
// Auth endpoints (/api/auth): login, 2FA, password and username changes
|
||||
const authApiClient = axios.create();
|
||||
|
||||
// Helper to get base URLs
|
||||
const getBaseUrl = (config) => config?.api_base_url || 'http://localhost:5001/api/v1';
|
||||
const getProfilesBaseUrl = (config) => config?.profiles_api_base_url || 'http://localhost:8000';
|
||||
// The auth routes sit next to the API root: /api/v1 -> /api/auth
|
||||
const getAuthBaseUrl = (config) => {
|
||||
const base = getBaseUrl(config).replace(/\/+$/, '');
|
||||
return /\/v1$/.test(base) ? base.replace(/\/v1$/, '/auth') : base + '/../auth';
|
||||
};
|
||||
|
||||
// Add interceptors to handle Auth and Dynamic Base URLs
|
||||
const setupInterceptors = (instance, getBase) => {
|
||||
// 401 on a regular API request: the session is gone, clear it and go to the login page
|
||||
export const handleUnauthorized = (error) => {
|
||||
if (error.response && error.response.status === 401) {
|
||||
localStorage.removeItem('ovpmon_token');
|
||||
localStorage.removeItem('ovpmon_user');
|
||||
// Redirecting using window.location for absolute refresh
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
};
|
||||
|
||||
// Add interceptors to handle Auth and Dynamic Base URLs.
|
||||
// endSessionOn401 is false for authApiClient: /auth/* answers 401 for a wrong current password or
|
||||
// 2FA code (login, change-password, change-username). That is a form error, not an expired session.
|
||||
const setupInterceptors = (instance, getBase, { endSessionOn401 = true } = {}) => {
|
||||
instance.interceptors.request.use((reqConfig) => {
|
||||
const { config } = useAppConfig();
|
||||
reqConfig.baseURL = getBase(config.value);
|
||||
@@ -22,24 +44,14 @@ const setupInterceptors = (instance, getBase) => {
|
||||
return reqConfig;
|
||||
});
|
||||
|
||||
instance.interceptors.response.use(
|
||||
response => response,
|
||||
error => {
|
||||
if (error.response && error.response.status === 401) {
|
||||
localStorage.removeItem('ovpmon_token');
|
||||
localStorage.removeItem('ovpmon_user');
|
||||
// Redirecting using window.location for absolute refresh
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login';
|
||||
if (endSessionOn401) {
|
||||
instance.interceptors.response.use(response => response, handleUnauthorized);
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
setupInterceptors(apiClient, getBaseUrl);
|
||||
setupInterceptors(profilesApiClient, getProfilesBaseUrl);
|
||||
setupInterceptors(authApiClient, getAuthBaseUrl, { endSessionOn401: false });
|
||||
|
||||
export function useApi() {
|
||||
const fetchStats = async () => {
|
||||
@@ -59,13 +71,14 @@ export function useApi() {
|
||||
|
||||
const fetchCertificates = async () => {
|
||||
const res = await profilesApiClient.get('/profiles');
|
||||
return res.data;
|
||||
// GET /profiles returns a plain array (not the {success, data} envelope of the monitoring API)
|
||||
return Array.isArray(res.data) ? res.data : [];
|
||||
};
|
||||
|
||||
|
||||
return {
|
||||
apiClient,
|
||||
profilesApiClient,
|
||||
authApiClient,
|
||||
fetchStats,
|
||||
fetchClientHistory,
|
||||
fetchAnalytics,
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { AxiosError } from 'axios';
|
||||
|
||||
const store = {};
|
||||
let location;
|
||||
|
||||
beforeEach(() => {
|
||||
for (const k of Object.keys(store)) delete store[k];
|
||||
store.ovpmon_token = 'tok';
|
||||
store.ovpmon_user = 'admin';
|
||||
location = { pathname: '/account', href: '/account' };
|
||||
vi.stubGlobal('localStorage', {
|
||||
getItem: (k) => (k in store ? store[k] : null),
|
||||
setItem: (k, v) => { store[k] = String(v); },
|
||||
removeItem: (k) => { delete store[k]; }
|
||||
});
|
||||
vi.stubGlobal('window', { location });
|
||||
});
|
||||
|
||||
// Make the client answer with the given status without any network
|
||||
const failWith = async (client, status, url) => {
|
||||
client.defaults.adapter = (config) => Promise.reject(
|
||||
new AxiosError('failed', 'ERR_BAD_REQUEST', config, null, { status, data: {}, config })
|
||||
);
|
||||
await client.post(url).catch(() => {});
|
||||
};
|
||||
|
||||
describe('401 handling', () => {
|
||||
it('keeps the session on 401 from /auth/* (wrong password or 2FA code)', async () => {
|
||||
const { useApi } = await import('./useApi');
|
||||
await failWith(useApi().authApiClient, 401, '/change-password');
|
||||
expect(store.ovpmon_token).toBe('tok');
|
||||
expect(location.href).toBe('/account');
|
||||
});
|
||||
|
||||
it('ends the session on 401 from other requests', async () => {
|
||||
const { useApi } = await import('./useApi');
|
||||
await failWith(useApi().apiClient, 401, '/stats');
|
||||
expect(store.ovpmon_token).toBeUndefined();
|
||||
expect(location.href).toBe('/login');
|
||||
});
|
||||
|
||||
it('builds the auth base URL next to the API root', async () => {
|
||||
const { useApi } = await import('./useApi');
|
||||
let seen;
|
||||
const client = useApi().authApiClient;
|
||||
client.defaults.adapter = (config) => { seen = config; return Promise.resolve({ status: 200, data: {}, config }); };
|
||||
await client.post('/login');
|
||||
expect(seen.baseURL).toBe('http://localhost:5001/api/auth');
|
||||
});
|
||||
|
||||
it('ignores other error codes', async () => {
|
||||
const { useApi } = await import('./useApi');
|
||||
await failWith(useApi().profilesApiClient, 500, '/profiles');
|
||||
expect(store.ovpmon_token).toBe('tok');
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,17 @@
|
||||
export function useFormatters() {
|
||||
function formatBytes(bytes, decimals = 2) {
|
||||
if (bytes === 0) return '0 B';
|
||||
const value = Number(bytes);
|
||||
// null, undefined, NaN and negative values are shown as zero
|
||||
if (!Number.isFinite(value) || value <= 0) return '0 B';
|
||||
const k = 1024;
|
||||
const dm = decimals < 0 ? 0 : decimals;
|
||||
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
|
||||
const i = Math.min(Math.max(Math.floor(Math.log(value) / Math.log(k)), 0), sizes.length - 1);
|
||||
return parseFloat((value / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
function formatRate(rate) {
|
||||
return parseFloat(rate).toFixed(3) + ' Mbps';
|
||||
return (parseFloat(rate) || 0).toFixed(3) + ' Mbps';
|
||||
}
|
||||
|
||||
function parseServerDate(dateStr) {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { useFormatters } from './useFormatters';
|
||||
|
||||
const { formatBytes, formatRate } = useFormatters();
|
||||
|
||||
describe('formatBytes', () => {
|
||||
it('formats regular values', () => {
|
||||
expect(formatBytes(1536)).toBe('1.5 KB');
|
||||
expect(formatBytes(5 * 1024 * 1024)).toBe('5 MB');
|
||||
});
|
||||
|
||||
it('shows zero for empty, non-numeric and negative values', () => {
|
||||
for (const v of [0, null, undefined, NaN, 'abc', -5, Infinity]) {
|
||||
expect(formatBytes(v)).toBe('0 B');
|
||||
}
|
||||
});
|
||||
|
||||
it('stays inside the unit table', () => {
|
||||
expect(formatBytes(0.5)).toBe('0.5 B');
|
||||
expect(formatBytes(Math.pow(1024, 6))).toMatch(/ TB$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatRate', () => {
|
||||
it('does not produce NaN', () => {
|
||||
expect(formatRate(1.23456)).toBe('1.235 Mbps');
|
||||
expect(formatRate(null)).toBe('0.000 Mbps');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { ref, onMounted, onUnmounted } from 'vue';
|
||||
|
||||
const STORAGE_KEY = 'theme';
|
||||
|
||||
const isDark = ref(false);
|
||||
|
||||
const apply = (theme) => {
|
||||
isDark.value = theme === 'dark';
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
};
|
||||
|
||||
// Saved choice first, then the system setting (prefers-color-scheme) on the first visit.
|
||||
// Called from main.js before the app is mounted, so the page never flashes in the wrong theme.
|
||||
export const initTheme = () => {
|
||||
let theme = null;
|
||||
try { theme = localStorage.getItem(STORAGE_KEY); } catch (e) { /* storage blocked */ }
|
||||
if (theme !== 'dark' && theme !== 'light') {
|
||||
theme = window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
apply(theme);
|
||||
};
|
||||
|
||||
const toggleTheme = () => {
|
||||
const theme = isDark.value ? 'light' : 'dark';
|
||||
apply(theme);
|
||||
try { localStorage.setItem(STORAGE_KEY, theme); } catch (e) { /* storage blocked */ }
|
||||
};
|
||||
|
||||
export function useTheme() {
|
||||
return { isDark, toggleTheme };
|
||||
}
|
||||
|
||||
// Call `callback` whenever data-theme of <html> changes; the observer is released with the component
|
||||
export function useThemeObserver(callback) {
|
||||
let observer = null;
|
||||
onMounted(() => {
|
||||
observer = new MutationObserver((mutations) => {
|
||||
if (mutations.some(m => m.attributeName === 'data-theme')) callback();
|
||||
});
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
||||
});
|
||||
onUnmounted(() => observer?.disconnect());
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import { onUnmounted } from 'vue';
|
||||
import Chart from 'chart.js/auto';
|
||||
import { useFormatters } from './useFormatters';
|
||||
|
||||
export const COLOR_RX = '#1652B8'; // OpenVPN Blue
|
||||
export const COLOR_TX = '#EC7C31'; // Brand Orange
|
||||
|
||||
const MB = 1024 * 1024;
|
||||
|
||||
// Chart colors depend on the page theme (data-theme of <html>)
|
||||
export const getThemeColors = () => {
|
||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
return {
|
||||
isDark,
|
||||
gridColor: isDark ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0,0,0,0.05)',
|
||||
textColor: isDark ? '#8b949e' : '#6c757d'
|
||||
};
|
||||
};
|
||||
|
||||
// Points: { timestamp, bytes_received, bytes_sent, rx_rate_mbps, tx_rate_mbps }.
|
||||
// Blocks of points are merged: traffic is summed, speed takes the block maximum.
|
||||
export const downsamplePoints = (points, maxPoints) => {
|
||||
if (!points || points.length === 0) return [];
|
||||
if (points.length <= maxPoints) return points;
|
||||
|
||||
const blockSize = Math.ceil(points.length / maxPoints);
|
||||
const result = [];
|
||||
|
||||
for (let i = 0; i < points.length; i += blockSize) {
|
||||
const chunk = points.slice(i, i + blockSize);
|
||||
if (chunk.length === 0) continue;
|
||||
|
||||
let sumRx = 0, sumTx = 0;
|
||||
let maxRxRate = 0, maxTxRate = 0;
|
||||
|
||||
chunk.forEach(pt => {
|
||||
sumRx += (pt.bytes_received || 0);
|
||||
sumTx += (pt.bytes_sent || 0);
|
||||
maxRxRate = Math.max(maxRxRate, pt.rx_rate_mbps || 0);
|
||||
maxTxRate = Math.max(maxTxRate, pt.tx_rate_mbps || 0);
|
||||
});
|
||||
|
||||
result.push({
|
||||
timestamp: chunk[0].timestamp,
|
||||
bytes_received: sumRx,
|
||||
bytes_sent: sumTx,
|
||||
rx_rate_mbps: maxRxRate,
|
||||
tx_rate_mbps: maxTxRate
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// Ranges of 1h/3h/24h come from raw samples (peak speed); longer ones (7d, 30d) from aggregates
|
||||
// that keep only bytes, so their speed is the average of a bucket and is labelled "(avg)".
|
||||
export const isAveragedRange = (range) => {
|
||||
const m = /^(\d+)([hd])$/.exec(range || '');
|
||||
if (!m) return false;
|
||||
return Number(m[1]) * (m[2] === 'd' ? 24 : 1) > 24;
|
||||
};
|
||||
|
||||
// Line chart of received/sent traffic bound to a canvas ref.
|
||||
// const chart = useTrafficChart(canvasRef, { maxPoints: 96 });
|
||||
// chart.render(points, { range: '24h', speedMode: false });
|
||||
// The chart is destroyed together with the component.
|
||||
export function useTrafficChart(canvasRef, { maxPoints }) {
|
||||
const { parseServerDate } = useFormatters();
|
||||
let instance = null;
|
||||
|
||||
const destroy = () => {
|
||||
if (instance) {
|
||||
instance.destroy();
|
||||
instance = null;
|
||||
}
|
||||
};
|
||||
|
||||
const formatLabel = (timestamp, range) => {
|
||||
const d = parseServerDate(timestamp);
|
||||
const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
if (range.includes('h') || range === '1d') return time;
|
||||
return d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' + time;
|
||||
};
|
||||
|
||||
const render = (points, { range, speedMode }) => {
|
||||
if (!canvasRef.value) return;
|
||||
destroy();
|
||||
|
||||
const labels = [];
|
||||
const dataRx = [];
|
||||
const dataTx = [];
|
||||
|
||||
downsamplePoints(points, maxPoints).forEach(point => {
|
||||
labels.push(formatLabel(point.timestamp, range));
|
||||
if (!speedMode) {
|
||||
dataRx.push(point.bytes_received / MB);
|
||||
dataTx.push(point.bytes_sent / MB);
|
||||
} else {
|
||||
dataRx.push(point.rx_rate_mbps || 0);
|
||||
dataTx.push(point.tx_rate_mbps || 0);
|
||||
}
|
||||
});
|
||||
|
||||
const { gridColor, textColor } = getThemeColors();
|
||||
const speedSuffix = isAveragedRange(range) ? ' (avg)' : '';
|
||||
const dataset = (label, data, color, fill) => ({
|
||||
label,
|
||||
data,
|
||||
borderColor: color,
|
||||
backgroundColor: fill,
|
||||
borderWidth: 2,
|
||||
fill: true,
|
||||
tension: 0.3,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 4
|
||||
});
|
||||
|
||||
instance = new Chart(canvasRef.value.getContext('2d'), {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels,
|
||||
datasets: [
|
||||
dataset(speedMode ? `RX Mbps${speedSuffix}` : 'Received (MB)', dataRx, COLOR_RX, 'rgba(22, 82, 184, 0.15)'),
|
||||
dataset(speedMode ? `TX Mbps${speedSuffix}` : 'Sent (MB)', dataTx, COLOR_TX, 'rgba(236, 124, 49, 0.15)')
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
plugins: { legend: { labels: { color: textColor } } },
|
||||
scales: {
|
||||
x: { ticks: { color: textColor, maxTicksLimit: 8 }, grid: { color: gridColor } },
|
||||
y: { beginAtZero: true, ticks: { color: textColor }, grid: { color: gridColor } }
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
onUnmounted(destroy);
|
||||
|
||||
return { render, destroy };
|
||||
}
|
||||
+3
-16
@@ -8,23 +8,10 @@ import 'bootstrap/dist/js/bootstrap.bundle.min.js';
|
||||
import '@fortawesome/fontawesome-free/css/all.min.css';
|
||||
|
||||
import './assets/main.css';
|
||||
import axios from 'axios';
|
||||
import { initTheme } from './composables/useTheme';
|
||||
|
||||
// Global Axios Defaults (No Base URL - handled by useApi.js)
|
||||
// We keep global error handling for 401s as a fallback
|
||||
axios.interceptors.response.use(
|
||||
response => response,
|
||||
error => {
|
||||
if (error.response && error.response.status === 401) {
|
||||
localStorage.removeItem('ovpmon_token');
|
||||
localStorage.removeItem('ovpmon_user');
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
// Theme is applied before mounting: no flash of the wrong theme
|
||||
initTheme();
|
||||
|
||||
const app = createApp(App);
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
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';
|
||||
@@ -13,7 +12,7 @@ const routes = [
|
||||
{
|
||||
path: '/clients',
|
||||
name: 'Clients',
|
||||
component: Clients
|
||||
component: () => import('../views/Clients.vue')
|
||||
},
|
||||
{
|
||||
path: '/certificates',
|
||||
@@ -52,6 +51,11 @@ const routes = [
|
||||
name: 'Login',
|
||||
component: Login,
|
||||
meta: { public: true }
|
||||
},
|
||||
// Unknown address: back to the start page (the guard sends guests to the login page)
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
redirect: '/'
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// IPv4 helpers for the VPN subnet field: "a.b.c.d/nn" <-> network address + dotted netmask.
|
||||
|
||||
const IPV4 = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
|
||||
|
||||
// 24 -> '255.255.255.0'; null for a value outside 0..32
|
||||
export function cidrToMask(bits) {
|
||||
const n = Number(bits);
|
||||
if (bits === '' || bits === null || !Number.isInteger(n) || n < 0 || n > 32) return null;
|
||||
const mask = n === 0 ? 0 : (0xFFFFFFFF << (32 - n)) >>> 0;
|
||||
return [24, 16, 8, 0].map(shift => (mask >>> shift) & 255).join('.');
|
||||
}
|
||||
|
||||
// '255.255.255.0' -> 24; null for a malformed or non-contiguous mask
|
||||
export function maskToCidr(mask) {
|
||||
if (typeof mask !== 'string' || !IPV4.test(mask)) return null;
|
||||
const value = mask.split('.').reduce((acc, p) => ((acc << 8) | Number(p)) >>> 0, 0);
|
||||
let bits = 0;
|
||||
while (bits < 32 && (value & (0x80000000 >>> bits))) bits++;
|
||||
// The rest must be zeros, otherwise the mask is not contiguous
|
||||
const expected = bits === 0 ? 0 : (0xFFFFFFFF << (32 - bits)) >>> 0;
|
||||
return value === expected ? bits : null;
|
||||
}
|
||||
|
||||
// '172.20.1.0/24' -> { network: '172.20.1.0', netmask: '255.255.255.0' }
|
||||
// '172.20.1.0' -> { network: '172.20.1.0', netmask: null } (no suffix: the caller keeps the current mask)
|
||||
// anything else -> null
|
||||
export function parseCidr(value) {
|
||||
const text = String(value ?? '').trim();
|
||||
const [network, suffix, ...rest] = text.split('/');
|
||||
if (rest.length || !IPV4.test(network)) return null;
|
||||
if (suffix === undefined) return { network, netmask: null };
|
||||
const netmask = cidrToMask(suffix);
|
||||
return netmask ? { network, netmask } : null;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { cidrToMask, maskToCidr, parseCidr } from './cidr';
|
||||
|
||||
describe('cidrToMask / maskToCidr', () => {
|
||||
it('converts a suffix to a netmask and back', () => {
|
||||
for (const [bits, mask] of [[8, '255.0.0.0'], [22, '255.255.252.0'], [24, '255.255.255.0'], [30, '255.255.255.252']]) {
|
||||
expect(cidrToMask(bits)).toBe(mask);
|
||||
expect(maskToCidr(mask)).toBe(bits);
|
||||
}
|
||||
expect(cidrToMask(0)).toBe('0.0.0.0');
|
||||
expect(cidrToMask(32)).toBe('255.255.255.255');
|
||||
});
|
||||
|
||||
it('rejects out-of-range suffixes and non-contiguous masks', () => {
|
||||
for (const v of [-1, 33, 'x', '', null]) expect(cidrToMask(v)).toBeNull();
|
||||
expect(maskToCidr('255.0.255.0')).toBeNull();
|
||||
expect(maskToCidr('255.255.255')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseCidr', () => {
|
||||
it('splits the address and the mask', () => {
|
||||
expect(parseCidr('172.20.1.0/24')).toEqual({ network: '172.20.1.0', netmask: '255.255.255.0' });
|
||||
expect(parseCidr(' 10.8.0.0/22 ')).toEqual({ network: '10.8.0.0', netmask: '255.255.252.0' });
|
||||
});
|
||||
|
||||
it('keeps the mask empty when there is no suffix', () => {
|
||||
expect(parseCidr('10.8.0.0')).toEqual({ network: '10.8.0.0', netmask: null });
|
||||
});
|
||||
|
||||
it('rejects malformed input', () => {
|
||||
for (const v of ['', 'abc', '10.8.0.0/', '10.8.0.0/33', '10.8.0/24', '300.1.1.1/24', '10.8.0.0/24/1']) {
|
||||
expect(parseCidr(v)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
// Multi-session helpers for the Clients page
|
||||
|
||||
// Badge "xN" is shown only when a client has more than one session
|
||||
export const sessionsBadge = (c) => (c.sessions_count > 1 ? `×${c.sessions_count}` : null);
|
||||
|
||||
// Toggle a client in the set of expanded rows (returns a new array)
|
||||
export const toggleExpanded = (expanded, name) =>
|
||||
expanded.includes(name) ? expanded.filter(n => n !== name) : [...expanded, name];
|
||||
|
||||
// Sessions to render under a client row: only when expanded and there is more than one
|
||||
export const visibleSessions = (c, expanded) =>
|
||||
(c.sessions_count > 1 && expanded.includes(c.common_name)) ? (c.sessions || []) : [];
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { sessionsBadge, toggleExpanded, visibleSessions } from './sessions';
|
||||
|
||||
describe('multi-session display', () => {
|
||||
const multi = { common_name: 'alice', sessions_count: 2, sessions: [{ real_address: 'a' }, { real_address: 'b' }] };
|
||||
const single = { common_name: 'bob', sessions_count: 1, sessions: [{ real_address: 'c' }] };
|
||||
|
||||
it('shows the badge only for more than one session', () => {
|
||||
expect(sessionsBadge(multi)).toBe('×2');
|
||||
expect(sessionsBadge(single)).toBeNull();
|
||||
expect(sessionsBadge({ common_name: 'old' })).toBeNull();
|
||||
});
|
||||
|
||||
it('expands and collapses the session list on click', () => {
|
||||
expect(visibleSessions(multi, [])).toEqual([]);
|
||||
const open = toggleExpanded([], 'alice');
|
||||
expect(visibleSessions(multi, open)).toHaveLength(2);
|
||||
expect(visibleSessions(multi, toggleExpanded(open, 'alice'))).toEqual([]);
|
||||
expect(visibleSessions(single, ['bob'])).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -50,7 +50,7 @@
|
||||
<h4 class="m-0 text-heading">Secure Your Account</h4>
|
||||
</div>
|
||||
<div class="card-interior-description">
|
||||
<p class="text-muted m-0">Protect your OpenVPN Monitor dashboard with second-layer security using Google Authenticator or any TOTP app.</p>
|
||||
<p class="text-muted m-0">Protect your OpenVPN Controller dashboard with second-layer security using Google Authenticator or any TOTP app.</p>
|
||||
</div>
|
||||
<button class="btn btn-action btn-action-primary py-2 fw-bold btn-account-action" @click="initSetup" :disabled="loading">
|
||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
||||
@@ -87,6 +87,9 @@
|
||||
v-model="otp"
|
||||
placeholder="000000"
|
||||
maxlength="6"
|
||||
inputmode="numeric"
|
||||
autocomplete="one-time-code"
|
||||
aria-label="6-digit authentication code"
|
||||
>
|
||||
<button class="btn btn-action btn-action-primary px-4 fw-bold" @click="verifyAndEnable" :disabled="loading">
|
||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
||||
@@ -117,10 +120,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Alerts/Notifications Modal -->
|
||||
<ConfirmModal ref="confirmModal" />
|
||||
|
||||
<!-- Action Confirmations Modal -->
|
||||
<!-- Confirmation before 2FA is disabled; results are shown as toasts -->
|
||||
<ConfirmModal ref="disable2FAModal" @confirm="handleDisable2FA" />
|
||||
|
||||
<!-- Password Change Modal -->
|
||||
@@ -134,6 +134,7 @@
|
||||
class="form-control"
|
||||
v-model="passwordForm.current_password"
|
||||
placeholder="Enter current password"
|
||||
autocomplete="current-password"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
@@ -144,6 +145,7 @@
|
||||
class="form-control"
|
||||
v-model="passwordForm.new_password"
|
||||
placeholder="Min. 8 characters"
|
||||
autocomplete="new-password"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
@@ -154,6 +156,7 @@
|
||||
class="form-control"
|
||||
v-model="passwordForm.confirm_password"
|
||||
placeholder="Confirm new password"
|
||||
autocomplete="new-password"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
@@ -191,6 +194,7 @@
|
||||
class="form-control"
|
||||
v-model="usernameForm.current_password"
|
||||
placeholder="Enter current password"
|
||||
autocomplete="current-password"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
@@ -223,16 +227,16 @@
|
||||
import { ref, onMounted, reactive } from 'vue';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import QrcodeVue from 'qrcode.vue';
|
||||
import Swal from 'sweetalert2';
|
||||
import BaseModal from '../components/BaseModal.vue';
|
||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||
import { useToast } from '../composables/useToast';
|
||||
|
||||
const { apiClient } = useApi();
|
||||
const { apiClient, authApiClient } = useApi();
|
||||
const toast = useToast();
|
||||
|
||||
// UI Refs
|
||||
const pwModal = ref(null);
|
||||
const userModal = ref(null);
|
||||
const confirmModal = ref(null);
|
||||
const disable2FAModal = ref(null);
|
||||
|
||||
// Password Logic
|
||||
@@ -252,36 +256,21 @@ const showPwModal = () => {
|
||||
|
||||
const handleChangePassword = async () => {
|
||||
if (passwordForm.new_password !== passwordForm.confirm_password) {
|
||||
Swal.fire({
|
||||
title: 'Error!',
|
||||
text: 'New passwords do not match',
|
||||
icon: 'error',
|
||||
confirmButtonColor: '#EC7C31'
|
||||
});
|
||||
toast.show('New passwords do not match', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
pwLoading.value = true;
|
||||
try {
|
||||
await apiClient.post('../auth/change-password', {
|
||||
await authApiClient.post('/change-password', {
|
||||
current_password: passwordForm.current_password,
|
||||
new_password: passwordForm.new_password
|
||||
});
|
||||
|
||||
pwModal.value.hide();
|
||||
Swal.fire({
|
||||
title: 'Success!',
|
||||
text: 'Password updated successfully.',
|
||||
icon: 'success',
|
||||
confirmButtonColor: '#1652B8'
|
||||
});
|
||||
toast.show('Password updated successfully.', 'success');
|
||||
} catch (err) {
|
||||
Swal.fire({
|
||||
title: 'Failed',
|
||||
text: err.response?.data?.error || 'Failed to update password',
|
||||
icon: 'error',
|
||||
confirmButtonColor: '#cf222e'
|
||||
});
|
||||
toast.show(err.response?.data?.error || 'Failed to update password', 'error');
|
||||
} finally {
|
||||
pwLoading.value = false;
|
||||
}
|
||||
@@ -300,18 +289,13 @@ const showUserModal = () => {
|
||||
|
||||
const handleChangeUsername = async () => {
|
||||
if (!/^[A-Za-z][A-Za-z0-9_.-]{2,31}$/.test(usernameForm.new_username)) {
|
||||
Swal.fire({
|
||||
title: 'Error!',
|
||||
text: 'Username must be 3-32 chars, start with a letter, and contain only letters, digits, . _ -',
|
||||
icon: 'error',
|
||||
confirmButtonColor: '#EC7C31'
|
||||
});
|
||||
toast.show('Username must be 3-32 chars, start with a letter, and contain only letters, digits, . _ -', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
userLoading.value = true;
|
||||
try {
|
||||
const res = await apiClient.post('../auth/change-username', {
|
||||
const res = await authApiClient.post('/change-username', {
|
||||
new_username: usernameForm.new_username,
|
||||
current_password: usernameForm.current_password,
|
||||
otp: usernameForm.otp || undefined
|
||||
@@ -320,19 +304,9 @@ const handleChangeUsername = async () => {
|
||||
try { localStorage.setItem('ovpmon_user', res.data.username); } catch (e) { /* ignore */ }
|
||||
window.dispatchEvent(new Event('ovpmon-user-changed'));
|
||||
userModal.value.hide();
|
||||
Swal.fire({
|
||||
title: 'Success!',
|
||||
text: 'Username updated. Use the new username the next time you sign in.',
|
||||
icon: 'success',
|
||||
confirmButtonColor: '#1652B8'
|
||||
});
|
||||
toast.show('Username updated. Use the new username the next time you sign in.', 'success');
|
||||
} catch (err) {
|
||||
Swal.fire({
|
||||
title: 'Failed',
|
||||
text: err.response?.data?.error || 'Failed to update username',
|
||||
icon: 'error',
|
||||
confirmButtonColor: '#cf222e'
|
||||
});
|
||||
toast.show(err.response?.data?.error || 'Failed to update username', 'error');
|
||||
} finally {
|
||||
userLoading.value = false;
|
||||
}
|
||||
@@ -344,7 +318,6 @@ const step2 = ref(false);
|
||||
const loading = ref(false);
|
||||
const otp = ref('');
|
||||
const setupData = ref({ secret: '', uri: '' });
|
||||
const isDark = ref(document.documentElement.getAttribute('data-theme') === 'dark');
|
||||
|
||||
const fetchUserStatus = async () => {
|
||||
loading.value = true;
|
||||
@@ -358,27 +331,16 @@ const fetchUserStatus = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
fetchUserStatus();
|
||||
|
||||
const observer = new MutationObserver((mutations) => {
|
||||
mutations.forEach((mutation) => {
|
||||
if (mutation.attributeName === 'data-theme') {
|
||||
isDark.value = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
}
|
||||
});
|
||||
});
|
||||
observer.observe(document.documentElement, { attributes: true });
|
||||
});
|
||||
onMounted(fetchUserStatus);
|
||||
|
||||
const initSetup = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await apiClient.post('../auth/setup-2fa');
|
||||
const res = await authApiClient.post('/setup-2fa');
|
||||
setupData.value = res.data;
|
||||
step2.value = true;
|
||||
} catch (err) {
|
||||
Swal.fire('Error', 'Failed to initialize 2FA setup.', 'error');
|
||||
toast.show(err.response?.data?.error || 'Failed to initialize 2FA setup.', 'error');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
@@ -388,26 +350,14 @@ const verifyAndEnable = async () => {
|
||||
if (!otp.value || otp.value.length !== 6) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
await apiClient.post('../auth/enable-2fa', {
|
||||
await authApiClient.post('/enable-2fa', {
|
||||
secret: setupData.value.secret,
|
||||
otp: otp.value
|
||||
});
|
||||
isEnabled.value = true;
|
||||
confirmModal.value.open({
|
||||
title: 'Success!',
|
||||
message: 'Two-factor authentication has been enabled successfully. Your dashboard is now more secure.',
|
||||
confirmText: 'Great!',
|
||||
confirmBtnClass: 'btn-action-save',
|
||||
showCancel: false
|
||||
});
|
||||
toast.show('Two-factor authentication has been enabled. Your dashboard is now more secure.', 'success');
|
||||
} catch (err) {
|
||||
confirmModal.value.open({
|
||||
title: 'Verification Failed',
|
||||
message: err.response?.data?.error || 'The code you entered is invalid. Please check your authenticator app and try again.',
|
||||
confirmText: 'Try Again',
|
||||
confirmBtnClass: 'btn-action-danger',
|
||||
showCancel: false
|
||||
});
|
||||
toast.show(err.response?.data?.error || 'The code you entered is invalid. Please check your authenticator app and try again.', 'error');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
@@ -424,25 +374,13 @@ const disableConfirm = () => {
|
||||
|
||||
const handleDisable2FA = async () => {
|
||||
try {
|
||||
await apiClient.post('../auth/disable-2fa');
|
||||
await authApiClient.post('/disable-2fa');
|
||||
|
||||
isEnabled.value = false;
|
||||
step2.value = false;
|
||||
confirmModal.value.open({
|
||||
title: '2FA Disabled',
|
||||
message: 'Two-factor authentication has been disabled. Your account is now using standard password protection.',
|
||||
confirmText: 'OK',
|
||||
confirmBtnClass: 'btn-action-primary',
|
||||
showCancel: false
|
||||
});
|
||||
toast.show('Two-factor authentication has been disabled. Your account is now using standard password protection.', 'warning');
|
||||
} catch (err) {
|
||||
confirmModal.value.open({
|
||||
title: 'Error',
|
||||
message: err.response?.data?.error || 'Failed to disable two-factor authentication. Please try again.',
|
||||
confirmText: 'OK',
|
||||
confirmBtnClass: 'btn-action-danger',
|
||||
showCancel: false
|
||||
});
|
||||
toast.show(err.response?.data?.error || 'Failed to disable two-factor authentication. Please try again.', 'error');
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
+29
-146
@@ -151,16 +151,18 @@ import Chart from 'chart.js/auto';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import { useFormatters } from '../composables/useFormatters';
|
||||
import { useAppConfig } from '../composables/useAppConfig';
|
||||
import { useThemeObserver } from '../composables/useTheme';
|
||||
import { useTrafficChart, getThemeColors, COLOR_RX, COLOR_TX } from '../composables/useTrafficChart';
|
||||
|
||||
const { fetchAnalytics, fetchCertificates } = useApi();
|
||||
const { formatBytes, parseServerDate } = useFormatters();
|
||||
const { formatBytes } = useFormatters();
|
||||
const { config } = useAppConfig();
|
||||
|
||||
// Refs
|
||||
const mainChartRef = ref(null);
|
||||
const pieChartRef = ref(null);
|
||||
let mainChartInstance = null;
|
||||
let pieChartInstance = null;
|
||||
const mainChart = useTrafficChart(mainChartRef, { maxPoints: 96 });
|
||||
|
||||
// State
|
||||
const loading = reactive({ analytics: true, certs: true });
|
||||
@@ -179,17 +181,14 @@ const kpi = reactive({
|
||||
|
||||
const topClients = ref([]);
|
||||
const expiringCertsList = ref([]);
|
||||
let cachedHistory = null;
|
||||
|
||||
// Helpers
|
||||
const MAX_CHART_POINTS = 96;
|
||||
let cachedHistory = [];
|
||||
|
||||
const loadAnalytics = async () => {
|
||||
loading.analytics = true;
|
||||
try {
|
||||
const res = await fetchAnalytics(range.value);
|
||||
if (res.success) {
|
||||
proccessData(res.data);
|
||||
processData(res.data);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
@@ -201,17 +200,16 @@ const loadAnalytics = async () => {
|
||||
const loadCerts = async () => {
|
||||
loading.certs = true;
|
||||
try {
|
||||
const res = await fetchCertificates();
|
||||
if(res.success && Array.isArray(res.data)) {
|
||||
const list = res.data.filter(cert => {
|
||||
// fetchCertificates returns the plain array of profiles
|
||||
const profiles = await fetchCertificates();
|
||||
const list = profiles.filter(cert => {
|
||||
// Only active, non-revoked, and expiring soon (within 45 days)
|
||||
return !cert.is_revoked && !cert.is_expired &&
|
||||
cert.days_remaining !== null && cert.days_remaining <= 45;
|
||||
cert.days_remaining != null && cert.days_remaining <= 45;
|
||||
});
|
||||
|
||||
kpi.expiringCerts = list.length;
|
||||
expiringCertsList.value = list.sort((a,b) => (a.days_remaining || 0) - (b.days_remaining || 0));
|
||||
}
|
||||
expiringCertsList.value = list.sort((a, b) => a.days_remaining - b.days_remaining);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
} finally {
|
||||
@@ -219,7 +217,7 @@ const loadCerts = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const proccessData = (data) => {
|
||||
const processData = (data) => {
|
||||
kpi.concurrentUsers = data.max_concurrent_24h || 0;
|
||||
|
||||
// Traffic Distribution
|
||||
@@ -238,87 +236,21 @@ const proccessData = (data) => {
|
||||
percent: kpi.totalTraffic > 0 ? ((Number(c.total_traffic) / kpi.totalTraffic) * 100).toFixed(1) : 0
|
||||
}));
|
||||
|
||||
cachedHistory = data.global_history_24h || [];
|
||||
// Map the raw fields to the point format of useTrafficChart
|
||||
cachedHistory = (data.global_history_24h || []).map(p => ({
|
||||
timestamp: p.timestamp,
|
||||
bytes_received: p.total_rx,
|
||||
bytes_sent: p.total_tx,
|
||||
rx_rate_mbps: p.total_rx_rate,
|
||||
tx_rate_mbps: p.total_tx_rate
|
||||
}));
|
||||
|
||||
renderMainChart();
|
||||
renderPieChart();
|
||||
};
|
||||
|
||||
const renderMainChart = () => {
|
||||
if (!mainChartRef.value) return;
|
||||
if (mainChartInstance) mainChartInstance.destroy();
|
||||
|
||||
const downsampled = downsampleData(cachedHistory, MAX_CHART_POINTS);
|
||||
const labels = [];
|
||||
const dataRx = [];
|
||||
const dataTx = [];
|
||||
|
||||
downsampled.forEach(point => {
|
||||
const d = parseServerDate(point.timestamp);
|
||||
let label = '';
|
||||
if(range.value.includes('h') || range.value === '1d') {
|
||||
label = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
} else {
|
||||
label = d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' +
|
||||
d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
labels.push(label);
|
||||
|
||||
if (!isSpeedMode.value) {
|
||||
dataRx.push(point.bytes_received / (1024 * 1024)); // MB
|
||||
dataTx.push(point.bytes_sent / (1024 * 1024)); // MB
|
||||
} else {
|
||||
dataRx.push(point.rx_rate_mbps || 0);
|
||||
dataTx.push(point.tx_rate_mbps || 0);
|
||||
}
|
||||
});
|
||||
|
||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
const gridColor = isDark ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0,0,0,0.05)';
|
||||
const textColor = isDark ? '#8b949e' : '#6c757d';
|
||||
|
||||
const ctx = mainChartRef.value.getContext('2d');
|
||||
mainChartInstance = new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels,
|
||||
datasets: [
|
||||
|
||||
{
|
||||
label: !isSpeedMode.value ? 'Received (MB)' : 'RX Mbps',
|
||||
data: dataRx,
|
||||
borderColor: '#1652B8', // OpenVPN Blue
|
||||
backgroundColor: 'rgba(22, 82, 184, 0.15)',
|
||||
borderWidth: 2,
|
||||
fill: true,
|
||||
tension: 0.3,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 4
|
||||
},
|
||||
{
|
||||
label: !isSpeedMode.value ? 'Sent (MB)' : 'TX Mbps',
|
||||
data: dataTx,
|
||||
borderColor: '#EC7C31', // Brand Orange
|
||||
backgroundColor: 'rgba(236, 124, 49, 0.15)',
|
||||
borderWidth: 2,
|
||||
fill: true,
|
||||
tension: 0.3,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 4
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
plugins: { legend: { labels: { color: textColor } } },
|
||||
scales: {
|
||||
x: { ticks: { color: textColor, maxTicksLimit: 8 }, grid: { color: gridColor } },
|
||||
y: { beginAtZero: true, ticks: { color: textColor }, grid: { color: gridColor } }
|
||||
}
|
||||
}
|
||||
});
|
||||
mainChart.render(cachedHistory, { range: range.value, speedMode: isSpeedMode.value });
|
||||
};
|
||||
|
||||
const renderPieChart = () => {
|
||||
@@ -326,8 +258,7 @@ const renderPieChart = () => {
|
||||
if (pieChartInstance) pieChartInstance.destroy();
|
||||
|
||||
const ctx = pieChartRef.value.getContext('2d');
|
||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
const bgColor = isDark ? '#161b22' : '#ffffff';
|
||||
const bgColor = getThemeColors().isDark ? '#161b22' : '#ffffff';
|
||||
|
||||
pieChartInstance = new Chart(ctx, {
|
||||
type: 'doughnut',
|
||||
@@ -335,7 +266,7 @@ const renderPieChart = () => {
|
||||
labels: ['Received', 'Sent'],
|
||||
datasets: [{
|
||||
data: [kpi.totalReceived, kpi.totalSent],
|
||||
backgroundColor: ['#1652B8', '#EC7C31'],
|
||||
backgroundColor: [COLOR_RX, COLOR_TX],
|
||||
borderColor: bgColor,
|
||||
borderWidth: 2,
|
||||
hoverOffset: 4
|
||||
@@ -350,66 +281,19 @@ const renderPieChart = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const downsampleData = (data, maxPoints) => {
|
||||
if (!data || data.length === 0) return [];
|
||||
if (data.length <= maxPoints) {
|
||||
// Map raw fields to internal standardized names
|
||||
return data.map(p => ({
|
||||
timestamp: p.timestamp,
|
||||
bytes_received: p.total_rx,
|
||||
bytes_sent: p.total_tx,
|
||||
rx_rate_mbps: p.total_rx_rate,
|
||||
tx_rate_mbps: p.total_tx_rate
|
||||
}));
|
||||
}
|
||||
|
||||
const blockSize = Math.ceil(data.length / maxPoints);
|
||||
const result = [];
|
||||
|
||||
for (let i = 0; i < data.length; i += blockSize) {
|
||||
const chunk = data.slice(i, i + blockSize);
|
||||
if (chunk.length === 0) continue;
|
||||
|
||||
let sumRx = 0, sumTx = 0;
|
||||
let maxRxR = 0, maxTxR = 0;
|
||||
|
||||
chunk.forEach(pt => {
|
||||
sumRx += (pt.total_rx || 0);
|
||||
sumTx += (pt.total_tx || 0);
|
||||
maxRxR = Math.max(maxRxR, pt.total_rx_rate || 0);
|
||||
maxTxR = Math.max(maxTxR, pt.total_tx_rate || 0);
|
||||
});
|
||||
|
||||
result.push({
|
||||
timestamp: chunk[0].timestamp,
|
||||
bytes_received: sumRx,
|
||||
bytes_sent: sumTx,
|
||||
rx_rate_mbps: maxRxR,
|
||||
tx_rate_mbps: maxTxR
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// Lifecycle
|
||||
let intervalId;
|
||||
|
||||
// Redraw the charts when the theme is toggled
|
||||
useThemeObserver(() => {
|
||||
renderMainChart();
|
||||
renderPieChart();
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
loadAnalytics();
|
||||
loadCerts();
|
||||
|
||||
// Support Theme Toggle re-render like in Clients
|
||||
// We observe the attribute on html
|
||||
const observer = new MutationObserver((mutations) => {
|
||||
mutations.forEach((mutation) => {
|
||||
if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') {
|
||||
renderMainChart();
|
||||
renderPieChart();
|
||||
}
|
||||
});
|
||||
});
|
||||
observer.observe(document.documentElement, { attributes: true });
|
||||
|
||||
const refreshTime = config.value?.refresh_interval || 30000;
|
||||
intervalId = setInterval(() => {
|
||||
loadAnalytics();
|
||||
@@ -419,7 +303,6 @@ onMounted(() => {
|
||||
|
||||
onUnmounted(() => {
|
||||
if (intervalId) clearInterval(intervalId);
|
||||
if (mainChartInstance) mainChartInstance.destroy();
|
||||
if (pieChartInstance) pieChartInstance.destroy();
|
||||
});
|
||||
</script>
|
||||
@@ -40,7 +40,7 @@
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-for="d in destinations" :key="d.id">
|
||||
<td>
|
||||
<td class="align-top">
|
||||
<div class="fw-semibold" style="color: var(--text-heading);">{{ d.name }}</div>
|
||||
<div class="text-muted small">{{ destinationSummary(d) }}</div>
|
||||
<div v-if="typeInfo(d.type)?.pins_host_key" class="small mt-1">
|
||||
@@ -55,13 +55,13 @@
|
||||
<span class="status-badge status-warning"><i class="fas fa-triangle-exclamation me-1"></i>No TLS: clear text</span>
|
||||
</div>
|
||||
</td>
|
||||
<td><span class="status-badge status-client">{{ typeLabel(d.type) }}</span></td>
|
||||
<td>
|
||||
<td class="align-top"><span class="status-badge status-client">{{ typeLabel(d.type) }}</span></td>
|
||||
<td class="align-top">
|
||||
<span :class="['status-badge', d.enabled ? 'status-valid' : 'status-secondary']">
|
||||
{{ d.enabled ? 'Enabled' : 'Disabled' }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<td class="align-top">
|
||||
<span v-if="d.last_status" :class="['status-badge', d.last_status === 'ok' ? 'status-valid' : 'status-expired']"
|
||||
:title="d.last_message">
|
||||
{{ d.last_status === 'ok' ? 'OK' : 'Failed' }}
|
||||
@@ -69,7 +69,7 @@
|
||||
<span v-else class="text-muted small">never used</span>
|
||||
<div v-if="d.last_at" class="text-muted small">{{ formatTime(d.last_at) }}</div>
|
||||
</td>
|
||||
<td>
|
||||
<td class="align-top">
|
||||
<button class="btn btn-sm btn-link text-primary p-0 me-2" title="Test connection"
|
||||
@click="testDestination(d)" :disabled="testingId === d.id">
|
||||
<i v-if="testingId === d.id" class="fas fa-spinner fa-spin"></i>
|
||||
|
||||
@@ -89,7 +89,7 @@
|
||||
<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'" style="cursor: pointer;" @click="showDetails(cert)">
|
||||
<tr v-for="cert in activeCerts" :key="cert.id + '_active'" style="cursor: pointer;" tabindex="0" @click="showDetails(cert)" @keydown.enter.self="showDetails(cert)">
|
||||
<td v-note-tooltip="cert.note">
|
||||
<div class="fw-semibold" style="color: var(--text-heading);">
|
||||
{{ cert.username }}
|
||||
@@ -102,7 +102,7 @@
|
||||
<td class="fw-semibold" :class="getDaysClass(cert.days_remaining)">
|
||||
{{ cert.days_remaining }}
|
||||
</td>
|
||||
<td v-html="getStatusBadgeHTML(cert)"></td>
|
||||
<td><StatusBadge :profile="cert" /></td>
|
||||
<td>
|
||||
<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>
|
||||
@@ -118,7 +118,7 @@
|
||||
<tr class="section-divider">
|
||||
<td colspan="6">Expired / Revoked ({{ expiredCerts.length }})</td>
|
||||
</tr>
|
||||
<tr v-for="cert in expiredCerts" :key="cert.id + '_expired'" style="cursor: pointer;" @click="showDetails(cert)">
|
||||
<tr v-for="cert in expiredCerts" :key="cert.id + '_expired'" style="cursor: pointer;" tabindex="0" @click="showDetails(cert)" @keydown.enter.self="showDetails(cert)">
|
||||
<td v-note-tooltip="cert.note">
|
||||
<div class="fw-semibold" style="color: var(--text-heading);">
|
||||
{{ cert.username }}
|
||||
@@ -131,7 +131,7 @@
|
||||
<td class="fw-semibold text-muted">
|
||||
{{ cert.days_remaining }}
|
||||
</td>
|
||||
<td v-html="getStatusBadgeHTML(cert)"></td>
|
||||
<td><StatusBadge :profile="cert" /></td>
|
||||
<td>
|
||||
<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>
|
||||
@@ -156,6 +156,7 @@ import { useApi } from '../composables/useApi';
|
||||
import NewClientModal from '../components/NewClientModal.vue';
|
||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||
import ProfileDetailsModal from '../components/ProfileDetailsModal.vue';
|
||||
import StatusBadge from '../components/StatusBadge.vue';
|
||||
import vNoteTooltip from '../directives/noteTooltip';
|
||||
import { useToast } from '../composables/useToast';
|
||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||
@@ -190,23 +191,6 @@ const getDaysClass = (days) => {
|
||||
return 'text-success';
|
||||
};
|
||||
|
||||
const getStatusBadgeHTML = (cert) => {
|
||||
if (cert.is_revoked) {
|
||||
return '<span class="status-badge status-expired"><i class="fas fa-ban me-1"></i>Revoked</span>';
|
||||
}
|
||||
if (cert.is_expired) {
|
||||
return '<span class="status-badge status-expired"><i class="fas fa-times-circle me-1"></i>Expired</span>';
|
||||
}
|
||||
|
||||
// Days check logic for expiring soon warning
|
||||
if (cert.days_remaining !== null && cert.days_remaining <= 30) {
|
||||
return '<span class="status-badge status-warning"><i class="fas fa-exclamation-triangle me-1"></i>Expiring Soon</span>';
|
||||
}
|
||||
|
||||
return '<span class="status-badge status-valid"><i class="fas fa-check-circle me-1"></i>Active</span>';
|
||||
};
|
||||
|
||||
|
||||
// Data Processing
|
||||
const filteredData = computed(() => {
|
||||
let data = allProfiles.value;
|
||||
@@ -234,8 +218,8 @@ const categorized = computed(() => {
|
||||
});
|
||||
|
||||
// Sort logic
|
||||
active.sort((a,b) => (a.days_remaining || 9999) - (b.days_remaining || 9999));
|
||||
expired.sort((a,b) => (b.days_remaining || -9999) - (a.days_remaining || -9999));
|
||||
active.sort((a,b) => (a.days_remaining ?? 9999) - (b.days_remaining ?? 9999));
|
||||
expired.sort((a,b) => (b.days_remaining ?? -9999) - (a.days_remaining ?? -9999));
|
||||
|
||||
return { active, expired };
|
||||
});
|
||||
@@ -312,6 +296,8 @@ const downloadConfig = async (cert) => {
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
// Release the blob after the browser has started the download
|
||||
setTimeout(() => window.URL.revokeObjectURL(url), 1000);
|
||||
} catch(e) {
|
||||
showToast('Could not download config: ' + (e.response?.data?.detail || e.message), 'error');
|
||||
}
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
<div class="stat-value">{{ stats.activeClients }}</div>
|
||||
<div class="stat-label">Active Clients</div>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<div class="stat-value">{{ stats.totalSessions }}</div>
|
||||
<div class="stat-label">Active Sessions</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-3">
|
||||
@@ -52,10 +56,10 @@
|
||||
<th>Client Name</th>
|
||||
<th>Real Address</th>
|
||||
<th>Status</th>
|
||||
<th @click="currentSort = 'received'" class="cursor-pointer" :class="{'active-sort': currentSort === 'received'}">
|
||||
<th @click="currentSort = 'received'" @keydown.enter="currentSort = 'received'" tabindex="0" class="cursor-pointer" :class="{'active-sort': currentSort === 'received'}">
|
||||
Received <i v-if="currentSort === 'received'" class="fas fa-sort-down ms-1"></i>
|
||||
</th>
|
||||
<th @click="currentSort = 'sent'" class="cursor-pointer" :class="{'active-sort': currentSort === 'sent'}">
|
||||
<th @click="currentSort = 'sent'" @keydown.enter="currentSort = 'sent'" tabindex="0" class="cursor-pointer" :class="{'active-sort': currentSort === 'sent'}">
|
||||
Sent <i v-if="currentSort === 'sent'" class="fas fa-sort-down ms-1"></i>
|
||||
</th>
|
||||
<th>Down Speed</th>
|
||||
@@ -78,17 +82,24 @@
|
||||
{{ group.status }} Clients
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-for="c in group.items" :key="c.common_name">
|
||||
<template v-for="c in group.items" :key="c.common_name">
|
||||
<tr>
|
||||
<td>
|
||||
<a @click="openHistory(c.common_name)" class="client-link">
|
||||
<a href="#" @click.prevent="openHistory(c.common_name)" class="client-link">
|
||||
{{ c.common_name }} <i class="fas fa-chart-area ms-1 small opacity-50"></i>
|
||||
</a>
|
||||
</td>
|
||||
<td class="small text-muted">{{ c.real_address || '-' }}</td>
|
||||
<td class="small text-muted">{{ c.sessions_count > 1 ? `${c.sessions_count} devices` : (c.real_address || '-') }}</td>
|
||||
<td>
|
||||
<span class="status-badge" :class="c.status === 'Active' ? 'status-active' : 'status-disconnected'">
|
||||
{{ c.status }}
|
||||
</span>
|
||||
<button v-if="sessionsBadge(c)" type="button" class="btn btn-sm btn-outline-secondary ms-2 py-0 px-1"
|
||||
:aria-expanded="expanded.includes(c.common_name)" :title="'Show sessions'"
|
||||
@click="expanded = toggleExpanded(expanded, c.common_name)">
|
||||
{{ sessionsBadge(c) }}
|
||||
<i class="fas ms-1 small" :class="expanded.includes(c.common_name) ? 'fa-chevron-up' : 'fa-chevron-down'"></i>
|
||||
</button>
|
||||
</td>
|
||||
<td class="font-monospace small">{{ formatBytes(c.total_bytes_received) }}</td>
|
||||
<td class="font-monospace small">{{ formatBytes(c.total_bytes_sent) }}</td>
|
||||
@@ -109,6 +120,15 @@
|
||||
|
||||
<td class="small text-muted">{{ formatDate(c.last_activity) }}</td>
|
||||
</tr>
|
||||
<tr v-for="(sess, i) in visibleSessions(c, expanded)" :key="`${c.common_name}-s${i}`" class="session-row">
|
||||
<td class="small text-muted ps-4"><i class="fas fa-level-up-alt fa-rotate-90 me-2 opacity-50"></i>Session {{ i + 1 }}</td>
|
||||
<td class="small text-muted">{{ sess.real_address || '-' }}</td>
|
||||
<td class="small text-muted" colspan="2">Since {{ formatDate(sess.connected_since) }}</td>
|
||||
<td class="font-monospace small">Down {{ sess.received_mb }} MB</td>
|
||||
<td class="font-monospace small">Up {{ sess.sent_mb }} MB</td>
|
||||
<td colspan="2"></td>
|
||||
</tr>
|
||||
</template>
|
||||
</template>
|
||||
</template>
|
||||
</tbody>
|
||||
@@ -125,8 +145,9 @@ import { useApi } from '../composables/useApi';
|
||||
import { useFormatters } from '../composables/useFormatters';
|
||||
import HistoryModal from '../components/HistoryModal.vue';
|
||||
import { useAppConfig } from '../composables/useAppConfig';
|
||||
import { sessionsBadge, toggleExpanded, visibleSessions } from '../utils/sessions';
|
||||
|
||||
const { fetchStats, apiClient } = useApi();
|
||||
const { fetchStats } = useApi();
|
||||
const { formatBytes, formatRate, parseServerDate } = useFormatters();
|
||||
const { config } = useAppConfig();
|
||||
|
||||
@@ -137,6 +158,7 @@ const searchQuery = ref('');
|
||||
const hideDisconnected = ref(false);
|
||||
const currentSort = ref('sent');
|
||||
const historyModal = ref(null);
|
||||
const expanded = ref([]); // CNs with an open session list; survives auto-refresh
|
||||
|
||||
let intervalId = null;
|
||||
|
||||
@@ -144,14 +166,16 @@ const stats = computed(() => {
|
||||
let totalReceived = 0;
|
||||
let totalSent = 0;
|
||||
let activeClients = 0;
|
||||
let totalSessions = 0;
|
||||
|
||||
clients.value.forEach(c => {
|
||||
totalReceived += c.total_bytes_received || 0;
|
||||
totalSent += c.total_bytes_sent || 0;
|
||||
if (c.status === 'Active') activeClients++;
|
||||
totalSessions += c.sessions_count || 0;
|
||||
});
|
||||
|
||||
return { totalReceived, totalSent, activeClients };
|
||||
return { totalReceived, totalSent, activeClients, totalSessions };
|
||||
});
|
||||
|
||||
const filteredClients = computed(() => {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<div class="brand-logo">
|
||||
<i class="fas fa-shield-alt"></i>
|
||||
</div>
|
||||
<h1>OpenVPN Monitor</h1>
|
||||
<h1>OpenVPN Controller</h1>
|
||||
<p class="text-muted">Secure Access Control</p>
|
||||
</div>
|
||||
|
||||
@@ -13,28 +13,32 @@
|
||||
<!-- Standard Login -->
|
||||
<form v-if="!requires2FA" @submit.prevent="handleLogin">
|
||||
<div class="mb-4">
|
||||
<label class="form-label">Username</label>
|
||||
<label class="form-label" for="loginUsername">Username</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
||||
<input
|
||||
id="loginUsername"
|
||||
type="text"
|
||||
class="form-control"
|
||||
v-model="form.username"
|
||||
placeholder="Enter username"
|
||||
autocomplete="username"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label class="form-label">Password</label>
|
||||
<label class="form-label" for="loginPassword">Password</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-lock"></i></span>
|
||||
<input
|
||||
id="loginPassword"
|
||||
type="password"
|
||||
class="form-control"
|
||||
v-model="form.password"
|
||||
placeholder="Enter password"
|
||||
autocomplete="current-password"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
@@ -65,6 +69,9 @@
|
||||
v-model="otp"
|
||||
placeholder="000 000"
|
||||
maxlength="6"
|
||||
inputmode="numeric"
|
||||
autocomplete="one-time-code"
|
||||
aria-label="6-digit authentication code"
|
||||
required
|
||||
autofocus
|
||||
>
|
||||
@@ -86,7 +93,7 @@
|
||||
</div>
|
||||
|
||||
<div class="login-footer text-center mt-4">
|
||||
<p class="small text-muted">© 2026 Admin Dashboard</p>
|
||||
<p class="small text-muted">© 2026 OpenVPN Controller</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -98,7 +105,7 @@ import { useRouter } from 'vue-router';
|
||||
import { useApi } from '../composables/useApi';
|
||||
|
||||
const router = useRouter();
|
||||
const { apiClient } = useApi();
|
||||
const { authApiClient } = useApi();
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const requires2FA = ref(false);
|
||||
@@ -114,9 +121,7 @@ const handleLogin = async () => {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
// Auth routes are under /api/auth, while apiClient defaults to /api/v1
|
||||
// We use a relative path with '..' to go up to /api
|
||||
const response = await apiClient.post('../auth/login', form);
|
||||
const response = await authApiClient.post('/login', form);
|
||||
if (response.data.requires_2fa) {
|
||||
requires2FA.value = true;
|
||||
tempToken.value = response.data.temp_token;
|
||||
@@ -137,7 +142,7 @@ const handleVerify2FA = async () => {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const response = await apiClient.post('../auth/verify-2fa', {
|
||||
const response = await authApiClient.post('/verify-2fa', {
|
||||
temp_token: tempToken.value,
|
||||
otp: otp.value
|
||||
});
|
||||
|
||||
@@ -1,251 +0,0 @@
|
||||
<template>
|
||||
<div class="login-page">
|
||||
<div class="login-card">
|
||||
<div class="login-header">
|
||||
<div class="brand-logo">
|
||||
<i class="fas fa-shield-alt"></i>
|
||||
</div>
|
||||
<h1>OpenVPN Monitor</h1>
|
||||
<p class="text-muted">Secure Access Control</p>
|
||||
</div>
|
||||
|
||||
<div class="login-body">
|
||||
<!-- Standard Login -->
|
||||
<form v-if="!requires2FA" @submit.prevent="handleLogin">
|
||||
<div class="mb-4">
|
||||
<label class="form-label">Username</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
||||
<input
|
||||
type="text"
|
||||
class="form-control"
|
||||
v-model="form.username"
|
||||
placeholder="Enter username"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label class="form-label">Password</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-lock"></i></span>
|
||||
<input
|
||||
type="password"
|
||||
class="form-control"
|
||||
v-model="form.password"
|
||||
placeholder="Enter password"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="error" class="alert alert-danger fade show mb-4">
|
||||
<i class="fas fa-exclamation-circle me-2"></i>{{ error }}
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary w-100 py-2 fw-bold" :disabled="loading">
|
||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
||||
Sign In
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- 2FA Verification -->
|
||||
<form v-else @submit.prevent="handleVerify2FA">
|
||||
<div class="text-center mb-4">
|
||||
<i class="fas fa-key fa-3x text-warning mb-3"></i>
|
||||
<h3>Two-Factor Authentication</h3>
|
||||
<p class="text-muted">Enter the 6-digit code from your authenticator app.</p>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<input
|
||||
type="text"
|
||||
class="form-control form-control-lg text-center fw-bold"
|
||||
v-model="otp"
|
||||
placeholder="000 000"
|
||||
maxlength="6"
|
||||
required
|
||||
autofocus
|
||||
>
|
||||
</div>
|
||||
|
||||
<div v-if="error" class="alert alert-danger fade show mb-4">
|
||||
<i class="fas fa-exclamation-circle me-2"></i>{{ error }}
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-warning w-100 py-2 fw-bold" :disabled="loading">
|
||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
||||
Verify & Continue
|
||||
</button>
|
||||
|
||||
<button type="button" class="btn btn-link w-100 mt-2 text-muted" @click="resetLogin">
|
||||
Back to login
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="login-footer text-center mt-4">
|
||||
<p class="small text-muted">© 2026 Admin Dashboard</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { reactive, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useApi } from '../composables/useApi';
|
||||
|
||||
const router = useRouter();
|
||||
const { apiClient } = useApi();
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const requires2FA = ref(false);
|
||||
const tempToken = ref('');
|
||||
const otp = ref('');
|
||||
|
||||
const form = reactive({
|
||||
username: '',
|
||||
password: ''
|
||||
});
|
||||
|
||||
const handleLogin = async () => {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
// Auth routes are under /api/auth, while apiClient defaults to /api/v1
|
||||
// We use a relative path with '..' to go up to /api
|
||||
const response = await apiClient.post('../auth/login', form);
|
||||
if (response.data.requires_2fa) {
|
||||
requires2FA.value = true;
|
||||
tempToken.value = response.data.temp_token;
|
||||
} else {
|
||||
localStorage.setItem('ovpmon_token', response.data.token);
|
||||
localStorage.setItem('ovpmon_user', response.data.username);
|
||||
router.push('/');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Login Error:', err);
|
||||
error.value = err.response?.data?.error || 'Login failed. Please check your connection.';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleVerify2FA = async () => {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const response = await apiClient.post('../auth/verify-2fa', {
|
||||
temp_token: tempToken.value,
|
||||
otp: otp.value
|
||||
});
|
||||
localStorage.setItem('ovpmon_token', response.data.token);
|
||||
localStorage.setItem('ovpmon_user', response.data.username);
|
||||
router.push('/');
|
||||
} catch (err) {
|
||||
error.value = err.response?.data?.error || 'Verification failed.';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const resetLogin = () => {
|
||||
requires2FA.value = false;
|
||||
tempToken.value = '';
|
||||
otp.value = '';
|
||||
error.value = '';
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.login-page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background-color: var(--bg-body);
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.login-card {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
background: var(--bg-card);
|
||||
padding: 40px;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.login-header {
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.brand-logo {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
background: var(--accent-color);
|
||||
color: white;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 24px;
|
||||
border-radius: 12px;
|
||||
margin: 0 auto 15px;
|
||||
}
|
||||
|
||||
.login-header h1 {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
margin: 0;
|
||||
color: var(--text-heading);
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-heading);
|
||||
}
|
||||
|
||||
.input-group-text {
|
||||
background: var(--bg-element);
|
||||
border-color: var(--border-color);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.form-control {
|
||||
background: var(--bg-input);
|
||||
border-color: var(--border-color);
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
.form-control:focus {
|
||||
border-color: var(--accent-color);
|
||||
box-shadow: 0 0 0 3px rgba(9, 105, 218, 0.1);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: #1652B8;
|
||||
border-color: #1652B8;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-color: #1449a5;
|
||||
border-color: #1449a5;
|
||||
}
|
||||
|
||||
.btn-warning {
|
||||
background-color: #EC7C31;
|
||||
border-color: #EC7C31;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-warning:hover {
|
||||
background-color: #d66d2a;
|
||||
border-color: #d66d2a;
|
||||
color: white;
|
||||
}
|
||||
</style>
|
||||
@@ -165,6 +165,8 @@
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref="initModal" @confirm="runInit" />
|
||||
<ConfirmModal ref="clearModal" @confirm="runClear" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -174,6 +176,7 @@ import { ref, computed, onMounted, onUnmounted, reactive } from 'vue';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import { useToast } from '../composables/useToast';
|
||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||
|
||||
const { profilesApiClient } = useApi();
|
||||
const toast = useToast();
|
||||
@@ -198,6 +201,8 @@ const form = reactive({
|
||||
easyrsa_batch: true
|
||||
});
|
||||
|
||||
const initModal = ref(null);
|
||||
const clearModal = ref(null);
|
||||
const isLoading = ref(false);
|
||||
const action = ref(''); // 'save', 'init', 'clear'
|
||||
|
||||
@@ -232,7 +237,7 @@ const loadConfig = async () => {
|
||||
|
||||
// Populate form
|
||||
Object.keys(data).forEach(key => {
|
||||
if (form.hasOwnProperty(key)) {
|
||||
if (Object.hasOwn(form, key)) {
|
||||
form[key] = data[key];
|
||||
}
|
||||
});
|
||||
@@ -290,9 +295,16 @@ const handleSave = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleInit = async () => {
|
||||
if (!confirm('Are you sure you want to Initialize system? This will start the PKI initialization process.')) return;
|
||||
const handleInit = () => {
|
||||
initModal.value.open({
|
||||
title: 'Initialize PKI?',
|
||||
message: 'Are you sure you want to initialize the system? This will start the PKI initialization process.',
|
||||
confirmText: 'Yes, initialize',
|
||||
confirmBtnClass: 'btn-action-primary'
|
||||
});
|
||||
};
|
||||
|
||||
const runInit = async () => {
|
||||
isLoading.value = true;
|
||||
action.value = 'init'; // locks the button until the server confirms the job state
|
||||
try {
|
||||
@@ -312,9 +324,16 @@ const handleInit = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleClear = async () => {
|
||||
if (!confirm('Are you sure you want to CLEAR PKI? This will delete all certificates and cannot be undone.')) return;
|
||||
const handleClear = () => {
|
||||
clearModal.value.open({
|
||||
title: 'Clear PKI?',
|
||||
message: 'Are you sure you want to CLEAR the PKI? This will delete all certificates and cannot be undone.',
|
||||
confirmText: 'Yes, clear',
|
||||
confirmBtnClass: 'btn-action-danger'
|
||||
});
|
||||
};
|
||||
|
||||
const runClear = async () => {
|
||||
isLoading.value = true;
|
||||
action.value = 'clear';
|
||||
try {
|
||||
|
||||
@@ -84,6 +84,8 @@
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref="confirmModal" @confirm="runControl" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -92,6 +94,7 @@ import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import { useToast } from '../composables/useToast';
|
||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||
|
||||
const { profilesApiClient } = useApi();
|
||||
const toast = useToast();
|
||||
@@ -114,6 +117,7 @@ const stats = reactive({
|
||||
uptime: null
|
||||
});
|
||||
|
||||
const confirmModal = ref(null);
|
||||
const isLoading = ref(false);
|
||||
const action = ref(''); // 'start', 'stop', 'restart'
|
||||
let pollInterval = null;
|
||||
@@ -131,9 +135,19 @@ const fetchStats = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleControl = async (cmd) => {
|
||||
if (!confirm(`Are you sure you want to ${cmd.toUpperCase()} the OpenVPN service?`)) return;
|
||||
const CONFIRM_CLASSES = { start: 'btn-action-primary', restart: 'btn-action-save', stop: 'btn-action-danger' };
|
||||
|
||||
const handleControl = (cmd) => {
|
||||
confirmModal.value.open({
|
||||
title: `${cmd.charAt(0).toUpperCase()}${cmd.slice(1)} the service?`,
|
||||
message: `Are you sure you want to ${cmd.toUpperCase()} the OpenVPN service?`,
|
||||
confirmText: `Yes, ${cmd}`,
|
||||
confirmBtnClass: CONFIRM_CLASSES[cmd],
|
||||
data: cmd
|
||||
});
|
||||
};
|
||||
|
||||
const runControl = async (cmd) => {
|
||||
isLoading.value = true;
|
||||
action.value = cmd;
|
||||
|
||||
|
||||
@@ -264,6 +264,7 @@ import { ref, onMounted, reactive, watch } from 'vue';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import { useToast } from '../composables/useToast';
|
||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||
import { maskToCidr, parseCidr } from '../utils/cidr';
|
||||
|
||||
const { profilesApiClient } = useApi();
|
||||
const toast = useToast();
|
||||
@@ -302,15 +303,8 @@ watch(isSplitTunnel, (val) => {
|
||||
form.tunnel_type = val ? 'SPLIT' : 'FULL';
|
||||
});
|
||||
|
||||
// Helpers
|
||||
function maskToCidr(mask) {
|
||||
if (!mask) return '';
|
||||
const parts = mask.split('.');
|
||||
let bits = 0;
|
||||
const map = {255:8, 254:7, 252:6, 248:5, 240:4, 224:3, 192:2, 128:1, 0:0};
|
||||
for(let p of parts) bits += map[parseInt(p)] || 0;
|
||||
return bits;
|
||||
}
|
||||
// Netmask received from the server: used when the subnet is typed without a /nn suffix
|
||||
let currentNetmask = '';
|
||||
|
||||
// Methods
|
||||
const showMessage = (text, type = 'success') => toast.show(text, type);
|
||||
@@ -329,7 +323,7 @@ const loadConfig = async () => {
|
||||
const data = payload.server ? payload.server : payload;
|
||||
|
||||
Object.keys(data).forEach(key => {
|
||||
if (form.hasOwnProperty(key)) {
|
||||
if (Object.hasOwn(form, key)) {
|
||||
if (key === 'tunnel_type') {
|
||||
isSplitTunnel.value = data[key] === 'SPLIT';
|
||||
}
|
||||
@@ -337,9 +331,10 @@ const loadConfig = async () => {
|
||||
}
|
||||
});
|
||||
|
||||
currentNetmask = data.vpn_netmask || '';
|
||||
if (data.vpn_network && data.vpn_netmask) {
|
||||
const cidrSuffix = maskToCidr(data.vpn_netmask);
|
||||
if (cidrSuffix) {
|
||||
if (cidrSuffix !== null) {
|
||||
form.vpn_network = `${data.vpn_network}/${cidrSuffix}`;
|
||||
}
|
||||
}
|
||||
@@ -351,20 +346,25 @@ const loadConfig = async () => {
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
// The API takes the address and the netmask separately: without vpn_netmask it resets the mask to 255.255.255.0
|
||||
const subnet = parseCidr(form.vpn_network);
|
||||
if (!subnet) {
|
||||
showMessage('VPN subnet must be an IPv4 network in CIDR format, e.g. 172.20.1.0/24', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
isLoading.value = true;
|
||||
action.value = 'save';
|
||||
|
||||
const payload = { ...form };
|
||||
payload.split_routes = payload.split_routes.filter(r => r && r.trim() !== '');
|
||||
payload.dns_servers = payload.dns_servers.filter(d => d && d.trim() !== '');
|
||||
|
||||
if (payload.vpn_network.includes('/')) {
|
||||
const [ip, suffix] = payload.vpn_network.split('/');
|
||||
payload.vpn_network = ip;
|
||||
}
|
||||
payload.vpn_network = subnet.network;
|
||||
payload.vpn_netmask = subnet.netmask || currentNetmask || '255.255.255.0';
|
||||
|
||||
try {
|
||||
await profilesApiClient.put('/config/server', payload);
|
||||
currentNetmask = payload.vpn_netmask;
|
||||
showMessage('Server configuration saved!', 'success');
|
||||
} catch (err) {
|
||||
showMessage(`Error saving: ${err.response?.data?.detail || err.message}`, 'error');
|
||||
|
||||
@@ -9,7 +9,7 @@ export default defineConfig({
|
||||
output: {
|
||||
manualChunks: {
|
||||
'vendor-charts': ['chart.js'],
|
||||
'vendor-ui': ['bootstrap', 'sweetalert2']
|
||||
'vendor-ui': ['bootstrap']
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# Скорость на графиках за период больше суток (сводка, 2026-10-07)
|
||||
|
||||
План: [2026-10-07_Aggregated_Speed_PLAN.md](2026-10-07_Aggregated_Speed_PLAN.md). Схема БД, миграции и гатерер не менялись.
|
||||
|
||||
## 1. Что изменено
|
||||
|
||||
- `APP_CORE/openvpn_api_v3.py`: словарь `BUCKET_SECONDS` (таблица -> секунды корзины) и функция `avg_rate_sql()`. Таблица берётся только из словаря, остальные аргументы это фиксированные выражения колонок, пользовательский ввод в SQL не попадает.
|
||||
- `get_client_history` (ветка `is_aggregated`): `bytes_*_rate_mbps` = `bytes * 8 / 1e6 / секунды` вместо `0`.
|
||||
- `get_analytics_data` (`7d`, `30d`; выбор таблицы не менялся, обе ветки используют `stats_hourly`): `total_rx_rate` / `total_tx_rate` считаются по сумме клиентов на одной отметке времени, дальше работают прежние `MAX` по интервалу группировки и zero-fill.
|
||||
- Текущая неполная корзина: длительность `min(длина корзины, время с начала корзины)`, не менее 1 с (UTC, как в агрегатах).
|
||||
- Fallback на `usage_history` (агрегатной таблицы нет) не затронут: отдаёт реальные скорости.
|
||||
- `APP_UI/src/composables/useTrafficChart.js` (общий код графиков, правка действует для `HistoryModal.vue` и `Analytics.vue`): для диапазонов больше 24 часов (`7d`, `30d`) в режиме Speed серии называются «RX Mbps (avg)» / «TX Mbps (avg)»; для `1h`, `3h`, `24h` подписи прежние.
|
||||
- `deploy/ui-dist` пересобран (`build-ui.sh --docker --publish`).
|
||||
- Тест `APP_CORE/test_aggregated_speed.py`: временная БД с миграциями, клиент и две записи `stats_hourly` (450 MB rx / 90 MB tx); полная корзина даёт 1.0 / 0.2 Mbps, корзина, начавшаяся 30 минут назад, 2.0 / 0.4 Mbps; `get_analytics_data('7d')` даёт ненулевую скорость.
|
||||
- Документация: `DOCS/Core_Monitoring/API_Reference.md`, `DOCS/Core_Monitoring/Data_Architecture.md`. Корневой `README.md` режим Speed не описывает, не менялся.
|
||||
|
||||
## 2. Результаты проверок
|
||||
|
||||
- `APP_CORE`, весь набор (venv проекта): 18 passed.
|
||||
- UI в `node:20-alpine` на копии вне репозитория: `npm ci`, `lint` без замечаний, `test` 13 passed, `build` успешно. `check-ui.sh`: fresh.
|
||||
- Стенд `ovpmon-test`: пересозданы только `app-api` и `app-ui` (`--no-deps`), `ovp-api` и `ovp-ui` healthy; `ovp-gatherer` и `ovp-profiler` не перезапускались (то же время старта и id). Ключ подписи JWT передан из окружения работающего контейнера (совпадение с профайлером проверено по хешу, значение нигде не выводилось). `GET http://127.0.0.1:8089/` даёт 200, `/api/v1/stats` без токена 401.
|
||||
- `get_client_history` напрямую в контейнере `ovp-api` (БД открыта только на чтение), клиент `msalice`, 7 дней, `resolution=hourly`: 8 точек, все с ненулевой скоростью, например корзина 10:00 UTC: 4 820 448 байт rx / 4 819 188 байт tx = 0.0107 / 0.0107 Mbps; текущая корзина 11:00: 0.0107 Mbps (при простой нормировке на 3600 с была бы занижена). `get_analytics_data('7d')` и `('30d')`: 96 точек, максимум `total_rx_rate` 0.0203 Mbps.
|
||||
|
||||
## 3. Не проверено
|
||||
|
||||
- Визуальная проверка графиков в браузере (выполняет владелец).
|
||||
- Работа через HTTP с токеном (учётные записи не создавались и не подбирались): проверен вызов метода напрямую.
|
||||
- Отдельный тест на `resolution` `5min`, `15min`, `6h`, `daily` не писался (минимум тестов); формула общая, значения берутся из словаря.
|
||||
|
||||
## 4. Ограничения
|
||||
|
||||
- Средняя скорость сглаживает кратковременные пики; на периодах больше суток это отражено подписью «avg». В Analytics для `7d` и `30d` на точку берётся максимум часовых средних.
|
||||
- Пиковые значения на больших периодах потребуют варианта 2 (колонки максимумов в агрегатах, миграция): вне этого изменения.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Скорость на графиках за период больше суток (план, 2026-10-07)
|
||||
|
||||
Основание: на графиках клиента (модальное окно) и в Analytics режим Speed (Mbps) пуст для периодов 7d и 30d, на периодах до 24 часов скорость есть.
|
||||
|
||||
## 1. Причина
|
||||
|
||||
Для периодов больше 24 часов API читает агрегатные таблицы `stats_5min`, `stats_15min`, `stats_hourly`, `stats_6h`, `stats_daily`. В них только `bytes_received` и `bytes_sent` (`migrations.py`, раздел 3), колонок скорости нет. Запросы подставляют константу:
|
||||
|
||||
- `get_client_history` (`APP_CORE/openvpn_api_v3.py`, ветка `is_aggregated`): `0 as bytes_received_rate_mbps`, `0 as bytes_sent_rate_mbps`.
|
||||
- `get_analytics_data` (там же, для `7d` и `30d`): `0 as total_rx_rate, 0 as total_tx_rate`.
|
||||
|
||||
## 2. Решение (вариант 1: средняя скорость из байтов)
|
||||
|
||||
Средняя скорость корзины = `bytes * 8 / 1 000 000 / секунды_корзины`, та же формула, что у гатерера (`calculate_rates`). Схема БД, гатерер и данные не меняются, история работает задним числом.
|
||||
|
||||
| Таблица | Секунд в корзине |
|
||||
|---|---|
|
||||
| `stats_5min` | 300 |
|
||||
| `stats_15min` | 900 |
|
||||
| `stats_hourly` | 3600 |
|
||||
| `stats_6h` | 21600 |
|
||||
| `stats_daily` | 86400 |
|
||||
|
||||
Незавершённая (текущая) корзина: длительность берётся как `min(длина корзины, время с начала корзины)`, минимум 1 секунда, иначе скорость была бы занижена.
|
||||
|
||||
## 3. Шаги
|
||||
|
||||
1. `get_client_history`: словарь `{таблица: секунды}`; в ветке `is_aggregated` вместо нулей выражение средней скорости (в SQL, значения для обоих направлений).
|
||||
2. `get_analytics_data`: то же для `stats_hourly` (суммирование по клиентам на одной отметке времени остаётся, затем `MAX` по интервалу группировки уже работает как для сырых данных).
|
||||
3. UI: в режиме Speed для периодов больше 24 часов подписи серий «RX Mbps (avg)» и «TX Mbps (avg)» (`HistoryModal.vue`, `Analytics.vue`; логика подписи в общем коде графиков, если он есть). Остальное в UI не меняется.
|
||||
4. Тест (минимальный, `APP_CORE`, pytest): запись в `stats_hourly` с известным объёмом, `get_client_history` с `resolution='hourly'` возвращает ожидаемый `bytes_*_rate_mbps` (полная корзина и текущая неполная).
|
||||
5. Проверка на стенде `ovpmon-test`: перезапуск только `ovp-api` (образ пересобирается), запрос `/api/v1/stats/<client>?range=7d` и `/api/v1/analytics?range=7d` возвращает ненулевую скорость при ненулевом трафике; визуальная проверка графиков выполняется владельцем. Пересборка `deploy/ui-dist` (`build-ui.sh --publish`), пересоздание `ovp-ui`.
|
||||
6. Сводка `2026-10-07_Aggregated_Speed.md`, строка в `DOCS/Changes/README.md`, обновление описания метрик и API в `DOCS/Core_Monitoring` и `README.md`, где описан режим Speed.
|
||||
|
||||
## 4. Тесты
|
||||
|
||||
Один тест из шага 4. Остальное: проверка запросом на стенде.
|
||||
|
||||
## 5. Риски
|
||||
|
||||
- Средняя скорость сглаживает кратковременные пики; на периодах больше суток это ожидаемо и обозначено подписью «avg».
|
||||
- Для пиковых значений на больших периодах потребуется вариант 2 (колонки максимумов в агрегатах, миграция): вне этого изменения.
|
||||
- Перезапуск `ovp-api` на стенде кратковременно прерывает API; гатерер и тома не трогаем, делается только с разрешения владельца (запрошено в рамках этого изменения при утверждении плана).
|
||||
@@ -0,0 +1,23 @@
|
||||
# Backup: выравнивание бейджей в таблице назначений (сводка, 2026-10-07)
|
||||
|
||||
План: [2026-10-07_Backup_Badges_Align_PLAN.md](2026-10-07_Backup_Badges_Align_PLAN.md)
|
||||
|
||||
## Что изменено
|
||||
|
||||
- `APP_UI/src/views/BackupRestore.vue`, таблица Destinations: у всех пяти ячеек строки (Name, Type, Status, Last result, Actions) добавлен класс Bootstrap `align-top` (вертикальное выравнивание по верху вместо центра). Верхний отступ ячеек общий (12px из `.table td`), поэтому бейджи, название и кнопки действий начинаются на одной линии. Дата в Last result осталась под бейджем. Заголовки (`thead`) не менялись.
|
||||
- Общий `.status-badge`, `main.css` и другие страницы не менялись.
|
||||
- `deploy/ui-dist` пересобран (`deploy/native/build-ui.sh --docker --publish`), `SOURCE_HASH` обновлён.
|
||||
|
||||
## Проверки
|
||||
|
||||
- Node 20 (контейнер `node:20-alpine`, на копии `APP_UI` вне дерева): `npm ci`, `npm run build`, `npm run lint` без ошибок; `npm test`: 13 тестов пройдено.
|
||||
- `deploy/native/check-ui.sh`: `fresh`.
|
||||
- Стенд (проект `ovpmon-test`): пересоздан только `ovp-ui` (порт 8089); `ovp-api`, `ovp-gatherer`, `ovp-profiler` не перезапускались. `ovp-ui` healthy, `curl -sI http://127.0.0.1:8089/` даёт 200 и заголовок CSP, в отданном бандле `BackupRestore-B3KsHsl0.js` класс `align-top` присутствует.
|
||||
|
||||
## Не проверено
|
||||
|
||||
- Визуальная проверка в браузере (`http://192.168.5.9:8089/`): остаётся владельцу. Возможное расхождение по высоте в 1-2 пикселя между текстом названия, бейджами и иконками кнопок из-за разной высоты строки не измерялось.
|
||||
|
||||
## Документация
|
||||
|
||||
`README.md` проекта не менялся: правка чисто визуальная.
|
||||
@@ -0,0 +1,22 @@
|
||||
# Backup: выравнивание бейджей в таблице назначений (план, 2026-10-07)
|
||||
|
||||
Основание: на странице Backup and Restore в таблице Destinations бейджи «Enabled» (колонка Status) и «OK» (колонка Last result) стоят на разной высоте (скриншот владельца).
|
||||
|
||||
## 1. Причина
|
||||
|
||||
Ячейки таблицы выравниваются по вертикали по центру. В колонке Last result под бейджем есть вторая строка (дата), поэтому ячейка выше, а бейдж в ней поднят. В колонках Status и Type бейдж один и стоит по центру строки.
|
||||
|
||||
## 2. Решение
|
||||
|
||||
`APP_UI/src/views/BackupRestore.vue`, таблица назначений: ячейки с бейджами (Type, Status, Last result) выравниваются по верхнему краю (`align-top`), у остальных ячеек строки (Name, Actions) то же выравнивание и одинаковый верхний отступ, чтобы бейджи, название и кнопки действий стояли на одной линии. Дату в Last result оставить под бейджем. Других страниц и общего стиля `.status-badge` не меняем.
|
||||
|
||||
## 3. Шаги
|
||||
|
||||
1. Правка разметки (при необходимости небольшой локальный класс в `main.css`).
|
||||
2. Проверка: `npm run build` и `npm run lint` в Node 20 (контейнер `node:20-alpine`), пересборка `deploy/ui-dist` (`deploy/native/build-ui.sh --publish`, иначе `check-ui.sh` покажет `stale`), пересоздание только `ovp-ui` на стенде.
|
||||
3. Скриншот или проверка владельцем: в среде нет браузера, поэтому визуальную проверку выполняет владелец на `http://192.168.5.9:8089/`.
|
||||
4. Сводка `2026-10-07_Backup_Badges_Align.md`, строка в `DOCS/Changes/README.md`; в `README.md` изменений нет (чисто визуальная правка), это указать в сводке.
|
||||
|
||||
## 4. Тесты
|
||||
|
||||
Автотесты не нужны (вёрстка).
|
||||
@@ -0,0 +1,77 @@
|
||||
# Доставка UI: сборка, CSP и nginx без root (сводка, 2026-10-07)
|
||||
|
||||
План: [2026-10-07_UI_Delivery_Hardening_PLAN.md](2026-10-07_UI_Delivery_Hardening_PLAN.md). Выполнены этапы A-D, по коммиту на этап, последний коммит - документация. Код `APP_UI/src`, бэкенд (`APP_CORE`, `APP_PROFILER`), B4 (`disable-2fa`) и разбиение `BackupRestore.vue` не менялись.
|
||||
|
||||
Решения владельца: для этапа D взят `nginxinc/nginx-unprivileged:alpine` (порт 8080); переменная называется `OVPMON_CSP_CONNECT_EXTRA` (внутри контейнеров `OVP_CSP_CONNECT_EXTRA`), значение - origin через пробел.
|
||||
|
||||
## 1. Что сделано
|
||||
|
||||
### Этап A. `deploy/ui-dist` (коммит `d38acd7`)
|
||||
|
||||
`check-ui.sh` до пересборки: `stale` (сборка `7960728...`, исходники `d778aa1...`). `build-ui.sh --publish` (режим Docker, `node:20-alpine`) опубликовал сборку с `SOURCE_HASH d778aa16...`; `check-ui.sh` после: `fresh`. В коммит вошёл только `deploy/ui-dist` (новые файлы `Clients-*.js`, `useFormatters-*.js`, `useTrafficChart-*.js`, удалены `vite.svg` и старые хеши). Временных файлов в дереве нет.
|
||||
|
||||
### Этап B. CSP и дополнительные origin для `connect-src` (коммит `d5e83ea`)
|
||||
|
||||
| Шаг | Результат |
|
||||
|---|---|
|
||||
| B1 | `APP_UI/Dockerfile`: `ENV OVP_CSP_CONNECT_EXTRA=""`; шаблон: `connect-src 'self' ${OVP_CSP_CONNECT_EXTRA}`; `docker-compose.yml`: `OVP_CSP_CONNECT_EXTRA: ${OVPMON_CSP_CONNECT_EXTRA:-}` |
|
||||
| B2 | All-in-one: переменная добавлена в явный список `envsubst` в `entrypoint.sh`; `docker-compose.allinone.yml` передаёт `OVPMON_CSP_CONNECT_EXTRA` |
|
||||
| B3 | Единый CSP: `set $csp "..."` на уровне `server`, `add_header Content-Security-Policy $csp always;` в `server` и в `location /assets/` |
|
||||
| B4 | Проверка значения (только `https://host[:port]` и `http://host[:port]`, разделитель - пробелы, пустое допустимо; без `;`, кавычек, запятых, путей, пробела в начале и в конце): `deploy/docker/lib.sh` (`csp_extra_problem`, вызывается из `check_env_file`, то есть в `install.sh` и `update.sh`), `deploy/native/lib.sh` (та же функция), `APP_UI/check-csp-connect-extra.sh` - один скрипт для образа `app-ui` (`/docker-entrypoint.d/15-check-csp-connect-extra.sh`, выполняется до `20-envsubst-on-templates.sh`) и для all-in-one (копируется в образ, вызывается из `entrypoint.sh`). Три копии правила содержат комментарий «держать в согласии» |
|
||||
| B5 | Системный nginx: в `ovpmon.conf.template` добавлен CSP с `@CSP_CONNECT_EXTRA@` (на уровне `server`, `Cache-Control: no-store` остался). `render_nginx SRC PORT OUT [ORIGINS]` проверяет значение и подставляет его с ведущим пробелом, при пустом значении ничего не остаётся. `install.sh` и `update.sh` принимают `--csp-connect-extra ORIGINS`, значение хранится в состоянии `OVPMON_CSP_CONNECT_EXTRA`; `update.sh` без флага берёт его из состояния, `--csp-connect-extra ""` убирает; справка обновлена |
|
||||
| B6 | Документация: `DOCS/UI/Architecture.md`, `DOCS/Deployment/Containers/Reference.md`, `Troubleshooting.md`, `DOCS/Deployment/System_Services/Nginx_Configuration.md` (раздел 4), `README.md`, `Operations.md`, `Reference.md` (состояние), `APP_UI/README.md` |
|
||||
|
||||
### Этап C. `npm ci` в all-in-one (коммит `71ea4c5`)
|
||||
|
||||
`deploy/allinone/Dockerfile`: `npm install` -> `npm ci`.
|
||||
|
||||
### Этап D. nginx без root в `app-ui` (коммит `3347fff`)
|
||||
|
||||
| Шаг | Результат |
|
||||
|---|---|
|
||||
| D1 | `APP_UI/Dockerfile`: база `nginxinc/nginx-unprivileged:alpine`, `EXPOSE 8080`, комментарий о root заменён описанием |
|
||||
| D2 | Шаблон: `listen ${OVP_UI_PORT};`; `ENV OVP_UI_PORT=8080` в образе; в all-in-one `entrypoint.sh` задаёт `OVP_UI_PORT=80` и передаёт в `envsubst` |
|
||||
| D3 | `docker-compose.yml`: `"${OVPMON_HTTP_PORT:-80}:8080"`, healthcheck на `http://127.0.0.1:8080/`. `docker-compose.allinone.yml` не менялся (порт 80) |
|
||||
| D4 | В `deploy/docker/*.sh` внутренний порт 80 контейнера `app-ui` не упоминается (скрипты работают только с портом хоста). В документации обновлены `Containers/Reference.md` и `README.md`; прочие «порт 80» относятся к хосту, системному nginx или вариантам, которых изменение не касается |
|
||||
|
||||
## 2. Проверки (команды и результаты)
|
||||
|
||||
Все проверки в одноразовых контейнерах и образах с именами `ovpchk-*`; рабочие контейнеры `ovp-*` не запускались, не останавливались и не перезапускались.
|
||||
|
||||
| Что | Как | Результат |
|
||||
|---|---|---|
|
||||
| A | `deploy/native/check-ui.sh` до и после `build-ui.sh --publish` | `stale` (код 1) -> `fresh` (код 0) |
|
||||
| B4, правило | 23 значения (допустимые: пусто, один origin, два через пробел, с портом, IP; недопустимые: `;`, запятая, кавычки, путь, `*`, `ftp://`, пустой хост и порт, порт 99999, лишний `:`, пробел в начале и в конце, табуляция, `#`, `&`) через `sh` (dash) и `bash` | `deploy/native/lib.sh` и `deploy/docker/lib.sh` дают одинаковый вывод; скрипт `check-csp-connect-extra.sh` в busybox `ash` (контейнер `alpine:3`) принимает и отклоняет те же значения |
|
||||
| B4, `.env` | `check_env_file` с временным `.env` | пустое и допустимое значения проходят, `https://a.com; x` отклонено с сообщением |
|
||||
| B, `app-ui` | образ из `APP_UI` (на тот момент `nginx:alpine`), `curl -I` на `/`, `/assets/*.css`, `/config.json`, `/clients/some/route`, `/index.html`; пустое и непустое значение | заголовок CSP есть везде, origin в `connect-src`; недопустимое значение: контейнер завершается с кодом 1 и сообщением из `15-check-csp-connect-extra.sh` |
|
||||
| B, all-in-one | сборка образа, одноразовый контейнер (без `NET_ADMIN`, без томов), значения допустимое/пустое/недопустимое | допустимое: `200`, CSP с origin, `nginx -T` содержит `$csp` и `listen 80`, `nginx -t` проходит, запуск дошёл до `supervisord`; пустое: `200`, CSP без лишних origin; недопустимое: `FATAL` и остановка до миграций |
|
||||
| B5, системный nginx | `render_nginx` с пустым и непустым значением (в т.ч. с двойным пробелом между origin), `nginx -t` в контейнере `nginx:alpine` с временным сертификатом | оба конфига проходят; в файле нет остатков `@...@`; при пустом значении `connect-src 'self';`; значение с `;` отклонено до записи файла (код 1); `curl -kI` к одноразовому контейнеру: `Cache-Control: no-store` и CSP на `/` и на маршруте SPA |
|
||||
| B5, маркер | `install_managed` для файла без маркера | код 2, файл не изменён |
|
||||
| B5, справка | `install.sh --help`, `update.sh --help` | флаг описан |
|
||||
| C | `docker build --no-cache --target ui-build -f deploy/allinone/Dockerfile .` (чтобы не взять слой из кэша), затем полная сборка | `npm ci`: 201 пакет, `vite build` проходит |
|
||||
| D | образ `app-ui` на `nginx-unprivileged`: `id`, `ps`, `nginx -T`, `curl`, `wget` (команда healthcheck) | uid 101 (`nginx`), все процессы nginx от `nginx`; `listen 8080`; шаблон отрисован; `/`, `/config.json`, маршрут SPA - `200`, заголовки те же; `/api/x` без бэкенда - `502` (допустимо); `wget -q -O /dev/null http://127.0.0.1:8080/` успешен; порядок скриптов `10-listen`, `15-check-csp...`, `15-local-resolvers.envsh`, `20-envsubst`: проверочный скрипт выполняется и останавливает контейнер до отрисовки |
|
||||
| D, all-in-one | пересборка и запуск после D | `listen 80`, `200`, CSP с origin |
|
||||
| compose | `docker compose config` с временным `JWT_SECRET` | `app-ui`: `target: 8080`, `published: "80"`, `OVP_CSP_CONNECT_EXTRA` передан, healthcheck на 8080; all-in-one: конфигурация корректна |
|
||||
| Синтаксис | `sh -n` для изменённых скриптов | без ошибок |
|
||||
| Уборка | `docker image rm` временных образов (`ovpchk-*`, `nginx:alpine`, `nginxinc/nginx-unprivileged:alpine`), временные каталоги и файлы в `/tmp` | остатков нет |
|
||||
|
||||
## 3. Отклонения от плана
|
||||
|
||||
- Значение с пробелом в начале или в конце отклоняется (план: пробел в начале недопустим; конец добавлен для симметрии).
|
||||
- Проверка для `app-ui` и all-in-one вынесена в один скрипт `APP_UI/check-csp-connect-extra.sh` (план предлагал отдельные реализации); правило при этом продублировано ещё в двух библиотеках `lib.sh`.
|
||||
- В контейнере `app-ui` при пустом значении CSP содержит `connect-src 'self' ;` (пробел перед `;`): `envsubst` подставляет пустую строку. Для политики безвредно. В all-in-one и в системном nginx пробелы нормализуются.
|
||||
- Для системного nginx в шаблоне плейсхолдер стоит без пробела перед ним (`'self'@CSP_CONNECT_EXTRA@;`): `render_nginx` добавляет пробел вместе со значением.
|
||||
|
||||
## 4. Что не проверено
|
||||
|
||||
- Живые `install.sh` / `update.sh` на хосте (native и docker) и `docker compose up` стенда: нужно разрешение владельца. Проверены только отдельные функции (`csp_extra_problem`, `render_nginx`, `check_env_file`, `install_managed`), `sh -n`, справка и `docker compose config`.
|
||||
- Обновление существующей установки контейнеров: при `update.sh` пересоздание `ovp-ui` с портом 8080 внутри не запускалось.
|
||||
- Браузерная проверка CSP (шрифты Font Awesome, inline-стили Bootstrap и Chart.js): браузера в среде нет.
|
||||
- Вызов API другого origin с непустым `OVPMON_CSP_CONNECT_EXTRA` (CORS и `config.json`) проверен только по заголовку.
|
||||
- `update.sh` системных служб на установке с уже записанным состоянием (чтение `OVPMON_CSP_CONNECT_EXTRA` из `deploy.state`) не запускался.
|
||||
|
||||
## 5. Риски и примечания
|
||||
|
||||
- Пользовательские compose-файлы или внешний прокси, которые публикуют порт 80 контейнера `ovp-ui`, нужно перевести на 8080 (внешний порт хоста не меняется).
|
||||
- Образ `nginx-unprivileged` не входит в закреплённые версии (тег `alpine`); при необходимости зафиксировать версию.
|
||||
- Значение CSP попадает в заголовок ответа: проверка обязательна, при изменении правила менять все три копии (`deploy/native/lib.sh`, `deploy/docker/lib.sh`, `APP_UI/check-csp-connect-extra.sh`).
|
||||
@@ -0,0 +1,70 @@
|
||||
# Доставка UI: сборка, CSP и nginx без root (план, 2026-10-07)
|
||||
|
||||
Основание: открытые пункты после `2026-10-07_UI_Review_Fixes.md`. Код `APP_UI/src` не меняется. B4 (`disable-2fa`) и разбиение `BackupRestore.vue` остаются вне плана.
|
||||
|
||||
## 1. Что найдено при подготовке
|
||||
|
||||
| Факт | Следствие |
|
||||
|---|---|
|
||||
| `SOURCE_HASH` считается по `APP_UI/src`, `public`, `index.html`, `package*.json`, `vite.config.js`, `jsconfig.json`. Шаблон nginx и `Dockerfile` в хеш не входят | `deploy/ui-dist` устарел из-за этапов 1-4 прошлого изменения; пересборка нужна один раз и не зависит от остальных этапов этого плана |
|
||||
| Шаблон `APP_UI/default.conf.template` общий для образа `app-ui` и all-in-one. Образ `app-ui` подставляет переменные окружения сам, all-in-one вызывает `envsubst` с явным списком `OVP_*` (`deploy/allinone/entrypoint.sh:78`) | Новая переменная должна быть добавлена в оба места, иначе в конфиге останется буквальный `${...}` |
|
||||
| CSP в шаблоне записан дважды (в `server` и в `location /assets/`) | Единый источник: `set $csp "..."` на уровне `server`, `add_header Content-Security-Policy $csp always` в обоих местах |
|
||||
| Системный nginx (`deploy/native/nginx/ovpmon.conf.template`) отдаёт `Cache-Control: no-store` на всё и не имеет CSP; параметры (`HTTPS_PORT`) хранятся через `state_set` и подставляются `render_nginx` | Новый параметр хранится так же; существующие установки получают CSP при `update.sh`, пока в файле есть маркер управления |
|
||||
| Healthcheck `app-ui` и публикация порта в `docker-compose.yml` привязаны к порту 80 | Для nginx без root порт меняется на 8080: правки compose и healthcheck |
|
||||
|
||||
## 2. Этапы
|
||||
|
||||
### Этап A. Пересборка `deploy/ui-dist` (пункт 2)
|
||||
|
||||
1. `deploy/native/check-ui.sh`: зафиксировать `stale` до пересборки.
|
||||
2. `deploy/native/build-ui.sh --publish` (на хосте Node 18, поэтому режим Docker, образ `node:20-alpine`).
|
||||
3. `check-ui.sh`: результат `ok`.
|
||||
4. Коммит `deploy/ui-dist` отдельно от остальных этапов.
|
||||
|
||||
### Этап B. CSP для другого origin API (пункт 3)
|
||||
|
||||
| Шаг | Что делаем |
|
||||
|---|---|
|
||||
| B1 | Контейнеры: переменная `OVP_CSP_CONNECT_EXTRA` (пусто по умолчанию, значение: origin через пробел, например `https://api.example.com`). `ENV OVP_CSP_CONNECT_EXTRA=""` в `APP_UI/Dockerfile`; в шаблоне `connect-src 'self' ${OVP_CSP_CONNECT_EXTRA}`; в `docker-compose.yml` `OVP_CSP_CONNECT_EXTRA: ${OVPMON_CSP_CONNECT_EXTRA:-}` |
|
||||
| B2 | All-in-one: добавить переменную в список `envsubst` и значение по умолчанию в `entrypoint.sh`; `docker-compose.allinone.yml` передаёт `OVPMON_CSP_CONNECT_EXTRA` |
|
||||
| B3 | Единый CSP через `set $csp` (см. выше) |
|
||||
| B4 | Проверка значения: допускаются только `https://host[:port]` и `http://host[:port]` без пробелов, `;` и кавычек (иначе можно внедрить директиву CSP). Для контейнеров проверка в `entrypoint.sh` (all-in-one) и в `deploy/docker/lib.sh` (скрипты установки); для `app-ui` без entrypoint проверка там же, где читается `.env` |
|
||||
| B5 | Системный nginx: CSP добавляется в `ovpmon.conf.template` с плейсхолдером `@CSP_CONNECT_EXTRA@`; `render_nginx` подставляет значение из `state_get OVPMON_CSP_CONNECT_EXTRA` (по умолчанию пусто); `install.sh` и `update.sh` принимают `--csp-connect-extra ORIGINS` и сохраняют его через `state_set`. `Cache-Control: no-store` остаётся |
|
||||
| B6 | Документация: `DOCS/UI/Architecture.md`, `DOCS/Deployment/Containers/Reference.md`, `DOCS/Deployment/System_Services/Nginx_Configuration.md` и `Reference.md` |
|
||||
|
||||
### Этап C. `npm ci` в all-in-one (пункт 4, часть 1)
|
||||
|
||||
`deploy/allinone/Dockerfile`: `npm install` заменить на `npm ci`; сборка образа и `docker-compose.allinone.yml` не меняются. Проверка: `docker build -f deploy/allinone/Dockerfile .` во временный образ (после проверки удалить).
|
||||
|
||||
### Этап D. nginx без root в образе `app-ui` (пункт 5)
|
||||
|
||||
Решение: `nginxinc/nginx-unprivileged:alpine` (шаблоны из `/etc/nginx/templates` рендерятся как и раньше, процесс от пользователя `nginx`, порт 8080).
|
||||
|
||||
| Шаг | Что делаем |
|
||||
|---|---|
|
||||
| D1 | `APP_UI/Dockerfile`: базовый образ `nginxinc/nginx-unprivileged:alpine`, `EXPOSE 8080`; убрать комментарий о root |
|
||||
| D2 | Шаблон: `listen ${OVP_UI_PORT}`. `ENV OVP_UI_PORT=8080` в Dockerfile; в all-in-one значение 80 задаёт `entrypoint.sh` (все процессы там под supervisord от root для OpenVPN, образ не меняется) |
|
||||
| D3 | `docker-compose.yml`: `"${OVPMON_HTTP_PORT:-80}:8080"`, healthcheck на `http://127.0.0.1:8080/`. Внешний порт не меняется |
|
||||
| D4 | Проверка `deploy/docker/*.sh` и документации на упоминания внутреннего порта 80 `app-ui` |
|
||||
| D5 | Проверка в одноразовом контейнере: `nginx -t`, `id` (не root), `curl -I` (заголовки, 200 на `/`, прокси `/api/` отвечает 502 без бэкенда, что допустимо) |
|
||||
|
||||
Если образ без root не подходит (например, политика на образы), этап D откладывается, остальное не затрагивается.
|
||||
|
||||
## 3. Порядок и коммиты
|
||||
|
||||
A, B, C, D: по одному коммиту, этапы независимы. Код пишет субагент (Sonnet 5.5, Medium) после утверждения плана.
|
||||
|
||||
## 4. Проверки
|
||||
|
||||
- **A:** `check-ui.sh` до и после.
|
||||
- **B:** `nginx -t` на шаблоне с пустым и непустым `OVP_CSP_CONNECT_EXTRA`; `curl -I` показывает origin в `connect-src`; недопустимое значение (`;`, пробел в начале, кавычка) отклоняется с понятным сообщением. Для системного nginx: `render_nginx` во временный файл и `nginx -t` в одноразовом контейнере; `update.sh` не затирает файл без маркера.
|
||||
- **C, D:** сборка образов, `nginx -t`, `curl -I`, `docker image rm` временных образов.
|
||||
- Рабочие контейнеры и службы не трогаем; живая проверка `install.sh`/`update.sh` и compose на стенде делается только с разрешения владельца.
|
||||
- Автотесты не добавляем (оболочка и конфигурация).
|
||||
|
||||
## 5. Риски
|
||||
|
||||
- Значение CSP попадает в заголовок: без проверки B4 можно внедрить лишнюю директиву, поэтому проверка обязательна.
|
||||
- Этап D меняет внутренний порт образа: при пользовательских compose-файлах, ссылающихся на порт 80 контейнера `ovp-ui`, нужно обновить публикацию порта. Указать в сводке.
|
||||
- Браузерная проверка (шрифты Font Awesome, inline-стили под CSP) остаётся ручной: в среде нет браузера.
|
||||
- По завершении: сводка `2026-10-07_UI_Delivery_Hardening.md`, строка в `DOCS/Changes/README.md`, обновление `README.md` проекта и профильных документов.
|
||||
@@ -0,0 +1,87 @@
|
||||
# Ревью фронта APP_UI: исправления (сводка, 2026-10-07)
|
||||
|
||||
План: [2026-10-07_UI_Review_Fixes_PLAN.md](2026-10-07_UI_Review_Fixes_PLAN.md). Выполнены этапы 1-4 (U1-U18), по коммиту на этап. Бэкенд (`APP_CORE`, `APP_PROFILER`) не менялся.
|
||||
|
||||
## 1. Что сделано
|
||||
|
||||
### Этап 1. Реальные ошибки
|
||||
|
||||
| ID | Результат |
|
||||
|---|---|
|
||||
| U1 | Неверный пароль или OTP в `change-password` / `change-username` больше не разлогинивает: запросы `/auth/*` идут через отдельный клиент без перехватчика сессии (см. U13). Ошибка показывается тостом, окно остаётся открытым |
|
||||
| U2 | `fetchCertificates` возвращает массив (иначе пустой); `Analytics.vue` читает его напрямую, панель Expiring и KPI заполняются. Сортировка без `\|\| 0` |
|
||||
| U3 | Проверено по `APP_PROFILER/schemas.py` и `PUT /config/server`: схема `SystemSettingsUpdate` задаёт `vpn_netmask = 255.255.255.0` по умолчанию, поэтому при отсутствии поля **каждое сохранение молча сбрасывало маску в /24**, а подсеть другой длины не проходила проверку. Теперь UI отправляет `vpn_netmask` вместе с `vpn_network`. Разбор CIDR вынесен в `src/utils/cidr.js` (проверка октетов, суффикса 0-32, сплошной маски); без суффикса берётся текущая маска; неверный ввод даёт сообщение до запроса. Неиспользуемая переменная `suffix` убрана |
|
||||
| U4 | `formatBytes`: `null`, `undefined`, `NaN`, отрицательные и бесконечные значения дают `0 B`; индекс единицы ограничен таблицей. `formatRate` не даёт `NaN` |
|
||||
| U5 | Сортировка в `Certificates.vue` через `??`: сертификат с 0 дней больше не уходит в конец |
|
||||
|
||||
### Этап 2. Безопасность и поставка
|
||||
|
||||
| ID | Результат |
|
||||
|---|---|
|
||||
| U6 | `default.conf.template`: `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, CSP (`default-src 'self'`, `style-src 'self' 'unsafe-inline'`, `img-src 'self' data:`, `font-src 'self' data:`, `connect-src 'self'`, `frame-ancestors 'none'`, `object-src 'none'`), `gzip`, `server_tokens off`; `/assets/` с `Cache-Control: public, max-age=31536000, immutable` и `404` для отсутствующих файлов; `index.html` и `config.json` с `Cache-Control: no-cache`; удалён лишний `proxy_pass_header Authorization`. Переменные `${OVP_*}` и nginx-переменные не затронуты. `add_header` в `location /assets/` повторяет заголовки безопасности (иначе nginx не наследует их из `server`) |
|
||||
| U7 | `Dockerfile`: `npm ci`; добавлен `.dockerignore` (`node_modules`, `dist`, `.vscode`, `.git`, `*.bak`, `*.log`). Запуск nginx не от root **не сделан**: образ `nginx:alpine` рендерит шаблон в `/etc/nginx/conf.d` и слушает 80; непривилегированный вариант меняет образ и порт (compose публикует `:80`). Причина записана комментарием в `Dockerfile` |
|
||||
| U8 | `v-html` заменён компонентом `StatusBadge.vue` (используется в `Certificates.vue` и `ProfileDetailsModal.vue`, логика статуса в одном месте). Токен остаётся в `localStorage`: **принятый риск** (см. раздел 3) |
|
||||
|
||||
### Этап 3. Чистка и дублирование
|
||||
|
||||
| ID | Результат |
|
||||
|---|---|
|
||||
| U9 | `composables/useTrafficChart.js`: понижение числа точек, подписи, цвета темы, конфиг Chart.js, жизненный цикл графика. `Analytics.vue` и `HistoryModal.vue` используют его (суммарно на 93 строки меньше) |
|
||||
| U10 | `MutationObserver` вынесен в `useThemeObserver` (`composables/useTheme.js`), отключается в `onUnmounted`; в `Account.vue` наблюдатель и переменная `isDark` не использовались и удалены; `URL.revokeObjectURL` после скачивания профиля (через 1 с) |
|
||||
| U11 | `ConfirmModal`: уникальный `id` через `useId()`; `confirm()` в `ServerManagement.vue` и `PKIConfig.vue` (Init, Clear) заменён на `ConfirmModal`; `Swal` в `Account.vue` заменён тостами, результаты 2FA (включено, отключено, ошибка) тоже тостами, `ConfirmModal` остался только для подтверждения отключения 2FA; `sweetalert2` удалён из зависимостей и `vite.config.js` |
|
||||
| U12 | Удалены `Login.vue.bak` (`git rm`), глобальный перехватчик в `main.js` (инстансы `axios.create()` его не наследуют), `sass` (scss не использовался), `props` в `HistoryModal`, `id="themeIcon"`/`refreshIcon`, пустые `<p></p>` (отступ после заголовка секции сохранён правилом `.nav-section-header + .nav-link` в CSS), неиспользуемый `apiClient` в `Clients.vue`; `proccessData` -> `processData` |
|
||||
| U13 | `authApiClient` (база `/api/auth`, выводится из `api_base_url` заменой `/v1` на `/auth`); хак `'../auth/...'` убран из `Login.vue` и `Account.vue` |
|
||||
| U14 | Маршрут-ловушка `/:pathMatch(.*)*` с перенаправлением на `/` (гостя защита маршрутов отправит на вход); `Clients` грузится лениво, страница входа не тянет `chart.js`; `isAuthenticated` в `App.vue` определяется токеном и публичностью маршрута |
|
||||
| U15 | `BaseModal`: размер через `computed`, убрано событие-дубль `close` (оставлено `closed`; `@close` нигде не использовался); `NewClientModal`: фокус по событию `opened`, проверка имени, кнопка неактивна при неверном имени; `HistoryModal.loadHistory`: счётчик запросов, устаревший ответ отбрасывается (и при закрытии окна) |
|
||||
|
||||
Тема (часть U17) сделана в этапе 3: `initTheme()` вызывается в `main.js` до монтирования приложения (без мигания), при первом запуске берётся `prefers-color-scheme`, дальше сохранённый выбор.
|
||||
|
||||
### Этап 4. Доступность и оформление
|
||||
|
||||
| ID | Результат |
|
||||
|---|---|
|
||||
| U16 | `Login.vue`: `label for`/`id`, `autocomplete="username"` / `"current-password"` / `"one-time-code"`, `inputmode="numeric"` и `aria-label` у кода 2FA (то же в `Account.vue`, плюс `new-password`); строки таблицы сертификатов фокусируются и открываются по Enter, ссылка клиента в `Clients.vue` получила `href="#"`, заголовки сортировки - `tabindex` и Enter |
|
||||
| U17 | Единое имя «OpenVPN Controller» (вход, боковая панель, текст в Account, подвал), favicon `logo.svg` вместо `vite.svg` (файл удалён), тема по системной настройке |
|
||||
| U18 | ESLint 10 с минимальной конфигурацией (`eslint.config.js`: recommended + `vue/flat/essential`, `npm run lint`, замечаний нет). `BackupRestore.vue` не разбивался (вынесено в отдельное изменение, как в плане) |
|
||||
|
||||
## 2. Что не сделано и почему
|
||||
|
||||
| Пункт | Причина |
|
||||
|---|---|
|
||||
| B4 (`disable-2fa` требует пароль) | Вне плана: решение владельца, затрагивает бэкенд |
|
||||
| Разбиение `BackupRestore.vue` (803 строки) | По плану отдельное изменение |
|
||||
| Запуск nginx не от root (U7) | См. выше: ломает схему образа и порт |
|
||||
| Ручная проверка в браузере | Браузера на стенде нет (см. раздел 4) |
|
||||
| `deploy/ui-dist` (закоммиченная сборка UI для системных служб) | Не обновлялась: `deploy/native/check-ui.sh` показывает `stale`. Нужно `deploy/native/build-ui.sh --publish` и коммит `deploy/ui-dist` (шаг мейнтейнера) |
|
||||
|
||||
## 3. Принятый риск: токен в localStorage
|
||||
|
||||
JWT хранится в `localStorage` (`ovpmon_token`). Любой XSS на странице может его прочитать. Меры, которые снижают риск: нет `v-html` с данными, CSP (`script-src 'self'`) в контейнерном nginx, `X-Frame-Options`. Переход на `HttpOnly`-cookie требует схемы cookie и защиты от CSRF на бэкенде (`APP_CORE`) и в этом изменении не делается.
|
||||
|
||||
## 4. Проверки
|
||||
|
||||
| Проверка | Результат |
|
||||
|---|---|
|
||||
| `npm ci --dry-run` (после обновления `package-lock.json`) | проходит |
|
||||
| `npm run build` (Node 20, контейнер `node:20-alpine`) | проходит; главный чанк 249 -> 238 кБ, `vendor-ui` 162 -> 82 кБ, `chart.js` на странице входа не грузится |
|
||||
| `npm test` (Vitest) | 3 файла, 13 тестов проходят: `formatBytes`/`formatRate` (U4), разбор CIDR (U3), клиент `/auth/*` не разлогинивает на 401, остальные разлогинивают (U1) |
|
||||
| `npm run lint` | без замечаний |
|
||||
| `docker build APP_UI` (временный образ, удалён) | собирается с `npm ci` |
|
||||
| `nginx -t` с отрендеренным шаблоном (одноразовый контейнер из образа `nginx:alpine`, без обращения к рабочим контейнерам) | успешно |
|
||||
| Заголовки (`curl -I` к одноразовому контейнеру с собранным `dist`, порт 127.0.0.1:18080, потом остановлен) | `/`, `/index.html`, `/config.json`, маршрут SPA: `Cache-Control: no-cache`, 4 заголовка безопасности; `/assets/*.js`: `immutable`, `Content-Encoding: gzip`, заголовки безопасности; несуществующий `/assets/nope.js`: 404 |
|
||||
| Ручной проход в браузере (неверный пароль в Account, панель Expiring, смена маски, темы, модальные окна, клавиатура, CSP без нарушений в консоли) | **не выполнялся**: браузера нет. Остаётся для владельца. Риск CSP из плана (шрифты Font Awesome, inline-стили) проверен только по составу сборки: шрифты берутся из `/assets/`, `style-src` допускает inline |
|
||||
|
||||
## 4.1. Отклонения от плана
|
||||
|
||||
- Тема перенесена в этап 3 (общий файл `App.vue`).
|
||||
- Имя клиента: `^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$` вместо `^[A-Za-z0-9_-]+$`: первый символ и длина совпадают с правилом профилировщика (`schemas.py`, `username`), точки не разрешены, как и в подсказке формы.
|
||||
- `Cache-Control` для `/assets/` без `expires`, одной строкой `public, max-age=31536000, immutable`.
|
||||
- Для U1 не использовано сопоставление текста ошибки токена («Token has expired»): при истёкшей сессии запрос `/auth/*` покажет ошибку, разлогинит следующий обычный запрос (смена маршрута вызывает `/user/me`).
|
||||
- `eslint` 10 с `@eslint/js` и `globals`: выбрано, так как 9.x помечен в npm как неподдерживаемый.
|
||||
|
||||
## 5. Открытые вопросы
|
||||
|
||||
1. Нужен ли CSP `connect-src 'self'` во всех развёртываниях: если `config.json` указывает на другой origin API, его нужно добавить в `connect-src` (контейнерный шаблон).
|
||||
2. Системные службы (`deploy/native/nginx/ovpmon.conf.template`) уже имеют свои заголовки без CSP и с `Cache-Control: no-store`; all-in-one использует `APP_UI/default.conf.template` (получил заголовки), его `Dockerfile` по-прежнему делает `npm install` (`deploy/allinone/Dockerfile`, не менялся).
|
||||
3. Обновить `deploy/ui-dist` (см. раздел 2).
|
||||
4. B4 и разбиение `BackupRestore.vue`.
|
||||
@@ -0,0 +1,71 @@
|
||||
# Ревью фронта APP_UI: план исправлений (план, 2026-10-07)
|
||||
|
||||
Основание: ревью `APP_UI` (Vue 3, Vite, Bootstrap). Код не менялся; план делится на этапы, каждый можно выполнить и проверить отдельно.
|
||||
|
||||
## 1. Область
|
||||
|
||||
Входит: `APP_UI/` (код, `default.conf.template`, `Dockerfile`, `package.json`).
|
||||
Не входит: изменения API бэкенда, кроме п. B4 (отдельное решение владельца).
|
||||
|
||||
## 2. Найденное и решение
|
||||
|
||||
### Этап 1. Реальные ошибки (приоритет высокий)
|
||||
|
||||
| ID | Проблема | Решение |
|
||||
|---|---|---|
|
||||
| U1 | Неверный `current_password` или OTP в `change-password` / `change-username` даёт HTTP 401 (`openvpn_api_v3.py:859, 909, 913`). Перехватчик `useApi.js` на любой 401 чистит токен и уходит на `/login`: пользователь разлогинен, ошибки не видит | В перехватчике не считать 401 истечением сессии для запросов `/auth/*` (кроме проверки токена). Бэкенд не меняем |
|
||||
| U2 | `Analytics.vue`: `fetchCertificates` возвращает массив, код проверяет `res.success && Array.isArray(res.data)`; панель «Expiring» и KPI всегда пусты | Принимать массив; общий разбор ответа в `useApi` |
|
||||
| U3 | `VPNConfig.vue`: суффикс CIDR отбрасывается, `vpn_netmask` в форме нет; смена маски не применяется | Преобразовывать CIDR в маску и отправлять `vpn_netmask` вместе с `vpn_network`; убрать неиспользуемую переменную |
|
||||
| U4 | `formatBytes(null/undefined)` даёт «NaN undefined» | Защита: нечисло или отрицательное значение даёт «0 B» |
|
||||
| U5 | `Certificates.vue`: `days_remaining \|\| 9999` отправляет сертификат с 0 днями в конец списка | Сравнение через `?? ` |
|
||||
|
||||
### Этап 2. Безопасность и поставка
|
||||
|
||||
| ID | Проблема | Решение |
|
||||
|---|---|---|
|
||||
| U6 | nginx без заголовков безопасности, gzip и кэширования ассетов; лишний `proxy_pass_header Authorization` | Добавить `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, CSP (разрешить `self`, `data:` для картинок, inline-стили Bootstrap/Chart.js), gzip; `Cache-Control` для `/assets/` (immutable) и `no-cache` для `index.html` и `config.json`; убрать лишнюю директиву |
|
||||
| U7 | `Dockerfile`: `npm install`, нет `.dockerignore`, nginx от root | `npm ci`, `.dockerignore` (`node_modules`, `dist`, `.vscode`, `*.bak`); оставить базовый образ, если запуск не от root ломает шаблон конфигурации (решить при проверке) |
|
||||
| U8 | Токен в `localStorage` и `v-html` в `Certificates.vue` | `v-html` заменить шаблоном (статусный бейдж как компонент). Хранение токена не меняем (требует cookie-схемы на бэкенде), фиксируем как принятый риск в `DOCS` |
|
||||
|
||||
### Этап 3. Чистка и устранение дублирования
|
||||
|
||||
| ID | Проблема | Решение |
|
||||
|---|---|---|
|
||||
| U9 | Дубль кода графиков в `Analytics.vue` и `HistoryModal.vue` (downsample, метки, цвета темы, конфиг Chart.js) | Composable `useTrafficChart` |
|
||||
| U10 | `MutationObserver` в `Analytics.vue` и `Account.vue` не отключается; `URL.createObjectURL` не освобождается | `disconnect()` в `onUnmounted`; `revokeObjectURL` |
|
||||
| U11 | Дубль `id="confirmModal"` при нескольких `ConfirmModal`; три способа подтверждения (`confirm()`, `ConfirmModal`, `Swal`); `ConfirmModal` как окно «Success» | Уникальный `id` (проп или счётчик); `confirm()` в Server и PKI заменить на `ConfirmModal`; `Swal` в Account заменить на тосты и `ConfirmModal`; удалить `sweetalert2` |
|
||||
| U12 | Мёртвый код: глобальный перехватчик в `main.js` (инстансы `axios.create()` его не наследуют), `Login.vue.bak`, неиспользуемые `props` в `HistoryModal`, `id="themeIcon"`/`refreshIcon`, пустые `<p></p>`, `proccessData`, `sass` | Удалить; переименовать функцию |
|
||||
| U13 | Хак `'../auth/login'` в `apiClient` | Отдельный инстанс `authApiClient` на `/api/auth` в `useApi` |
|
||||
| U14 | Нет маршрута 404; `Clients` и `Login` грузятся статически и тянут `chart.js` на странице входа; `isAuthenticated` в `App.vue` зависит от имени маршрута | Catch-all маршрут (перенаправление на `/`); ленивая загрузка `Clients`; `isAuthenticated` по токену |
|
||||
| U15 | `BaseModal`: `sizeClass` не реактивен, дубль `close`/`closed`; `NewClientModal`: фокус через `setTimeout(500)`, нет проверки имени; гонка в `HistoryModal.loadHistory` | Computed для размера; фокус по событию `opened`; проверка `^[A-Za-z0-9_-]+$`; игнорировать устаревший ответ |
|
||||
|
||||
### Этап 4. Доступность и оформление (низкий приоритет)
|
||||
|
||||
| ID | Проблема | Решение |
|
||||
|---|---|---|
|
||||
| U16 | Login: нет `for` у `label`, `autocomplete`, `inputmode`; кликабельные `<tr>` и `<a>` без клавиатуры | `autocomplete="username"/"current-password"/"one-time-code"`, `inputmode="numeric"`; `href`/`tabindex` и Enter для кликабельных элементов |
|
||||
| U17 | Разные названия продукта, favicon Vite, подвал «Admin Dashboard», тема без `prefers-color-scheme` | Единое имя «OpenVPN Controller», свой favicon (`logo.svg`), тема по системной настройке при первом запуске, установка до монтирования (без мигания) |
|
||||
| U18 | Нет линтера; `BackupRestore.vue` 803 строки | ESLint (минимальная конфигурация для Vue). Разбиение `BackupRestore.vue` вынести в отдельное изменение, здесь не делаем |
|
||||
|
||||
### Требует решения владельца (вне плана)
|
||||
|
||||
| ID | Вопрос |
|
||||
|---|---|
|
||||
| B4 | `POST /auth/disable-2fa` не требует пароля или OTP: украденная сессия отключает 2FA. Предлагается требовать `current_password` (и OTP). Затрагивает бэкенд (`APP_CORE`) и форму в `Account.vue` |
|
||||
|
||||
## 3. Порядок выполнения
|
||||
|
||||
1. Утвердить план. Субагент (Sonnet 5.5, Medium) пишет код по этапам 1-4, каждый этап отдельным коммитом.
|
||||
2. Этап 1 и U6/U7: проверка сборкой (`npm run build`) и вручную в браузере (неверный пароль в Account, панель Expiring, смена маски, заголовки `curl -I`).
|
||||
3. Этапы 3-4: сборка, ручной проход по всем страницам (темы, модальные окна, обновление данных, переходы между страницами без ошибок в консоли).
|
||||
4. Сводка `2026-10-07_UI_Review_Fixes.md`, строка в `DOCS/Changes/README.md`, обновление `APP_UI/README.md` и `DOCS/UI`.
|
||||
|
||||
## 4. Тесты
|
||||
|
||||
Минимум (Vitest, добавляется в `devDependencies`): `useFormatters` (U4), разбор CIDR в маску (U3), перехватчик 401 для `/auth/*` (U1). Остальное: сборка и ручная проверка.
|
||||
|
||||
## 5. Риски
|
||||
|
||||
- CSP (U6) может блокировать inline-стили и шрифты Font Awesome: проверить в браузере, при необходимости `style-src 'unsafe-inline'`.
|
||||
- Замена `Swal` (U11) меняет вид сообщений в Account: согласовать на ревью.
|
||||
- U3 зависит от поведения `PUT /config/server`: перед правкой проверить, что частичная схема не сбрасывает `vpn_netmask`.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Показ нескольких сессий клиента в UI (сводка, 2026-11-12)
|
||||
|
||||
План: [2026-11-12_Multi_Session_UI_PLAN.md](2026-11-12_Multi_Session_UI_PLAN.md)
|
||||
|
||||
## Что изменено
|
||||
|
||||
- `APP_CORE/openvpn_api_v3.py`, `get_current_stats`: один запрос к `active_sessions`, группировка по CN. В запись клиента добавлены `sessions_count` и `sessions` (адрес, начало в UTC, байты, МБ). Для отключённых клиентов `0` и `[]`; при отсутствии таблицы список пуст. Прежние поля не менялись, `/api/v1/stats` отдаёт новые поля без правок маршрута.
|
||||
- `APP_UI/src/views/Clients.vue`: бейдж «×N» (кнопка, `aria-expanded`) при двух и более сессиях; «N devices» вместо одного адреса; раскрывающиеся строки сессий (адрес, начало, Down/Up в МБ), состояние раскрытия в `ref` переживает автообновление; KPI «Active Sessions» рядом с «Active Clients».
|
||||
- `APP_UI/src/utils/sessions.js`: чистые функции `sessionsBadge`, `toggleExpanded`, `visibleSessions`.
|
||||
- `deploy/ui-dist` пересобран (`deploy/native/build-ui.sh --docker --publish`), `SOURCE_HASH` обновлён.
|
||||
- Документация: `DOCS/Core_Monitoring/API_Reference.md` (новые поля), `DOCS/UI/Architecture.md` (страница Clients), строка в `DOCS/Changes/README.md`.
|
||||
- Сборщик, схема БД и миграции не менялись.
|
||||
|
||||
## Тесты (2 шт.)
|
||||
|
||||
- `APP_CORE/test_multi_session.py`: CN с двумя сессиями, CN с одной, отключённый CN; прежние поля без изменений.
|
||||
- `APP_UI/src/utils/sessions.test.js`: бейдж только при `sessions_count > 1`, раскрытие и сворачивание.
|
||||
|
||||
## Проверки
|
||||
|
||||
`pytest` в `APP_CORE`: 19 passed. `npm test`: 15 passed. `npm run lint`: без замечаний. Сборка UI в контейнере прошла, `SOURCE_HASH` совпадает с исходниками.
|
||||
|
||||
## Отклонения от плана и ограничения
|
||||
|
||||
- UI-тест проверяет чистые функции, а не смонтированный компонент: `@vue/test-utils` в проекте нет, зависимость не добавлялась.
|
||||
- API-тест вызывает `api.get_current_stats()` напрямую: маршрут закрыт JWT и лишь пробрасывает поля. Красный прогон на старом коде отдельно не делался.
|
||||
- Видимой подписи «Show sessions» нет, только `title` и `aria-expanded`.
|
||||
- Ручная проверка на стенде с двумя устройствами под одним CN (шаг 4 плана) **не выполнена**.
|
||||
- Коммит не создан.
|
||||
@@ -0,0 +1,56 @@
|
||||
# Показ нескольких сессий клиента в UI (план, 2026-11-12)
|
||||
|
||||
Источник: анализ состояния проекта (запрос от 2026-11-12). Затронутый код: `APP_CORE/openvpn_api_v3.py`, `APP_UI/src/views/Clients.vue`, `APP_CORE/test_*.py`, `APP_UI/src/**/*.test.js`.
|
||||
|
||||
Цель: в списке клиентов видно, что пользователь (CN) подключён с нескольких устройств, и можно посмотреть параметры каждой сессии.
|
||||
|
||||
## 1. Исходное состояние
|
||||
|
||||
- Сборщик пишет по строке на сессию в `active_sessions` (адрес, байты, `connected_since`, `session_id`), таблица обновляется каждый тик.
|
||||
- `/api/v1/stats` отдаёт одну запись на CN: статус `Active`/`Disconnected`, суммарные байты и скорость, `real_address` последней сессии.
|
||||
- `/api/v1/sessions` отдаёт все активные сессии, но UI его не вызывает.
|
||||
- В UI число сессий и список устройств не видны.
|
||||
|
||||
## 2. Решение
|
||||
|
||||
Расширить `/api/v1/stats`, а не добавлять второй запрос из UI: поллинг остаётся один, данные согласованы между собой.
|
||||
|
||||
| ID | Изменение | Результат |
|
||||
|---|---|---|
|
||||
| MU-1 | `get_current_stats`: один запрос к `active_sessions`, сессии группируются по `common_name`; в каждую запись клиента добавляются `sessions_count` (0 для отключённых) и `sessions` (адрес, `connected_since` в UTC, байты приёма и отправки) | API отдаёт число и список сессий вместе с клиентом |
|
||||
| MU-2 | `Clients.vue`: бейдж «×N» рядом со статусом, если `sessions_count > 1`; в колонке адреса при N > 1 показывать «N devices» вместо одного адреса | многосессионность видна в списке |
|
||||
| MU-3 | `Clients.vue`: по клику на бейдж раскрывается вложенная строка со списком сессий (адрес, начало, Down/Up в МБ), повторный клик скрывает; состояние раскрытия хранится в `ref` и переживает автообновление | детали по каждому устройству |
|
||||
| MU-4 | KPI на странице Clients: рядом с `Active clients` показать общее число сессий (сумма `sessions_count`) | видна нагрузка по сессиям, а не только по пользователям |
|
||||
|
||||
Вне объёма: изменение сборщика, схемы БД, метрики `Concurrent Users (Peak)` на Analytics (она считает пользователей, это корректно), принудительное отключение сессии.
|
||||
|
||||
## 3. Шаги
|
||||
|
||||
| # | Шаг | Результат |
|
||||
|---|---|---|
|
||||
| 0 | Тест API (красный на текущем коде): две строки `active_sessions` у одного CN, одна у другого, ни одной у третьего | поведение зафиксировано |
|
||||
| 1 | MU-1 в `openvpn_api_v3.py`; обратная совместимость: существующие поля не меняются, поля только добавляются; при отсутствии таблицы `active_sessions` `sessions = []` | тест из шага 0 зелёный |
|
||||
| 2 | MU-2, MU-4 в `Clients.vue` | бейдж и счётчик |
|
||||
| 3 | MU-3 в `Clients.vue` | раскрывающийся список |
|
||||
| 4 | Сборка UI и пересборка `deploy/ui-dist` по принятой процедуре проекта; ручная проверка на стенде с двумя клиентами под одним CN | подтверждено в реальном UI |
|
||||
| 5 | Документация: `DOCS/Core_Monitoring/API_Reference.md` (поля `sessions_count`, `sessions`), `DOCS/UI` (описание страницы Clients), README.md, строка в таблице `DOCS/Changes/README.md`, сводка `2026-11-12_Multi_Session_UI.md` | документация актуальна |
|
||||
|
||||
## 4. Автотесты (минимум, 2 шт.)
|
||||
|
||||
1. **API** (`pytest`, в `APP_CORE`): `/api/v1/stats` возвращает `sessions_count` и `sessions` для CN с двумя сессиями, `0` и пустой список для отключённого, прежние поля без изменений.
|
||||
2. **UI** (`Vitest`): компонент показывает бейдж «×2» только при `sessions_count > 1` и раскрывает список сессий по клику.
|
||||
|
||||
## 5. Совместимость и риски
|
||||
|
||||
- Схема и сборщик не меняются, миграций нет. Откат: возврат кода API и UI.
|
||||
- Новые поля только добавляются, другие потребители `/api/v1/stats` не затронуты.
|
||||
- Размер ответа растёт на число активных сессий (десятки строк), на поллинг не влияет.
|
||||
- `connected_since` хранится в UTC, в UI выводится так же, как другие даты на странице, формат единый.
|
||||
- Между двумя тиками сборщика список сессий может отставать на один тик; для мониторинга это допустимо.
|
||||
|
||||
## 6. Порядок выполнения
|
||||
|
||||
1. Утверждение плана.
|
||||
2. Реализация субагентом (Sonnet 5.5, Medium Effort): шаги 0-3.
|
||||
3. Проверка: `pytest` в `APP_CORE`, `npm test` и ESLint в `APP_UI`, ручная проверка (шаг 4).
|
||||
4. Документация и сводка (шаг 5).
|
||||
@@ -0,0 +1,36 @@
|
||||
# Суммаризация: доработки по итогам обновления ПРОД (2026-11-12)
|
||||
|
||||
План: [2026-11-12_Prod_Upgrade_Fixes_PLAN.md](2026-11-12_Prod_Upgrade_Fixes_PLAN.md). Источник: `prod_upgrade_findings.md`.
|
||||
|
||||
## Что сделано
|
||||
|
||||
| Шаг | Изменение | Файлы |
|
||||
|-----|-----------|-------|
|
||||
| 1 | `Query(None, enum=[...])` → `Optional[Literal["server", "pki"]] = Query(None)`; тест значений параметра (200 / 422) | `APP_PROFILER/routers/system.py`, `APP_PROFILER/test_config_section.py` |
|
||||
| 2 | Закреплены `fastapi==0.143.3`, `starlette==1.8.0`, `uvicorn==0.54.0`, `pydantic==2.14.1`; в `APP_CORE` добавлены верхние границы по мажору | `APP_PROFILER/requirements.txt`, `APP_CORE/requirements.txt` |
|
||||
| 3 | При отказе `wait_http` выводится лог связанных сервисов (API → свой сервис, nginx-проверки → все) | `deploy/native/lib.sh` |
|
||||
| 4 | `OLD_VERSION`: `deploy.state` → `<prefix>/VERSION` → `unknown` | `deploy/native/update.sh` |
|
||||
| 5 | `migrate.py`: подсказка `Hint:` про `OVPMON_*_DB_PATH`, если БД не найдена и `--db` не задан; коды возврата не менялись | `APP_CORE/migrate.py`, `APP_PROFILER/migrate.py` |
|
||||
| 6 | Документация: `--source --no-pull`, фиксация зависимостей, `PIP_CONSTRAINT` | `DOCS/Deployment/System_Services/Operations.md`, `README.md`, `DOCS/Changes/README.md` |
|
||||
| + | Починены два устаревших теста `test_server_process.py` (см. ниже) | `APP_PROFILER/test_server_process.py` |
|
||||
|
||||
## Проверка (ревью после субагента)
|
||||
|
||||
- Дифф сверен с планом: все шаги выполнены, лишних изменений нет. Имена переменных БД сверены с `APP_CORE/db.py` и `install.sh`.
|
||||
- `bash -n` для `lib.sh` и `update.sh`: без ошибок.
|
||||
- Тесты в `venv` проекта: `APP_CORE` 19 passed; `APP_PROFILER` 25 passed (после правки ниже).
|
||||
- Тесты `APP_PROFILER` в чистом окружении с закреплённым набором (fastapi 0.143.3, starlette 1.8.0, uvicorn 0.54.0, pydantic 2.14.1): те же результаты до правки тестов. Закреплённый набор ставится и работает.
|
||||
|
||||
## Починка двух падавших тестов
|
||||
|
||||
`test_server_process.py::test_get_stats` и `::test_control_invalid` падали с 404 и до нашего изменения. Причина в самих тестах: они ходили на `/server/process/...` без префикса `/api` (роутер подключён с ним с первого коммита) и без подмены `verify_token` (иначе 401). Приложение работает правильно (на `/api/...` с токеном: 200 и 400). Исправлено: добавлен префикс `/api`, подмена `verify_token` и временная БД по образцу `test_pki_guard.py`; убран мёртвый блок `__main__` и `print`. Тест `stats` проверяет только форму ответа.
|
||||
|
||||
## Не проверено
|
||||
|
||||
- Вывод лога сервиса при реальном отказе health-check и расчёт `OLD_VERSION` на хосте с `deploy.state`: проверены только синтаксис и чтение кода, на живой установке не запускались.
|
||||
- Верхние границы в `APP_CORE/requirements.txt` (`Flask-Cors<7`, `qrcode<9`, `bcrypt<6`) выбраны по текущим мажорам; сверить с набором на ПРОД.
|
||||
|
||||
## Вне объёма
|
||||
|
||||
- Команда «показать diff и применить» для ручных установок.
|
||||
- Расследование повторов `Client disconnected` в логе gatherer.
|
||||
@@ -0,0 +1,36 @@
|
||||
# План: доработки по результатам обновления ПРОД (2026-11-12)
|
||||
|
||||
Источник: `prod_upgrade_findings.md`. Статус: **ожидает утверждения**.
|
||||
|
||||
## Проверка находок по коду
|
||||
|
||||
| # | Находка | Статус в коде | Решение |
|
||||
|---|---------|---------------|---------|
|
||||
| 1 | `Query(..., enum=...)` падает на новом FastAPI; зависимости без версий | Подтверждено: единственное место `APP_PROFILER/routers/system.py:16`; `APP_PROFILER/requirements.txt` без версий, `APP_CORE` только `>=` | Исправить |
|
||||
| 2 | Health-check не показывает причину отказа | Лог выводится только если сервис не `active`; при ошибке HTTP (`wait_http`) лога нет | Исправить |
|
||||
| 3 | `OLD_VERSION == NEW_VERSION` в итоге | `OLD_VERSION` берётся из `$PREFIX/VERSION`, а не из `deploy.state` | Исправить + описать режим `--source --no-pull` в документации |
|
||||
| 4a | `migrate.py --check` код 2 без окружения | Не ошибка: код 2 = «есть неприменённые миграции» (БД по умолчанию не существует) | Только понятное сообщение, когда БД не найдена |
|
||||
| 4b | Нужен GNU tar | Уже есть: `check_gnu_tar` в `update.sh:271` | Не требуется |
|
||||
| 4c | Ручная установка: diff шаблонов | Отдельная функция (новая команда) | Вне объёма, отдельное изменение |
|
||||
| 4d | Повтор `Client disconnected` каждые ~20 с | Не расследовалось | Вне объёма, отдельное расследование |
|
||||
|
||||
## Шаги
|
||||
|
||||
1. **Совместимость профайлера.** `routers/system.py`: `Query(None, enum=[...])` → `Literal["server", "pki"]` (с сохранением значения по умолчанию `None`). Один тест на значения параметра (допустимое / недопустимое → 422).
|
||||
2. **Фиксация зависимостей.**
|
||||
- `APP_PROFILER/requirements.txt`: `fastapi==0.143.3`, `starlette==1.8.0`, `uvicorn==0.54.0`, `pydantic==2.14.1` (рабочий набор с ПРОД); остальные пакеты без изменений.
|
||||
- `APP_CORE/requirements.txt`: добавить верхние границы по мажорной версии (`Flask>=3.0.0,<4` и т. д.).
|
||||
- Прогнать тесты в `venv` на зафиксированном наборе.
|
||||
3. **Диагностика health-check** (`deploy/native/lib.sh`): при отказе `wait_http` выводить `show_service_log` для сервиса, к которому относится проверка (monitoring API → `ovpmon-api`, profiler API → `ovpmon-profiler`; для nginx-проверок — все сервисы).
|
||||
4. **Версия «до»** (`deploy/native/update.sh`): `OLD_VERSION` брать из `OVPMON_VERSION` в `deploy.state`, при отсутствии — из `$PREFIX/VERSION`.
|
||||
5. **`migrate.py`** (оба компонента): если БД не существует и `--db` не задан, добавить в вывод подсказку про `OVPMON_*_DB_PATH` / `/etc/ovpmon/env`. Код возврата не меняется.
|
||||
6. **Документация.** В `DOCS/Deployment` описать режим `--source --no-pull` (состояние git-каталога установки, `git reset --hard origin/main` с сохранением живого `config.ini`), фиксацию зависимостей и `PIP_CONSTRAINT`. Обновить `README.md` и `DOCS/Changes/README.md`.
|
||||
|
||||
## Исполнение
|
||||
|
||||
Код пишет субагент (Sonnet 5.5, Medium Effort) после утверждения плана. По завершении — файл `2026-11-12_Prod_Upgrade_Fixes.md` (суммаризация).
|
||||
|
||||
## Риски
|
||||
|
||||
- Закреплённые версии устареют: обновлять осознанно, проверкой тестами. Для Docker-образов набор тот же, пересборка подтянет его.
|
||||
- Изменение `Literal` меняет схему OpenAPI (enum остаётся, формат корректнее).
|
||||
@@ -25,3 +25,9 @@ Every change has a plan (`*_PLAN.md`) before it and a summary of what was done a
|
||||
| 2026-10-07 | Резервное копирование и восстановление из UI и API (проход 1 из 3): пакет с базами, PKI и профилями, шифрование, назначения Local и S3, ротация, восстановление с миграцией и откатом, страница Backup and Restore | [plan](2026-10-07_Backup_Restore_PLAN.md) · [change](2026-10-07_Backup_Restore.md) · [guide](../Profiler_Management/Backup_Restore.md) |
|
||||
| 2026-10-07 | Резервное копирование: замечания и дополнения: имя сервера и точное время UTC в имени пакета, назначения SFTP (закрепление отпечатка ключа хоста) и FTP/FTPS, миграции монитора в образе профилировщика (вариант B), ограничение частоты сообщений сборщика, раздел Backups в Security_Architecture | [plan](2026-10-07_Backup_Restore_Fixes_PLAN.md) · [change](2026-10-07_Backup_Restore_Fixes.md) · [guide](../Profiler_Management/Backup_Restore.md) |
|
||||
| 2026-10-07 | Проверка скриптов установки и миграции на новом коде: проверка версии compose для варианта B (Docker Compose 2.17+), `ovpmon_backup.db` в резервной копии и восстановлении системных служб | [plan](2026-10-07_Deploy_Scripts_Check_PLAN.md) · [change](2026-10-07_Deploy_Scripts_Check.md) |
|
||||
| 2026-10-07 | Ревью фронта: 401 на `/auth/*` не разлогинивает, панель Expiring, `vpn_netmask` при сохранении (раньше сбрасывалась в /24), заголовки безопасности и кэш в nginx, `npm ci`, общий код графиков, `ConfirmModal` и тосты вместо `confirm()`/SweetAlert2, отдельный клиент `/api/auth`, доступность, ESLint и Vitest | [plan](2026-10-07_UI_Review_Fixes_PLAN.md) · [change](2026-10-07_UI_Review_Fixes.md) |
|
||||
| 2026-10-07 | Доставка UI: пересборка `deploy/ui-dist`, единый CSP с `OVPMON_CSP_CONNECT_EXTRA` (контейнеры и системный nginx, флаг `--csp-connect-extra`), `npm ci` в all-in-one, `app-ui` на `nginx-unprivileged` (порт 8080 внутри) | [plan](2026-10-07_UI_Delivery_Hardening_PLAN.md) · [change](2026-10-07_UI_Delivery_Hardening.md) |
|
||||
| 2026-10-07 | Backup: бейджи Type, Status и Last result в таблице Destinations выровнены по верхнему краю строки (`align-top`), дата остаётся под бейджем | [plan](2026-10-07_Backup_Badges_Align_PLAN.md) · [change](2026-10-07_Backup_Badges_Align.md) |
|
||||
| 2026-10-07 | Скорость (Mbps) на графиках за период больше суток: средняя скорость корзины из байтов агрегатных таблиц вместо нулей (история клиента и Analytics), подписи «RX/TX Mbps (avg)» | [plan](2026-10-07_Aggregated_Speed_PLAN.md) · [change](2026-10-07_Aggregated_Speed.md) |
|
||||
| 2026-11-12 | Clients: несколько сессий одного пользователя видны в UI: бейдж «×N», «N devices» вместо адреса, раскрывающийся список сессий, KPI Active Sessions; `/api/v1/stats` отдаёт `sessions_count` и `sessions` | [plan](2026-11-12_Multi_Session_UI_PLAN.md) · [change](2026-11-12_Multi_Session_UI.md) |
|
||||
| 2026-11-12 | Доработки по итогам обновления ПРОД: `Literal` вместо `Query(enum=)` в профайлере (совместимость с новым FastAPI), фиксация зависимостей, лог сервиса при отказе health-check, версия «до» из `deploy.state`, подсказка в `migrate.py`, документация `--source --no-pull` | [plan](2026-11-12_Prod_Upgrade_Fixes_PLAN.md) · [change](2026-11-12_Prod_Upgrade_Fixes.md) |
|
||||
@@ -22,6 +22,7 @@ Provides aggregated trend data for the entire server. optimized for visualizatio
|
||||
* **7d**: Returns 105-minute intervals (1h 45m).
|
||||
* **30d**: Returns 450-minute intervals (7h 30m).
|
||||
* **Zero-Filling**: Missing data periods are automatically filled with zeros to ensure graph continuity.
|
||||
* **Speed (`total_rx_rate`, `total_tx_rate`)**: for `24h` it is the peak of the summed rates over a point interval (raw `usage_history`). For `7d` and `30d` the source is `stats_hourly`, which keeps only bytes, so the rate is the **average** of an hourly bucket (`bytes * 8 / 1e6 / 3600`, Mbps), summed over clients; per point the maximum of the hourly averages is returned. Short peaks are smoothed out.
|
||||
|
||||
#### Example Response
|
||||
```json
|
||||
@@ -75,6 +76,8 @@ The API automatically selects the aggregation interval based on the requested ra
|
||||
|
||||
*All short-term ranges (≤24h) include automatic **Zero-Filling**.*
|
||||
|
||||
**Speed fields.** For ranges up to 24h `bytes_received_rate_mbps` / `bytes_sent_rate_mbps` are the peak over the point interval (raw samples). The aggregate tables (`stats_5min`, `stats_15min`, `stats_hourly`, `stats_6h`, `stats_daily`) keep only bytes, so for longer ranges (and `resolution` other than `raw`) the fields are the **average speed of the bucket**: `bytes * 8 / 1e6 / bucket seconds` (300, 900, 3600, 21600, 86400). For the current incomplete bucket the duration is `min(bucket length, time since the bucket start)`, at least 1 second. The UI labels such series "RX Mbps (avg)" / "TX Mbps (avg)". If an aggregate table is missing, the API falls back to `usage_history` and returns real speeds.
|
||||
|
||||
#### Examples: Long-Term Aggregated Data
|
||||
|
||||
To explicitly request data from long-term storage tables (skipping raw data), use the `resolution` parameter or specific ranges.
|
||||
@@ -139,6 +142,7 @@ Returns a snapshot of all known clients.
|
||||
Field notes (a user with several simultaneous sessions is one record):
|
||||
- `current_recv_rate_mbps` / `current_sent_rate_mbps`: peak over the last 30 seconds of the **sum of the rates of all sessions** of the user at one tick (not the rate of a single session).
|
||||
- `real_address`: the address of the session with the latest start. `last_bytes_received/sent` (table `clients`): the sum of the current counters of all active sessions. Per-session values are in `GET /sessions`.
|
||||
- `sessions_count` and `sessions`: the active sessions of the user from `active_sessions` (`real_address`, `connected_since` in UTC, `bytes_received`, `bytes_sent`, `received_mb`, `sent_mb`). `0` and `[]` for a disconnected client or when the table is absent. The Clients page uses them for the "×N" badge and the list of devices.
|
||||
- In `GET /stats/<common_name>` the history of every interval has the volume and the rate summed over the user's sessions (rate: `MAX` over the interval of the per-tick sum).
|
||||
|
||||
#### Example Response
|
||||
|
||||
@@ -51,6 +51,8 @@ To support long-term statistics without storing billions of rows, the `TimeSerie
|
||||
| `stats_6h` | **6 Hours** | 00:00, 06:00, 12:00... | 180 Days |
|
||||
| `stats_daily` | **1 Day** | 00:00:00 | 365 Days |
|
||||
|
||||
The aggregate tables hold only `bytes_received` / `bytes_sent`, no speed. For periods over 24 hours the API derives the **average speed** of a bucket from its bytes (`bytes * 8 / 1e6 / bucket seconds`; for the current incomplete bucket the time since its start is used); peaks are available only in `usage_history` (up to 24 hours).
|
||||
|
||||
**Logic**: Every 10s cycle, the calculated `Increment` is added to the sum of *all* relevant overlapping buckets. A single 5MB download contributes immediately to the current 5min, 15min, Hourly, 6h, and Daily counters simultaneously.
|
||||
|
||||
## 3. Data Retention
|
||||
|
||||
@@ -64,7 +64,7 @@ deploy/docker/install.sh --variant b --project ovpmon --http-port 8080 --vpn-por
|
||||
What `install.sh` does:
|
||||
|
||||
1. **Preflight:** docker and compose, running daemon, the other variant is not running, no foreign container with the same names, ports free, free disk space.
|
||||
2. **`.env`** next to the compose files, only if it does not exist: mode 600, random `JWT_SECRET`, initial administrator with a generated 24-character password. An existing `.env` is never overwritten (`--http-port` / `--vpn-port` only set their own keys in it).
|
||||
2. **`.env`** next to the compose files, only if it does not exist: mode 600, random `JWT_SECRET`, initial administrator with a generated 24-character password. An existing `.env` is never overwritten (`--http-port` / `--vpn-port` only set their own keys in it). It also checks `OVPMON_CSP_CONNECT_EXTRA` when set (see [Reference](Reference.md)).
|
||||
3. **Build, start** (`docker compose up -d`), write the state file `.ovpmon-deploy` (variant and project; used by `update.sh`, `backup.sh`, `restore.sh`), wait up to 3 minutes for the health checks.
|
||||
4. **Initial administrator:** when the users table is not empty, `OVPMON_INITIAL_ADMIN_*` are removed from `.env` and the container that reads them is recreated (variant B: `app-api`, variant A: `ovpmon`). If the table cannot be read or is empty, the lines stay in `.env` and a warning says so.
|
||||
5. **Result:** URL, ports, and the administrator login and password. **The password is shown once** and stored nowhere else. `JWT_SECRET` is never printed.
|
||||
|
||||
@@ -9,7 +9,8 @@ Configuration (`.env`), ports and volumes of the container installation. Install
|
||||
| `JWT_SECRET` | yes | none (compose refuses to start) | Signing key of both APIs (`OVPMON_API_SECRET_KEY`). At least 32 characters, no `change-me`/`changeme`: `install.sh`, `update.sh` and the all-in-one container refuse a weak value. Changing it logs every user out. Keep the same value across updates |
|
||||
| `OVPMON_INITIAL_ADMIN_USER`, `OVPMON_INITIAL_ADMIN_PASSWORD` | first start only | empty | Seed for the first user, used only while the users table is empty. Removed by `install.sh` afterwards |
|
||||
| `OVPMON_CORS_ORIGINS` | no | empty (off) | Comma-separated extra origins; the UI is same-origin behind nginx |
|
||||
| `OVPMON_HTTP_PORT` | no | `80` | Host port of the UI |
|
||||
| `OVPMON_HTTP_PORT` | no | `80` | Host port of the UI (variant B: mapped to port 8080 of `ovp-ui`, variant A: to port 80 of `ovp-allinone`) |
|
||||
| `OVPMON_CSP_CONNECT_EXTRA` | no | empty | Extra origins in the `connect-src` of the Content-Security-Policy, for a UI whose `config.json` points to an API on another host: `https://host[:port]` or `http://host[:port]`, separated by spaces (quote the value when there are several). Anything else is refused with a message by `install.sh` / `update.sh` and by the containers at start (the value goes into a response header). Passed to the containers as `OVP_CSP_CONNECT_EXTRA`; apply with `docker compose up -d` (the container is recreated) |
|
||||
| `OVPMON_VPN_PORT` | no | `1194` | Host UDP port of OpenVPN (the container side is always 1194) |
|
||||
|
||||
Variables of the scripts (environment of the shell, not `.env`): `OVPMON_BACKUP_DIR` (backup root, default `./backups`), `OVPMON_BACKUP_IMAGE` (helper image, default `alpine:3`), `OVPMON_HEALTH_TIMEOUT` (seconds, default 180), `OVPMON_MIN_FREE_MB` (docker data, default 2048), `OVPMON_MIN_FREE_BACKUP_MB` (backups, default 1024).
|
||||
@@ -20,7 +21,7 @@ Variables of the scripts (environment of the shell, not `.env`): `OVPMON_BACKUP_
|
||||
|
||||
| Port | Published | Purpose |
|
||||
|---|---|---|
|
||||
| `${OVPMON_HTTP_PORT:-80}/tcp` | yes | UI and reverse proxy to both APIs (plain HTTP) |
|
||||
| `${OVPMON_HTTP_PORT:-80}/tcp` | yes | UI and reverse proxy to both APIs (plain HTTP). Inside the container: `8080` in variant B (`ovp-ui` runs nginx as the unprivileged user `nginx`), `80` in variant A. Custom compose files or a proxy that target port 80 of `ovp-ui` must be changed to 8080 |
|
||||
| `${OVPMON_VPN_PORT:-1194}/udp` | yes | OpenVPN |
|
||||
| `5001` (monitoring API), `8000` (profiler API) | no | variant B: `expose`d on `ovp-net` only; variant A: listen on `127.0.0.1` inside the container |
|
||||
|
||||
@@ -51,4 +52,4 @@ The profiler resolves `easy-rsa/` and `client-config/` relative to its working d
|
||||
|
||||
Processes in `ovp-allinone` (`deploy/allinone/supervisord.conf`, started in this order, all with `autorestart`, logs to stdout/stderr): `gatherer`, `api` (`gunicorn -w 2 -b 127.0.0.1:5001 openvpn_api_v3:app`), `profiler` (`uvicorn` on `127.0.0.1:8000`, no reload), `nginx`. OpenVPN is started by the profiler API on request (direct start inside containers), as in variant B.
|
||||
|
||||
`deploy/allinone/entrypoint.sh` runs before `supervisord`: secret mapping (`JWT_SECRET` → `OVPMON_API_SECRET_KEY` when only the first is set), `/dev/net/tun`, easy-rsa workspace (copied only when the volume does not have it yet), NAT and MSS rules without duplicates, the nginx configuration rendered from `APP_UI/default.conf.template` for `127.0.0.1`, then the **database migration as an explicit step**: the container does not start if it fails. The services then run with `OVPMON_AUTO_MIGRATE=0` (they only verify the schema).
|
||||
`deploy/allinone/entrypoint.sh` runs before `supervisord`: secret mapping (`JWT_SECRET` → `OVPMON_API_SECRET_KEY` when only the first is set), `/dev/net/tun`, easy-rsa workspace (copied only when the volume does not have it yet), NAT and MSS rules without duplicates, the nginx configuration rendered from `APP_UI/default.conf.template` for `127.0.0.1` (port 80, CSP origins from `OVP_CSP_CONNECT_EXTRA`, checked first: an invalid value stops the container), then the **database migration as an explicit step**: the container does not start if it fails. The services then run with `OVPMON_AUTO_MIGRATE=0` (they only verify the schema).
|
||||
@@ -8,6 +8,7 @@ Install: [Containers](README.md). Update and backup: [Operations](Operations.md)
|
||||
|---|---|
|
||||
| `port 80/tcp is already in use` | Another service uses the port. Install with `--http-port 8080` or set `OVPMON_HTTP_PORT` in `.env` (same for `OVPMON_VPN_PORT`) |
|
||||
| `container 'ovp-...' of the OTHER variant is running` | Variants A and B cannot run together. Stop the other stack first |
|
||||
| `OVPMON_CSP_CONNECT_EXTRA ... is invalid` (script) or `check-csp-connect-extra` in the log of a container that stops at start | The value is not a list of origins. Use `https://host[:port]` or `http://host[:port]` separated by spaces (no `;`, quotes, commas, paths, leading space) or leave it empty |
|
||||
| `container 'ovp-ui' ... belongs to compose project 'x'` | A stack of another project uses the fixed names. Use `--project x` or remove that stack |
|
||||
| Health check does not turn healthy | `docker compose ps`, then `docker compose logs --tail 100 <service>` (A: `docker logs ovp-allinone`). The scripts print the last log lines of failing services. The profiler allows 40 s and the all-in-one container 60 s before failures count |
|
||||
| `FATAL: ... newer than this version` / migration "too new" | The database was migrated by a newer release. Do not start the old version on it: update to the newer sources, or restore a matching backup (`update.sh --rollback` or `restore.sh`) |
|
||||
|
||||
@@ -122,3 +122,25 @@ sudo apt install nginx
|
||||
```bash
|
||||
setsebool -P httpd_can_network_connect 1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Security headers and CSP (site written by `install.sh`)
|
||||
|
||||
The site that `install.sh` / `update.sh` write (`deploy/native/nginx/ovpmon.conf.template`, first line has the marker "managed by ovpmon") sends `Strict-Transport-Security`, `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, `Cache-Control: no-store` and a Content-Security-Policy:
|
||||
|
||||
```
|
||||
default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:;
|
||||
connect-src 'self' <extra origins>; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'
|
||||
```
|
||||
|
||||
The headers are declared on the `server` level only: an `add_header` inside a `location` would drop all of them. `style-src 'unsafe-inline'` is needed by Bootstrap and Chart.js.
|
||||
|
||||
The default `connect-src` allows the page origin only. If `config.json` points the UI to an API on another host, add its origin:
|
||||
|
||||
```bash
|
||||
deploy/native/update.sh --csp-connect-extra "https://api.example.com http://10.0.0.5:5001" # several origins: separated by spaces
|
||||
deploy/native/update.sh --csp-connect-extra "" # remove them
|
||||
```
|
||||
|
||||
`install.sh` accepts the same option. The value is kept in `/etc/ovpmon/deploy.state` (`OVPMON_CSP_CONNECT_EXTRA`) and applied again by every update. Only `https://host[:port]` and `http://host[:port]` are accepted (the value ends up in a response header). An existing site without the marker line is not changed by `update.sh`: add the CSP there by hand. The API on the other origin must also allow this UI origin (`OVPMON_CORS_ORIGINS`).
|
||||
@@ -13,7 +13,7 @@ deploy/native/update.sh --no-pull # sources already in p
|
||||
deploy/native/update.sh --rollback # manual rollback to the newest backup
|
||||
```
|
||||
|
||||
Run it from the checkout that holds the new version (the script uses the templates of that checkout). `--prefix` and the HTTPS port come from `/etc/ovpmon/deploy.state`. The update needs access to PyPI for the new virtualenvs.
|
||||
Run it from the checkout that holds the new version (the script uses the templates of that checkout). `--prefix`, the HTTPS port and the extra CSP origins (`OVPMON_CSP_CONNECT_EXTRA`) come from `/etc/ovpmon/deploy.state`; `--csp-connect-extra "https://api.example.com"` changes the origins (`""` removes them) and re-renders the nginx site. A site that is not managed by the scripts (marker line removed) is left untouched. The update needs access to PyPI for the new virtualenvs.
|
||||
|
||||
Each phase is logged separately:
|
||||
|
||||
@@ -102,6 +102,18 @@ How the code is restored: the current (new or half-swapped) code directories are
|
||||
|
||||
`update.sh --rollback` does the same by hand from the newest `COMPLETE` backup after a confirmation, with one difference: PKI and client profiles come from the backup too (one consistent set with the databases), and the current state is saved first to `<time>-pre-restore`. Use it when an update succeeded but the new version misbehaves. Data created after that backup is lost (it is in the `-pre-restore` copy).
|
||||
|
||||
## Updating with `--source ... --no-pull` (install directory is a git checkout)
|
||||
|
||||
When the install directory is a git checkout and the new version is brought in by hand (`--source <checkout> --no-pull`), keep in mind:
|
||||
|
||||
- `--no-pull` skips `git pull`: the sources must already be at the wanted commit. `deploy.state` records the version that was installed by the scripts; the git checkout of the install directory can differ from it (for example after a manual `git pull` or local commits). The "before" version in the update log is taken from `OVPMON_VERSION` in `deploy.state`, then from `<prefix>/VERSION`.
|
||||
- To bring a diverged checkout to the published state: `git fetch origin && git reset --hard origin/main`. This discards local changes of tracked files, including the **live `config.ini`** of both components. Save them first (`cp APP_CORE/config.ini APP_PROFILER/config.ini` to a safe place) and put them back after the reset; the update keeps `config.ini` and writes the shipped one as `config.ini.dist` when it differs.
|
||||
- The update runs the migrations as a separate step; `python migrate.py --check` outside the service environment looks at the default database path, which may not exist (exit code 2 = pending migrations). Load `/etc/ovpmon/env` first or pass `--db PATH` (variables `OVPMON_OPENVPN_MONITOR_DB_PATH` and `OVPMON_PROFILER_DB_PATH`).
|
||||
|
||||
### Dependency versions
|
||||
|
||||
`APP_PROFILER/requirements.txt` pins `fastapi`, `starlette`, `uvicorn` and `pydantic` to the tested set (an unpinned install pulled a newer FastAPI that broke the API); `APP_CORE/requirements.txt` has an upper bound by major version for each package. Update the pins deliberately and run the tests on the new set. To hold back any package without editing the files, give `pip` a constraints file: `PIP_CONSTRAINT=/etc/ovpmon/constraints.txt deploy/native/update.sh ...` (the variable is read by every `pip install` of the scripts, the environment is inherited).
|
||||
|
||||
## Existing installations (adoption)
|
||||
|
||||
A host that was set up by hand (the layout of the old guide: code in `/opt/OpenVPN-Monitoring-Simple`, `/etc/ovpmon/env`, init scripts or units, helper and doas rules) can be updated with `update.sh`: it has no state file, so it is adopted and recorded after the first successful update. Files that these scripts do not manage are **left as they are**: init scripts, units, an nginx site and a doas file that do not carry the marker line `managed by ovpmon deploy/native` and differ from the shipped ones are only reported. The helper is replaced (the new one behaves like the old one without `helper.conf`), `helper.conf` is written when missing, and `OVPMON_RUNTIME`, `OVPMON_OPENVPN_SERVICE` and `OVPMON_OPENVPN_CONFIG` are added to the environment file only when absent. If the install directory is a git checkout (the source is the install directory), `git pull` changes the live files, therefore a rollback is armed from phase 2.
|
||||
|
||||
@@ -100,6 +100,7 @@ Options:
|
||||
| `--node-download` | with `--build-ui`: use a temporary official Node 20 (checksum verified, glibc only) |
|
||||
| `--no-ui` | install a placeholder page on purpose; without any UI source and without this option the install stops |
|
||||
| `--https-port N` | HTTPS port of the web UI (default `8088`) |
|
||||
| `--csp-connect-extra ORIGINS` | extra origins the UI may call (CSP `connect-src`), for an API on another host: `https://host[:port]` or `http://host[:port]` separated by spaces, in quotes; default none (same origin only). Stored in `/etc/ovpmon/deploy.state` as `OVPMON_CSP_CONNECT_EXTRA`; anything else is refused |
|
||||
| `--host-name NAME` | DNS name or IP for the certificate and the CORS origin (default: the detected address of the default route) |
|
||||
| `--admin-user NAME` | login of the first administrator (default `admin`) |
|
||||
| `--force` | continue on an untested OS version |
|
||||
|
||||
@@ -64,6 +64,18 @@ With the unprivileged profiler the API only stages `server.conf`; **the helper c
|
||||
|
||||
OpenRC runs `/sbin/rc-service <unit> <action>`, systemd runs `systemctl <action> <unit>` (fixed argument list, fixed `PATH`). Unknown keys or invalid values make the helper refuse.
|
||||
|
||||
## Deployment state (`/etc/ovpmon/deploy.state`)
|
||||
|
||||
`KEY=VALUE` lines written by `install.sh` and `update.sh`; `update.sh` reads them back.
|
||||
|
||||
| Key | Meaning |
|
||||
|---|---|
|
||||
| `OVPMON_PREFIX` | install directory |
|
||||
| `OVPMON_HTTPS_PORT` | HTTPS port of the nginx site |
|
||||
| `OVPMON_CSP_CONNECT_EXTRA` | extra origins of the CSP `connect-src` in the nginx site (`install.sh` / `update.sh --csp-connect-extra`); empty = same origin only. Validated: `https://host[:port]` or `http://host[:port]` separated by spaces |
|
||||
| `OVPMON_OS`, `OVPMON_VERSION`, `OVPMON_INSTALLED_AT`, `OVPMON_LAST_UPDATE` | information |
|
||||
| `FIREWALL_*` | settings of `firewall.sh`, see [Firewall](Firewall.md) |
|
||||
|
||||
## Security notes
|
||||
|
||||
- Services run as `ovpmon` (no login shell); code and virtualenvs are root-owned and read-only for them. systemd units add `PrivateTmp`, `ProtectHome`, `ProtectSystem=full`, kernel and cgroup protection; `ovpmon-api` and `ovpmon-gatherer` also set `NoNewPrivileges`. `ovpmon-profiler` must **not** (it calls the setuid `doas`), must not use seccomp-based options either (`ProtectKernelTunables`, `ProtectKernelModules`, `RestrictRealtime`, `LockPersonality`, `SystemCallFilter`, ...): for an unprivileged unit systemd then sets NoNewPrivileges implicitly and `doas` fails with "not installed setuid" (check: `grep NoNewPrivs /proc/<main pid>/status` must show 0). It keeps `/etc/openvpn` writable, because the helper runs inside the profiler's mount namespace.
|
||||
|
||||
@@ -58,10 +58,13 @@ This includes:
|
||||
- Add `Logout` button to the sidebar.
|
||||
- Conditionally render Sidebar only if logged in (optional, or just redirect).
|
||||
|
||||
#### [MODIFY] [main.js](../../APP_UI/src/main.js)
|
||||
- Setup `axios` interceptors:
|
||||
#### [MODIFY] [composables/useApi.js](../../APP_UI/src/composables/useApi.js)
|
||||
- `axios` interceptors (there is no global interceptor in `main.js`):
|
||||
- **Request**: Add `Authorization: Bearer <token>`.
|
||||
- **Response**: On `401 Unauthorized`, clear token and redirect to `/login`.
|
||||
- **Response**: On `401 Unauthorized` from the monitoring or profiler API, clear token and redirect to `/login`. The `/api/auth` client does not do this: `401` there means a wrong current password or 2FA code (change-password, change-username), which the form shows as an error.
|
||||
|
||||
#### Token storage (accepted risk)
|
||||
- The JWT is kept in `localStorage`, so a script running on the page (XSS) can read it. Mitigations: no `v-html` with data, CSP `script-src 'self'` and `X-Frame-Options` in the container nginx (`APP_UI/default.conf.template`). `HttpOnly` cookies would need a cookie scheme and CSRF protection in `APP_CORE`; not planned. Open item: `POST /auth/disable-2fa` does not ask for the password or a 2FA code.
|
||||
|
||||
## Backups
|
||||
|
||||
|
||||
+19
-5
@@ -7,20 +7,23 @@ The frontend is a Single Page Application (SPA) built with **Vue 3** and **Vite*
|
||||
- **Build Tool**: Vite
|
||||
- **Styling**: Bootstrap 5 + Custom CSS (`src/assets/main.css`)
|
||||
- **Routing**: Vue Router
|
||||
- **HTTP Client**: Axios
|
||||
- **HTTP Client**: Axios (three instances in `useApi.js`: monitoring API, profiler API, `/api/auth`)
|
||||
- **Checks**: Vitest (`npm test`), ESLint (`npm run lint`)
|
||||
|
||||
## Key Features
|
||||
- **Responsive Design**: Mobile-friendly sidebar and layouts.
|
||||
- **Theme Support**: Built-in Light/Dark mode toggling.
|
||||
- **Theme Support**: Light/Dark mode toggling; the first visit follows the system setting (`prefers-color-scheme`), the choice is saved. The theme is applied before the app is mounted.
|
||||
- **Real-Time Data**: Polls the Monitoring API (`APP_CORE`) for live statistics.
|
||||
- **Authentication**: JWT-based auth flow with support for 2FA.
|
||||
- **Authentication**: JWT-based auth flow with support for 2FA. The token is kept in `localStorage` (accepted risk, see [Security Architecture](../General/Security_Architecture.md)). A `401` from the monitoring or profiler API ends the session and opens `/login`; `401` from `/api/auth/*` (wrong current password or 2FA code) does not: it is shown as an error. Unknown addresses redirect to `/`.
|
||||
- **Confirmations and notices**: destructive actions ask through `ConfirmModal` (each instance has a unique id); results are toasts (`useToast`). The native `confirm()` and SweetAlert2 are not used.
|
||||
- **Charts**: `composables/useTrafficChart.js` (downsampling, labels, theme colors, Chart.js config) is shared by Analytics and the client history window.
|
||||
|
||||
## Pages
|
||||
|
||||
| Route | View | Purpose |
|
||||
|---|---|---|
|
||||
| `/` | `Analytics.vue` | traffic charts |
|
||||
| `/clients`, `/certificates` | `Clients.vue`, `Certificates.vue` | connected clients, issued profiles |
|
||||
| `/clients`, `/certificates` | `Clients.vue`, `Certificates.vue` | connected clients (badge "×N" and a list of sessions when a user is connected from several devices), issued profiles |
|
||||
| `/config/pki`, `/config/vpn` | `PKIConfig.vue`, `VPNConfig.vue` | PKI and server settings |
|
||||
| `/server` | `ServerManagement.vue` | OpenVPN process control |
|
||||
| `/backup` | `BackupRestore.vue` | **Backup and Restore** (MANAGEMENT section): destinations table with an add/edit modal (the form is built from the `fields` of `GET /backup/settings`: text, number, switch, password and multi-line secret fields; a field may carry a warning, for example plain FTP or a disabled certificate check; types with a pinned host key (SFTP) show it, and **Test** opens a confirmation with the fingerprint and a Trust button), backup panel (encryption status, **server name** field with the name actually used, destination checkboxes, progress per destination, history), restore panel (source, package list with the server name and the time in UTC and in the browser's local time, passphrase, red Restore button with a confirmation). It polls `GET /backup/status` every 2 s while a job runs. See [Backup and Restore](../Profiler_Management/Backup_Restore.md) |
|
||||
@@ -33,7 +36,7 @@ Run-time configuration is loaded from `/public/config.json`. This allows the Vue
|
||||
```json
|
||||
{
|
||||
"api_base_url": "/api/v1", // Proxy path to Core Monitoring API
|
||||
"profiles_api_base_url": "/api", // Proxy path to Profiler API
|
||||
"profiles_api_base_url": "/profiles-api", // Proxy path to Profiler API
|
||||
"refresh_interval": 30000 // Poll interval in ms
|
||||
}
|
||||
```
|
||||
@@ -44,3 +47,14 @@ The UI is served by Nginx in production and proxies API requests to:
|
||||
- `/profiles-api/` -> **APP_PROFILER** (FastAPI, Port 8000)
|
||||
|
||||
See [Deployment Guide](../Deployment/README.md) for Nginx configuration details.
|
||||
|
||||
## Web server headers (container image)
|
||||
`APP_UI/default.conf.template` (also used by the all-in-one image) sends `X-Content-Type-Options`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer` and a CSP (`default-src 'self'`, inline styles allowed, `img-src`/`font-src` with `data:`, `connect-src 'self'` plus optional extra origins), compresses text files, serves `/assets/` with `immutable` caching and `index.html`/`config.json` with `no-cache`.
|
||||
|
||||
The CSP is written once (`set $csp "..."` in the `server` block) and sent with `add_header Content-Security-Policy $csp always` in the `server` block and in `location /assets/` (a location with its own `add_header` does not inherit the server ones).
|
||||
|
||||
**API on another origin.** If `config.json` points the UI to another origin, list it in `OVPMON_CSP_CONNECT_EXTRA` (inside the containers `OVP_CSP_CONNECT_EXTRA`): origins `https://host[:port]` or `http://host[:port]` separated by spaces, empty by default (same origin only). The value goes into a response header, so anything but origins is refused (`;`, quotes, commas, paths, a leading space): by the deploy scripts, by the all-in-one entrypoint and by `/docker-entrypoint.d/15-check-csp-connect-extra.sh` of the `app-ui` image (the container stops with a message). The API on the other origin must also allow this UI origin in `OVPMON_CORS_ORIGINS`.
|
||||
|
||||
The `app-ui` image is based on `nginxinc/nginx-unprivileged:alpine`: nginx runs as the user `nginx` (uid 101) and listens on `OVP_UI_PORT` (8080 in the image); docker-compose publishes it as the host port `OVPMON_HTTP_PORT` (default 80). In the all-in-one image the same template listens on 80 (the supervisor runs everything as root, OpenVPN needs it).
|
||||
|
||||
The system-service nginx (`deploy/native/nginx/ovpmon.conf.template`) sends the same CSP (headers are declared on the `server` level only); extra origins are set with `install.sh` / `update.sh --csp-connect-extra`, see [System services](../Deployment/System_Services/README.md).
|
||||
@@ -4,7 +4,7 @@ Web suite for OpenVPN servers: real-time traffic monitoring, history and analyti
|
||||
|
||||
| Component | Dir | Stack | Port |
|
||||
|---|---|---|---|
|
||||
| UI | `APP_UI/` | Vue 3 + Vite, served by Nginx | 80 (containers) / 8088 (system services, HTTPS) |
|
||||
| UI | `APP_UI/` | Vue 3 + Vite, served by Nginx | 80 (containers, host port; 8080 inside `ovp-ui`) / 8088 (system services, HTTPS) |
|
||||
| Monitoring API + data gatherer | `APP_CORE/` | Flask (gunicorn), Python daemon | 5001, internal |
|
||||
| Profiler API | `APP_PROFILER/` | FastAPI (uvicorn) | 8000, internal |
|
||||
|
||||
@@ -23,6 +23,8 @@ Nginx is the only public entry point. More: [Overview](DOCS/General/Overview.md)
|
||||
2. The script prints the URL and the **administrator password once** (no default account exists).
|
||||
3. Follow [First steps](DOCS/Deployment/First_Steps.md): secure the account, initialize the PKI, configure and start the VPN server, create the first client.
|
||||
|
||||
Update notes (2026-11-12): profiler dependencies are pinned (`fastapi`, `starlette`, `uvicorn`, `pydantic`), the health check prints the service log on failure, `update.sh` takes the "before" version from `deploy.state`, `migrate.py` hints at `OVPMON_*_DB_PATH`; `--source --no-pull` and `PIP_CONSTRAINT`: [Operations](DOCS/Deployment/System_Services/Operations.md).
|
||||
|
||||
Optional: NAT, MSS clamping and TTL for the VPN clients on system-service hosts: `deploy/native/firewall.sh --dry-run` ([Firewall](DOCS/Deployment/System_Services/Firewall.md)).
|
||||
|
||||
## Documentation
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
FROM node:20-alpine AS ui-build
|
||||
WORKDIR /app
|
||||
COPY APP_UI/package*.json ./
|
||||
RUN npm install
|
||||
RUN npm ci
|
||||
COPY APP_UI/ ./
|
||||
RUN npm run build
|
||||
|
||||
@@ -47,6 +47,7 @@ COPY APP_PROFILER /app/APP_PROFILER
|
||||
# UI and nginx: the template is rendered at container start (entrypoint.sh)
|
||||
COPY --from=ui-build /app/dist /usr/share/nginx/html
|
||||
COPY APP_UI/default.conf.template /etc/ovpmon/default.conf.template
|
||||
COPY APP_UI/check-csp-connect-extra.sh /usr/local/bin/ovpmon-check-csp.sh
|
||||
RUN rm -f /etc/nginx/http.d/default.conf \
|
||||
&& mkdir -p /run/nginx /var/log/nginx \
|
||||
&& ln -sf /dev/stdout /var/log/nginx/access.log \
|
||||
@@ -56,7 +57,7 @@ COPY deploy/allinone/supervisord.conf /etc/supervisord.conf
|
||||
COPY deploy/allinone/entrypoint.sh /usr/local/bin/ovpmon-entrypoint.sh
|
||||
|
||||
# Mount points of the five data volumes and of the backup packages volume (ovp_backups)
|
||||
RUN chmod +x /usr/local/bin/ovpmon-entrypoint.sh \
|
||||
RUN chmod +x /usr/local/bin/ovpmon-entrypoint.sh /usr/local/bin/ovpmon-check-csp.sh \
|
||||
&& mkdir -p /app/db /app/easy-rsa /app/client-config /app/backups /etc/openvpn /var/log/openvpn
|
||||
|
||||
# Default database locations (the compose file sets the same values)
|
||||
|
||||
@@ -71,11 +71,21 @@ ensure_rule mangle FORWARD -o "$NAT_IFACE" -p tcp --tcp-flags SYN,RST SYN -j TCP
|
||||
ensure_rule mangle FORWARD -i "$NAT_IFACE" -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
|
||||
|
||||
# --- 5. Nginx configuration ---------------------------------------------------------------
|
||||
# The same template as the UI image of variant B; all upstreams are local. Only the four
|
||||
# OVP_* variables are substituted, nginx's own $variables stay intact.
|
||||
# The same template as the UI image of variant B; all upstreams are local. Only the OVP_* variables
|
||||
# are substituted, nginx's own $variables stay intact.
|
||||
# OVP_CSP_CONNECT_EXTRA (compose: OVPMON_CSP_CONNECT_EXTRA): extra connect-src origins of the CSP. It goes into
|
||||
# a response header, so only origins are accepted (APP_UI/check-csp-connect-extra.sh, copied into the image):
|
||||
# anything else could inject another CSP directive.
|
||||
# Empty value: same origin only.
|
||||
OVP_CSP_CONNECT_EXTRA="${OVP_CSP_CONNECT_EXTRA:-}"
|
||||
/usr/local/bin/ovpmon-check-csp.sh || die "invalid OVPMON_CSP_CONNECT_EXTRA (see above)"
|
||||
# one space between origins (the template has the value after 'self' and a space)
|
||||
OVP_CSP_CONNECT_EXTRA=$(printf '%s' "$OVP_CSP_CONNECT_EXTRA" | tr -s ' ')
|
||||
export OVP_CSP_CONNECT_EXTRA
|
||||
export OVP_API_HOST=127.0.0.1 OVP_API_PORT=5001
|
||||
export OVP_PROFILER_HOST=127.0.0.1 OVP_PROFILER_PORT=8000
|
||||
envsubst '${OVP_API_HOST} ${OVP_API_PORT} ${OVP_PROFILER_HOST} ${OVP_PROFILER_PORT}' \
|
||||
export OVP_UI_PORT=80
|
||||
envsubst '${OVP_API_HOST} ${OVP_API_PORT} ${OVP_PROFILER_HOST} ${OVP_PROFILER_PORT} ${OVP_UI_PORT} ${OVP_CSP_CONNECT_EXTRA}' \
|
||||
< /etc/ovpmon/default.conf.template > /etc/nginx/http.d/ovpmon.conf
|
||||
nginx -t || die "generated nginx configuration is invalid (see above)"
|
||||
|
||||
|
||||
@@ -105,6 +105,7 @@ else
|
||||
if [ -n "$ARG_HTTP_PORT" ]; then echo "OVPMON_HTTP_PORT=$ARG_HTTP_PORT"; else echo "# OVPMON_HTTP_PORT=80"; fi
|
||||
if [ -n "$ARG_VPN_PORT" ]; then echo "OVPMON_VPN_PORT=$ARG_VPN_PORT"; else echo "# OVPMON_VPN_PORT=1194"; fi
|
||||
echo "# OVPMON_CORS_ORIGINS="
|
||||
echo "# OVPMON_CSP_CONNECT_EXTRA="
|
||||
} > "$ENV_FILE"
|
||||
)
|
||||
chmod 600 "$ENV_FILE"
|
||||
|
||||
@@ -310,6 +310,47 @@ secret_problem() {
|
||||
return 0
|
||||
}
|
||||
|
||||
# csp_extra_problem VALUE: extra origins for the connect-src directive of the Content-Security-Policy
|
||||
# (OVPMON_CSP_CONNECT_EXTRA in .env). Allowed: empty, or origins https://host[:port] and
|
||||
# http://host[:port] separated by spaces (host: letters, digits, dots, hyphens; no path, quotes, ; or commas).
|
||||
# Anything else would let a value inject its own CSP directive. Prints the reason and returns 1 when the
|
||||
# value is not acceptable. Use it as: if reason=$(csp_extra_problem "$v"); then ...ok...; else ...; fi
|
||||
csp_extra_problem() {
|
||||
local _t _rest _host _port
|
||||
[ -n "$1" ] || return 0
|
||||
case "$1" in
|
||||
*[!A-Za-z0-9.:/\ -]*)
|
||||
printf 'contains characters that are not allowed (only letters, digits, . - : / and spaces; no quotes, ; or commas)'; return 1 ;;
|
||||
" "*|*" ")
|
||||
printf 'starts or ends with a space'; return 1 ;;
|
||||
esac
|
||||
set -f
|
||||
for _t in $1; do
|
||||
case "$_t" in
|
||||
https://*) _rest=${_t#https://} ;;
|
||||
http://*) _rest=${_t#http://} ;;
|
||||
*) set +f; printf "'%s' is not an origin (use https://host[:port] or http://host[:port])" "$_t"; return 1 ;;
|
||||
esac
|
||||
_host=${_rest%%:*}
|
||||
_port=""
|
||||
case "$_rest" in *:*) _port=${_rest#*:} ;; esac
|
||||
case "$_host" in
|
||||
""|*[!A-Za-z0-9.-]*) set +f; printf "'%s' has an invalid host (letters, digits, dots and hyphens; no path)" "$_t"; return 1 ;;
|
||||
esac
|
||||
if [ -n "$_port" ]; then
|
||||
case "$_port" in
|
||||
*[!0-9]*) set +f; printf "'%s' has an invalid port (digits only, no path)" "$_t"; return 1 ;;
|
||||
esac
|
||||
if [ "${#_port}" -gt 5 ] || [ "$_port" -lt 1 ] || [ "$_port" -gt 65535 ]; then
|
||||
set +f; printf "'%s' has a port out of range" "$_t"; return 1
|
||||
fi
|
||||
fi
|
||||
case "$_rest" in *:) set +f; printf "'%s' has an empty port" "$_t"; return 1 ;; esac
|
||||
done
|
||||
set +f
|
||||
return 0
|
||||
}
|
||||
|
||||
check_env_file() {
|
||||
local _reason
|
||||
[ -f "$ENV_FILE" ] || die ".env not found at $ENV_FILE (install.sh creates it)"
|
||||
@@ -317,6 +358,9 @@ check_env_file() {
|
||||
if ! _reason=$(secret_problem "$(env_get JWT_SECRET)"); then
|
||||
die "JWT_SECRET in $ENV_FILE is $_reason: the API refuses to start with a weak signing key. Set a random value of at least 32 characters (for example: openssl rand -hex 32); note that a changed key signs out all users"
|
||||
fi
|
||||
if ! _reason=$(csp_extra_problem "$(env_get OVPMON_CSP_CONNECT_EXTRA)"); then
|
||||
die "OVPMON_CSP_CONNECT_EXTRA in $ENV_FILE is invalid: $_reason. Use origins https://host[:port] or http://host[:port] separated by spaces, or leave it empty"
|
||||
fi
|
||||
if [ -n "$(find "$ENV_FILE" \( -perm -040 -o -perm -004 \) 2>/dev/null)" ]; then
|
||||
warn ".env is readable by other users; fix with: chmod 600 $ENV_FILE"
|
||||
fi
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# Install OpenVPN Monitor & Profiler as system services (no containers): Alpine (OpenRC), Debian, Ubuntu (systemd).
|
||||
#
|
||||
# deploy/native/install.sh [--prefix DIR] [--ui-dist FILE|DIR | --build-ui [--node-download] | --no-ui]
|
||||
# [--https-port N] [--host-name NAME] [--admin-user NAME] [--force]
|
||||
# [--https-port N] [--csp-connect-extra ORIGINS] [--host-name NAME] [--admin-user NAME] [--force]
|
||||
#
|
||||
# --prefix install directory (APP_CORE, APP_PROFILER, venvs). REQUIRED: without the option the script
|
||||
# asks for it (no default is assumed). It must be a new or empty directory, different from
|
||||
@@ -18,6 +18,9 @@
|
||||
# automatically (a warning is printed when it is older than APP_UI); when there is no UI
|
||||
# source at all the install stops
|
||||
# --https-port HTTPS port of the web UI (default 8088)
|
||||
# --csp-connect-extra extra origins the UI may call (CSP connect-src), for an API on another host: origins
|
||||
# https://host[:port] or http://host[:port] separated by spaces, in quotes (default: none, same
|
||||
# origin only). Kept in /etc/ovpmon/deploy.state as OVPMON_CSP_CONNECT_EXTRA
|
||||
# --host-name DNS name or IP of this host: certificate name and CORS origin (default: detected address)
|
||||
# --admin-user login of the initial administrator (default: admin); the password is generated
|
||||
# --force continue on an untested OS version / Debian derivative
|
||||
@@ -41,6 +44,7 @@ UI_BUILD=0
|
||||
UI_NODE_DL=0
|
||||
NO_UI=0
|
||||
HTTPS_PORT=8088
|
||||
CSP_EXTRA=""
|
||||
HOST_NAME=""
|
||||
ADMIN_USER="admin"
|
||||
FORCE=0
|
||||
@@ -54,6 +58,7 @@ while [ $# -gt 0 ]; do
|
||||
--node-download) UI_NODE_DL=1; shift ;;
|
||||
--no-ui) NO_UI=1; shift ;;
|
||||
--https-port) [ $# -ge 2 ] || die "--https-port needs a value"; HTTPS_PORT="$2"; shift 2 ;;
|
||||
--csp-connect-extra) [ $# -ge 2 ] || die "--csp-connect-extra needs a value"; CSP_EXTRA="$2"; shift 2 ;;
|
||||
--host-name) [ $# -ge 2 ] || die "--host-name needs a value"; HOST_NAME="$2"; shift 2 ;;
|
||||
--admin-user) [ $# -ge 2 ] || die "--admin-user needs a value"; ADMIN_USER="$2"; shift 2 ;;
|
||||
--force) FORCE=1; shift ;;
|
||||
@@ -125,6 +130,7 @@ else
|
||||
[ -z "$_problem" ] || die "invalid --prefix '$PREFIX': $_problem"
|
||||
fi
|
||||
valid_port "$HTTPS_PORT" || die "invalid --https-port '$HTTPS_PORT'"
|
||||
if ! _csp_reason=$(csp_extra_problem "$CSP_EXTRA"); then die "invalid --csp-connect-extra '$CSP_EXTRA': $_csp_reason"; fi
|
||||
case "$ADMIN_USER" in
|
||||
""|*[!A-Za-z0-9._-]*) die "invalid --admin-user (letters, digits, . _ - only)" ;;
|
||||
esac
|
||||
@@ -434,7 +440,7 @@ fi
|
||||
# nginx site
|
||||
_tmp="$TMPD/ovpmon.conf"
|
||||
mkdir -p "$NGINX_CONF_DIR"
|
||||
render_nginx "$SRC" "$HTTPS_PORT" "$_tmp"
|
||||
render_nginx "$SRC" "$HTTPS_PORT" "$_tmp" "$CSP_EXTRA"
|
||||
rc=0
|
||||
install_managed "$_tmp" "$NGINX_SITE" 644 "deploy/native/nginx/ovpmon.conf.template" || rc=$?
|
||||
case "$rc" in
|
||||
@@ -497,6 +503,7 @@ fi
|
||||
CURRENT_PHASE="finish"
|
||||
state_set OVPMON_PREFIX "$PREFIX"
|
||||
state_set OVPMON_HTTPS_PORT "$HTTPS_PORT"
|
||||
state_set OVPMON_CSP_CONNECT_EXTRA "$CSP_EXTRA"
|
||||
state_set OVPMON_OS "$OS_ID $OS_VERSION_ID"
|
||||
state_set OVPMON_VERSION "$(cat "$PREFIX/VERSION")"
|
||||
[ -n "$(state_get OVPMON_INSTALLED_AT)" ] || state_set OVPMON_INSTALLED_AT "$(now_iso)"
|
||||
|
||||
+62
-11
@@ -383,6 +383,47 @@ secret_problem() {
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
# csp_extra_problem VALUE: extra origins for the connect-src directive of the Content-Security-Policy
|
||||
# (OVPMON_CSP_CONNECT_EXTRA / --csp-connect-extra). Allowed: empty, or origins https://host[:port] and
|
||||
# http://host[:port] separated by spaces (host: letters, digits, dots, hyphens; no path, quotes, ; or commas).
|
||||
# Anything else would let a value inject its own CSP directive. Prints the reason and returns 1 when the
|
||||
# value is not acceptable. Use it as: if reason=$(csp_extra_problem "$v"); then ...ok...; else ...; fi
|
||||
csp_extra_problem() {
|
||||
local _t _rest _host _port
|
||||
[ -n "$1" ] || return 0
|
||||
case "$1" in
|
||||
*[!A-Za-z0-9.:/\ -]*)
|
||||
printf 'contains characters that are not allowed (only letters, digits, . - : / and spaces; no quotes, ; or commas)'; return 1 ;;
|
||||
" "*|*" ")
|
||||
printf 'starts or ends with a space'; return 1 ;;
|
||||
esac
|
||||
set -f
|
||||
for _t in $1; do
|
||||
case "$_t" in
|
||||
https://*) _rest=${_t#https://} ;;
|
||||
http://*) _rest=${_t#http://} ;;
|
||||
*) set +f; printf "'%s' is not an origin (use https://host[:port] or http://host[:port])" "$_t"; return 1 ;;
|
||||
esac
|
||||
_host=${_rest%%:*}
|
||||
_port=""
|
||||
case "$_rest" in *:*) _port=${_rest#*:} ;; esac
|
||||
case "$_host" in
|
||||
""|*[!A-Za-z0-9.-]*) set +f; printf "'%s' has an invalid host (letters, digits, dots and hyphens; no path)" "$_t"; return 1 ;;
|
||||
esac
|
||||
if [ -n "$_port" ]; then
|
||||
case "$_port" in
|
||||
*[!0-9]*) set +f; printf "'%s' has an invalid port (digits only, no path)" "$_t"; return 1 ;;
|
||||
esac
|
||||
if [ "${#_port}" -gt 5 ] || [ "$_port" -lt 1 ] || [ "$_port" -gt 65535 ]; then
|
||||
set +f; printf "'%s' has a port out of range" "$_t"; return 1
|
||||
fi
|
||||
fi
|
||||
case "$_rest" in *:) set +f; printf "'%s' has an empty port" "$_t"; return 1 ;; esac
|
||||
done
|
||||
set +f
|
||||
return 0
|
||||
}
|
||||
state_get() { kv_get "$STATE_FILE" "$1"; }
|
||||
state_set() { kv_set "$STATE_FILE" "$1" "$2" 644; }
|
||||
|
||||
@@ -510,13 +551,20 @@ render_unit() {
|
||||
sed -e "s#$DEFAULT_PREFIX#$3#g" "$src" > "$4"
|
||||
}
|
||||
|
||||
# render_nginx SRC_DIR HTTPS_PORT OUT
|
||||
# render_nginx SRC_DIR HTTPS_PORT OUT [CSP_CONNECT_EXTRA]
|
||||
# CSP_CONNECT_EXTRA: validated origins for connect-src (see csp_extra_problem); empty = same origin only.
|
||||
# The template has no space before @CSP_CONNECT_EXTRA@: it is filled in with a leading space or with nothing.
|
||||
render_nginx() {
|
||||
local src
|
||||
local src csp reason
|
||||
src="$1/deploy/native/nginx/ovpmon.conf.template"
|
||||
[ -f "$src" ] || die "nginx template not found: $src"
|
||||
sed -e "s#@HTTPS_PORT@#$2#g" -e "s#@WEB_ROOT@#$WEB_ROOT#g" \
|
||||
-e "s#@TLS_CRT@#$TLS_DIR/ovpmon.crt#g" -e "s#@TLS_KEY@#$TLS_DIR/ovpmon.key#g" "$1/deploy/native/nginx/ovpmon.conf.template" > "$3"
|
||||
if ! reason=$(csp_extra_problem "${4:-}"); then
|
||||
die "invalid CSP connect-src origins '${4:-}': $reason"
|
||||
fi
|
||||
csp=""
|
||||
[ -z "${4:-}" ] || csp=" $(printf '%s' "$4" | tr -s ' ')"
|
||||
sed -e "s#@HTTPS_PORT@#$2#g" -e "s#@WEB_ROOT@#$WEB_ROOT#g" -e "s#@CSP_CONNECT_EXTRA@#$csp#g" \
|
||||
-e "s#@TLS_CRT@#$TLS_DIR/ovpmon.crt#g" -e "s#@TLS_KEY@#$TLS_DIR/ovpmon.key#g" "$src" > "$3"
|
||||
}
|
||||
|
||||
# helper_conf_text PREFIX: content of /etc/ovpmon/helper.conf for this OS
|
||||
@@ -935,10 +983,12 @@ nginx_apply() { # test the configuration, reload or start nginx
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
http_code() { curl -sk -o /dev/null -w '%{http_code}' --max-time 5 "$@" 2>/dev/null || true; }
|
||||
|
||||
# wait_http LABEL URL REGEX: waits until the HTTP status matches REGEX (e.g. '200' or '401|403')
|
||||
# wait_http LABEL URL REGEX [SERVICE...]: waits until the HTTP status matches REGEX (e.g. '200' or '401|403').
|
||||
# On failure the log of the given services is shown (to find the reason)
|
||||
wait_http() {
|
||||
local label url re w code
|
||||
local label url re w code s
|
||||
label="$1"; url="$2"; re="$3"
|
||||
shift 3 || true
|
||||
w=0
|
||||
while :; do
|
||||
code=$(http_code "$url")
|
||||
@@ -948,6 +998,7 @@ wait_http() {
|
||||
fi
|
||||
if [ "$w" -ge "$HEALTH_TIMEOUT" ]; then
|
||||
log " $label: no good answer after ${HEALTH_TIMEOUT}s (last HTTP status '$code', wanted $re): $url" >&2
|
||||
for s in "$@"; do show_service_log "$s"; done
|
||||
return 1
|
||||
fi
|
||||
sleep 2
|
||||
@@ -964,12 +1015,12 @@ health_check() {
|
||||
if svc_active "$s"; then log " $s: $(svc_state_word "$s")"; else log " $s: NOT running" >&2; show_service_log "$s"; bad=1; fi
|
||||
done
|
||||
[ "$bad" = 0 ] || return 1
|
||||
wait_http "monitoring API" "http://127.0.0.1:5001/" '[1-5][0-9][0-9]' || bad=1
|
||||
wait_http "profiler API" "http://127.0.0.1:8000/" '200' || bad=1
|
||||
wait_http "monitoring API" "http://127.0.0.1:5001/" '[1-5][0-9][0-9]' ovpmon-api || bad=1
|
||||
wait_http "profiler API" "http://127.0.0.1:8000/" '200' ovpmon-profiler || bad=1
|
||||
if [ -n "${1:-}" ]; then
|
||||
wait_http "UI (nginx)" "https://127.0.0.1:$1/" '200' || bad=1
|
||||
wait_http "monitoring API through nginx" "https://127.0.0.1:$1/api/v1/user/me" '401|403' || bad=1
|
||||
wait_http "profiler API through nginx" "https://127.0.0.1:$1/profiles-api/config" '401|403' || bad=1
|
||||
wait_http "UI (nginx)" "https://127.0.0.1:$1/" '200' $SERVICES || bad=1
|
||||
wait_http "monitoring API through nginx" "https://127.0.0.1:$1/api/v1/user/me" '401|403' $SERVICES || bad=1
|
||||
wait_http "profiler API through nginx" "https://127.0.0.1:$1/profiles-api/config" '401|403' $SERVICES || bad=1
|
||||
fi
|
||||
[ "$bad" = 0 ] || return 1
|
||||
log "all health checks passed"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# managed by ovpmon deploy/native (install.sh / update.sh replace this file only while this marker line is present)
|
||||
#
|
||||
# HTTPS site of OpenVPN Monitor & Profiler. Rendered by install.sh / update.sh: they fill in the HTTPS port
|
||||
# (default 8088), the UI directory (/var/www/ovpmon) and the certificate and key paths (/etc/ovpmon/tls/ovpmon.crt
|
||||
# (default 8088), the extra CSP connect-src origins (default none), the UI directory (/var/www/ovpmon) and the certificate and key paths (/etc/ovpmon/tls/ovpmon.crt
|
||||
# and .key: self-signed by install.sh; replace them with a real certificate under the same names, or edit this
|
||||
# file and remove the marker line above so that updates leave it alone).
|
||||
# Installed to the nginx include directory (Alpine /etc/nginx/http.d, Debian/Ubuntu /etc/nginx/conf.d),
|
||||
@@ -32,6 +32,11 @@ server {
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "no-referrer" always;
|
||||
add_header Cache-Control "no-store" always;
|
||||
# CSP: the bundle is served from this origin only; style-src 'unsafe-inline' is needed by Bootstrap and Chart.js
|
||||
# (inline style attributes). connect-src: same origin plus the optional origins of another API host
|
||||
# (install.sh / update.sh --csp-connect-extra, state OVPMON_CSP_CONNECT_EXTRA; the value is filled in
|
||||
# with its own leading space, so there is none before the placeholder). Same policy as APP_UI/default.conf.template.
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'@CSP_CONNECT_EXTRA@; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
|
||||
gzip on;
|
||||
gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;
|
||||
|
||||
+20
-3
@@ -2,7 +2,7 @@
|
||||
# Update OpenVPN Monitor & Profiler (system services) without touching the data.
|
||||
#
|
||||
# deploy/native/update.sh [--prefix DIR] [--ui-dist FILE|DIR | --build-ui [--node-download]] [--source DIR]
|
||||
# [--no-pull] [--yes] [--rollback]
|
||||
# [--csp-connect-extra ORIGINS] [--no-pull] [--yes] [--rollback]
|
||||
#
|
||||
# --prefix install directory (default: from /etc/ovpmon/deploy.state, else /opt/OpenVPN-Monitoring-Simple)
|
||||
# --ui-dist UI tarball from build-ui.sh, or a directory with index.html: always installed (highest priority)
|
||||
@@ -12,6 +12,9 @@
|
||||
# Without these the committed build deploy/ui-dist of the source is installed automatically when
|
||||
# it differs from the installed UI (<web root>/.ui-source-hash); no UI source: the UI stays
|
||||
# --source checkout with the new version (default: the repository this script is in)
|
||||
# --csp-connect-extra extra origins the UI may call (CSP connect-src): https://host[:port] or http://host[:port]
|
||||
# separated by spaces, in quotes; "" removes them. Without the option the value kept in
|
||||
# /etc/ovpmon/deploy.state (OVPMON_CSP_CONNECT_EXTRA) is applied
|
||||
# --no-pull no "git pull --ff-only" of the source checkout (offline hosts, sources already in place)
|
||||
# --yes no confirmation questions
|
||||
# --rollback restore code, databases, configuration, PKI and client profiles from the newest backup
|
||||
@@ -51,6 +54,8 @@ STAMP=$(stamp)
|
||||
RESTORE_STAMP="$STAMP"
|
||||
STAGING=""
|
||||
HTTPS_PORT=""
|
||||
CSP_EXTRA=""
|
||||
CSP_EXTRA_SET=0
|
||||
OLD_VERSION="unknown"
|
||||
NEW_VERSION="unknown"
|
||||
UI_STAGED=0
|
||||
@@ -217,6 +222,7 @@ main() {
|
||||
--ui-dist) [ $# -ge 2 ] || die "--ui-dist needs a value"; UI_DIST="$2"; shift 2 ;;
|
||||
--build-ui) UI_BUILD=1; shift ;;
|
||||
--node-download) UI_NODE_DL=1; shift ;;
|
||||
--csp-connect-extra) [ $# -ge 2 ] || die "--csp-connect-extra needs a value"; CSP_EXTRA="$2"; CSP_EXTRA_SET=1; shift 2 ;;
|
||||
--source) [ $# -ge 2 ] || die "--source needs a value"; SOURCE="$2"; shift 2 ;;
|
||||
--no-pull) NO_PULL=1; shift ;;
|
||||
--yes|-y) ASSUME_YES=1; shift ;;
|
||||
@@ -243,6 +249,7 @@ main() {
|
||||
valid_prefix "$PREFIX" || die "invalid install directory '$PREFIX'"
|
||||
HTTPS_PORT=$(state_get OVPMON_HTTPS_PORT)
|
||||
[ -n "$HTTPS_PORT" ] || HTTPS_PORT=$(detect_https_port || true)
|
||||
if [ "$CSP_EXTRA_SET" = 0 ]; then CSP_EXTRA=$(state_get OVPMON_CSP_CONNECT_EXTRA); fi
|
||||
SOURCE="${SOURCE:-$ROOT_DIR}"
|
||||
case "$UI_DIST" in ""|/*) ;; *) UI_DIST="$PWD/$UI_DIST" ;; esac
|
||||
|
||||
@@ -252,6 +259,11 @@ main() {
|
||||
return 0
|
||||
fi
|
||||
|
||||
if ! _csp_reason=$(csp_extra_problem "$CSP_EXTRA"); then
|
||||
if [ "$CSP_EXTRA_SET" = 1 ]; then _csp_src="--csp-connect-extra"; else _csp_src="OVPMON_CSP_CONNECT_EXTRA in $STATE_FILE"; fi
|
||||
die "invalid CSP connect-src origins '$CSP_EXTRA' ($_csp_src): $_csp_reason"
|
||||
fi
|
||||
|
||||
# ----- Phase 0 -------------------------------------------------------------------------
|
||||
CURRENT_PHASE="0 preflight"
|
||||
phase 0 "preflight"
|
||||
@@ -267,7 +279,11 @@ main() {
|
||||
else
|
||||
warn "no state file ($STATE_FILE): this installation was not made by install.sh; it is adopted and recorded after a successful update. Files that these scripts do not manage (init scripts, nginx site, doas file) are left as they are"
|
||||
fi
|
||||
OLD_VERSION=$(cat "$PREFIX/VERSION" 2>/dev/null || echo "unknown")
|
||||
# The version "before": deploy.state first (VERSION in a git-based install directory may already be the new one)
|
||||
OLD_VERSION=""
|
||||
[ ! -f "$STATE_FILE" ] || OLD_VERSION=$(state_get OVPMON_VERSION 2>/dev/null || true)
|
||||
[ -n "$OLD_VERSION" ] || OLD_VERSION=$(cat "$PREFIX/VERSION" 2>/dev/null || true)
|
||||
[ -n "$OLD_VERSION" ] || OLD_VERSION="unknown"
|
||||
|
||||
for _f in APP_CORE/openvpn_api_v3.py APP_CORE/openvpn_gatherer_v3.py APP_CORE/migrate.py APP_CORE/requirements.txt \
|
||||
APP_PROFILER/main.py APP_PROFILER/migrate.py APP_PROFILER/requirements.txt \
|
||||
@@ -480,7 +496,7 @@ main() {
|
||||
[ -d /etc/openvpn/scripts ] || ensure_dir /etc/openvpn/scripts root:root 755
|
||||
# nginx site (only when it is ours and the port is known)
|
||||
if [ -n "$HTTPS_PORT" ]; then
|
||||
render_nginx "$SOURCE" "$HTTPS_PORT" "$TMPD/ovpmon.conf"
|
||||
render_nginx "$SOURCE" "$HTTPS_PORT" "$TMPD/ovpmon.conf" "$CSP_EXTRA"
|
||||
rc=0; install_managed "$TMPD/ovpmon.conf" "$NGINX_SITE" 644 "deploy/native/nginx/ovpmon.conf.template" || rc=$?
|
||||
report "$rc" "$NGINX_SITE"
|
||||
if [ "$rc" = 0 ]; then
|
||||
@@ -510,6 +526,7 @@ main() {
|
||||
rm -rf "$WEB_ROOT.old"
|
||||
state_set OVPMON_PREFIX "$PREFIX"
|
||||
[ -z "$HTTPS_PORT" ] || state_set OVPMON_HTTPS_PORT "$HTTPS_PORT"
|
||||
state_set OVPMON_CSP_CONNECT_EXTRA "$CSP_EXTRA"
|
||||
state_set OVPMON_OS "$OS_ID $OS_VERSION_ID"
|
||||
state_set OVPMON_VERSION "$NEW_VERSION"
|
||||
[ -n "$(state_get OVPMON_INSTALLED_AT)" ] || state_set OVPMON_INSTALLED_AT "adopted $(now_iso)"
|
||||
|
||||
@@ -1 +1 @@
|
||||
796072800fd2abd0a674c02ef1c626b796e587b263818d13f1159561c7a7d724
|
||||
0dde6861a570886200b2f34cf375e07801fcd229eac29b12db2666723be9e97b
|
||||
@@ -1 +0,0 @@
|
||||
import{G as $,H as N,r as S,I as ae,o as ne,F as ue,a as j,c as x,d,A as V,g as z,J as K,x as Q,t as de,w as B,q as U,m as q,C as ee,j as ce,k}from"./index-BsVv6gaD.js";import{S as O}from"./vendor-ui-jlFFG6nm.js";import{a as te,_ as re}from"./ConfirmModal-CzamKe9d.js";import"./vendor-charts-Bcjh2pZL.js";var T=function(){return T=Object.assign||function(c){for(var f,u=1,h=arguments.length;u<h;u++){f=arguments[u];for(var m in f)Object.prototype.hasOwnProperty.call(f,m)&&(c[m]=f[m])}return c},T.apply(this,arguments)};var D;(function(s){var c=(function(){function a(e,t,r,n){if(this.version=e,this.errorCorrectionLevel=t,this.modules=[],this.isFunction=[],e<a.MIN_VERSION||e>a.MAX_VERSION)throw new RangeError("Version value out of range");if(n<-1||n>7)throw new RangeError("Mask value out of range");this.size=e*4+17;for(var o=[],i=0;i<this.size;i++)o.push(!1);for(var i=0;i<this.size;i++)this.modules.push(o.slice()),this.isFunction.push(o.slice());this.drawFunctionPatterns();var v=this.addEccAndInterleave(r);if(this.drawCodewords(v),n==-1)for(var p=1e9,i=0;i<8;i++){this.applyMask(i),this.drawFormatBits(i);var M=this.getPenaltyScore();M<p&&(n=i,p=M),this.applyMask(i)}h(0<=n&&n<=7),this.mask=n,this.applyMask(n),this.drawFormatBits(n),this.isFunction=[]}return a.encodeText=function(e,t){var r=s.QrSegment.makeSegments(e);return a.encodeSegments(r,t)},a.encodeBinary=function(e,t){var r=s.QrSegment.makeBytes(e);return a.encodeSegments([r],t)},a.encodeSegments=function(e,t,r,n,o,i){if(r===void 0&&(r=1),n===void 0&&(n=40),o===void 0&&(o=-1),i===void 0&&(i=!0),!(a.MIN_VERSION<=r&&r<=n&&n<=a.MAX_VERSION)||o<-1||o>7)throw new RangeError("Invalid value");var v,p;for(v=r;;v++){var M=a.getNumDataCodewords(v,t)*8,w=m.getTotalBits(e,v);if(w<=M){p=w;break}if(v>=n)throw new RangeError("Data too long")}for(var C=0,A=[a.Ecc.MEDIUM,a.Ecc.QUARTILE,a.Ecc.HIGH];C<A.length;C++){var y=A[C];i&&p<=a.getNumDataCodewords(v,y)*8&&(t=y)}for(var b=[],_=0,R=e;_<R.length;_++){var P=R[_];f(P.mode.modeBits,4,b),f(P.numChars,P.mode.numCharCountBits(v),b);for(var F=0,g=P.getData();F<g.length;F++){var l=g[F];b.push(l)}}h(b.length==p);var E=a.getNumDataCodewords(v,t)*8;h(b.length<=E),f(0,Math.min(4,E-b.length),b),f(0,(8-b.length%8)%8,b),h(b.length%8==0);for(var I=236;b.length<E;I^=253)f(I,8,b);for(var L=[];L.length*8<b.length;)L.push(0);return b.forEach(function(Y,G){return L[G>>>3]|=Y<<7-(G&7)}),new a(v,t,L,o)},a.prototype.getModule=function(e,t){return 0<=e&&e<this.size&&0<=t&&t<this.size&&this.modules[t][e]},a.prototype.getModules=function(){return this.modules},a.prototype.drawFunctionPatterns=function(){for(var e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0),this.setFunctionModule(e,6,e%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);for(var t=this.getAlignmentPatternPositions(),r=t.length,e=0;e<r;e++)for(var n=0;n<r;n++)e==0&&n==0||e==0&&n==r-1||e==r-1&&n==0||this.drawAlignmentPattern(t[e],t[n]);this.drawFormatBits(0),this.drawVersion()},a.prototype.drawFormatBits=function(e){for(var t=this.errorCorrectionLevel.formatBits<<3|e,r=t,n=0;n<10;n++)r=r<<1^(r>>>9)*1335;var o=(t<<10|r)^21522;h(o>>>15==0);for(var n=0;n<=5;n++)this.setFunctionModule(8,n,u(o,n));this.setFunctionModule(8,7,u(o,6)),this.setFunctionModule(8,8,u(o,7)),this.setFunctionModule(7,8,u(o,8));for(var n=9;n<15;n++)this.setFunctionModule(14-n,8,u(o,n));for(var n=0;n<8;n++)this.setFunctionModule(this.size-1-n,8,u(o,n));for(var n=8;n<15;n++)this.setFunctionModule(8,this.size-15+n,u(o,n));this.setFunctionModule(8,this.size-8,!0)},a.prototype.drawVersion=function(){if(!(this.version<7)){for(var e=this.version,t=0;t<12;t++)e=e<<1^(e>>>11)*7973;var r=this.version<<12|e;h(r>>>18==0);for(var t=0;t<18;t++){var n=u(r,t),o=this.size-11+t%3,i=Math.floor(t/3);this.setFunctionModule(o,i,n),this.setFunctionModule(i,o,n)}}},a.prototype.drawFinderPattern=function(e,t){for(var r=-4;r<=4;r++)for(var n=-4;n<=4;n++){var o=Math.max(Math.abs(n),Math.abs(r)),i=e+n,v=t+r;0<=i&&i<this.size&&0<=v&&v<this.size&&this.setFunctionModule(i,v,o!=2&&o!=4)}},a.prototype.drawAlignmentPattern=function(e,t){for(var r=-2;r<=2;r++)for(var n=-2;n<=2;n++)this.setFunctionModule(e+n,t+r,Math.max(Math.abs(n),Math.abs(r))!=1)},a.prototype.setFunctionModule=function(e,t,r){this.modules[t][e]=r,this.isFunction[t][e]=!0},a.prototype.addEccAndInterleave=function(e){var t=this.version,r=this.errorCorrectionLevel;if(e.length!=a.getNumDataCodewords(t,r))throw new RangeError("Invalid argument");for(var n=a.NUM_ERROR_CORRECTION_BLOCKS[r.ordinal][t],o=a.ECC_CODEWORDS_PER_BLOCK[r.ordinal][t],i=Math.floor(a.getNumRawDataModules(t)/8),v=n-i%n,p=Math.floor(i/n),M=[],w=a.reedSolomonComputeDivisor(o),C=0,A=0;C<n;C++){var y=e.slice(A,A+p-o+(C<v?0:1));A+=y.length;var b=a.reedSolomonComputeRemainder(y,w);C<v&&y.push(0),M.push(y.concat(b))}for(var _=[],R=function(P){M.forEach(function(F,g){(P!=p-o||g>=v)&&_.push(F[P])})},C=0;C<M[0].length;C++)R(C);return h(_.length==i),_},a.prototype.dLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{G as $,H as N,r as S,I as te,o as re,F as ie,a as J,d as x,e as u,q as V,g as T,J as Y,m as D,t as le,w as U,x as O,A as q,z as j,j as de,C as ue,k as I}from"./index-CH6sppUl.js";import{a as ce,_ as ee}from"./ConfirmModal-XwuF5iM0.js";import"./vendor-ui-Dumif2LN.js";var z=function(){return z=Object.assign||function(h){for(var c,l=1,f=arguments.length;l<f;l++){c=arguments[l];for(var p in c)Object.prototype.hasOwnProperty.call(c,p)&&(h[p]=c[p])}return h},z.apply(this,arguments)};var B;(function(s){var h=(function(){function a(e,t,r,n){if(this.version=e,this.errorCorrectionLevel=t,this.modules=[],this.isFunction=[],e<a.MIN_VERSION||e>a.MAX_VERSION)throw new RangeError("Version value out of range");if(n<-1||n>7)throw new RangeError("Mask value out of range");this.size=e*4+17;for(var i=[],o=0;o<this.size;o++)i.push(!1);for(var o=0;o<this.size;o++)this.modules.push(i.slice()),this.isFunction.push(i.slice());this.drawFunctionPatterns();var v=this.addEccAndInterleave(r);if(this.drawCodewords(v),n==-1)for(var C=1e9,o=0;o<8;o++){this.applyMask(o),this.drawFormatBits(o);var y=this.getPenaltyScore();y<C&&(n=o,C=y),this.applyMask(o)}f(0<=n&&n<=7),this.mask=n,this.applyMask(n),this.drawFormatBits(n),this.isFunction=[]}return a.encodeText=function(e,t){var r=s.QrSegment.makeSegments(e);return a.encodeSegments(r,t)},a.encodeBinary=function(e,t){var r=s.QrSegment.makeBytes(e);return a.encodeSegments([r],t)},a.encodeSegments=function(e,t,r,n,i,o){if(r===void 0&&(r=1),n===void 0&&(n=40),i===void 0&&(i=-1),o===void 0&&(o=!0),!(a.MIN_VERSION<=r&&r<=n&&n<=a.MAX_VERSION)||i<-1||i>7)throw new RangeError("Invalid value");var v,C;for(v=r;;v++){var y=a.getNumDataCodewords(v,t)*8,E=p.getTotalBits(e,v);if(E<=y){C=E;break}if(v>=n)throw new RangeError("Data too long")}for(var m=0,A=[a.Ecc.MEDIUM,a.Ecc.QUARTILE,a.Ecc.HIGH];m<A.length;m++){var g=A[m];o&&C<=a.getNumDataCodewords(v,g)*8&&(t=g)}for(var b=[],M=0,R=e;M<R.length;M++){var P=R[M];c(P.mode.modeBits,4,b),c(P.numChars,P.mode.numCharCountBits(v),b);for(var k=0,w=P.getData();k<w.length;k++){var d=w[k];b.push(d)}}f(b.length==C);var _=a.getNumDataCodewords(v,t)*8;f(b.length<=_),c(0,Math.min(4,_-b.length),b),c(0,(8-b.length%8)%8,b),f(b.length%8==0);for(var F=236;b.length<_;F^=253)c(F,8,b);for(var L=[];L.length*8<b.length;)L.push(0);return b.forEach(function(G,H){return L[H>>>3]|=G<<7-(H&7)}),new a(v,t,L,i)},a.prototype.getModule=function(e,t){return 0<=e&&e<this.size&&0<=t&&t<this.size&&this.modules[t][e]},a.prototype.getModules=function(){return this.modules},a.prototype.drawFunctionPatterns=function(){for(var e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0),this.setFunctionModule(e,6,e%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);for(var t=this.getAlignmentPatternPositions(),r=t.length,e=0;e<r;e++)for(var n=0;n<r;n++)e==0&&n==0||e==0&&n==r-1||e==r-1&&n==0||this.drawAlignmentPattern(t[e],t[n]);this.drawFormatBits(0),this.drawVersion()},a.prototype.drawFormatBits=function(e){for(var t=this.errorCorrectionLevel.formatBits<<3|e,r=t,n=0;n<10;n++)r=r<<1^(r>>>9)*1335;var i=(t<<10|r)^21522;f(i>>>15==0);for(var n=0;n<=5;n++)this.setFunctionModule(8,n,l(i,n));this.setFunctionModule(8,7,l(i,6)),this.setFunctionModule(8,8,l(i,7)),this.setFunctionModule(7,8,l(i,8));for(var n=9;n<15;n++)this.setFunctionModule(14-n,8,l(i,n));for(var n=0;n<8;n++)this.setFunctionModule(this.size-1-n,8,l(i,n));for(var n=8;n<15;n++)this.setFunctionModule(8,this.size-15+n,l(i,n));this.setFunctionModule(8,this.size-8,!0)},a.prototype.drawVersion=function(){if(!(this.version<7)){for(var e=this.version,t=0;t<12;t++)e=e<<1^(e>>>11)*7973;var r=this.version<<12|e;f(r>>>18==0);for(var t=0;t<18;t++){var n=l(r,t),i=this.size-11+t%3,o=Math.floor(t/3);this.setFunctionModule(i,o,n),this.setFunctionModule(o,i,n)}}},a.prototype.drawFinderPattern=function(e,t){for(var r=-4;r<=4;r++)for(var n=-4;n<=4;n++){var i=Math.max(Math.abs(n),Math.abs(r)),o=e+n,v=t+r;0<=o&&o<this.size&&0<=v&&v<this.size&&this.setFunctionModule(o,v,i!=2&&i!=4)}},a.prototype.drawAlignmentPattern=function(e,t){for(var r=-2;r<=2;r++)for(var n=-2;n<=2;n++)this.setFunctionModule(e+n,t+r,Math.max(Math.abs(n),Math.abs(r))!=1)},a.prototype.setFunctionModule=function(e,t,r){this.modules[t][e]=r,this.isFunction[t][e]=!0},a.prototype.addEccAndInterleave=function(e){var t=this.version,r=this.errorCorrectionLevel;if(e.length!=a.getNumDataCodewords(t,r))throw new RangeError("Invalid argument");for(var n=a.NUM_ERROR_CORRECTION_BLOCKS[r.ordinal][t],i=a.ECC_CODEWORDS_PER_BLOCK[r.ordinal][t],o=Math.floor(a.getNumRawDataModules(t)/8),v=n-o%n,C=Math.floor(o/n),y=[],E=a.reedSolomonComputeDivisor(i),m=0,A=0;m<n;m++){var g=e.slice(A,A+C-i+(m<v?0:1));A+=g.length;var b=a.reedSolomonComputeRemainder(g,E);m<v&&g.push(0),y.push(g.concat(b))}for(var M=[],R=function(P){y.forEach(function(k,w){(P!=C-i||w>=v)&&M.push(k[P])})},m=0;m<y[0].length;m++)R(m);return f(M.length==o),M},a.prototype.drawCodewords=function(e){if(e.lLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{r as c,a as T,u as z,o as B,b as E,c as I,d as n,e as t,t as o,f as R,g as r,w as A,v as V,h as F,F as b,i as D,j as P,k as i,n as H}from"./index-CH6sppUl.js";import{u as X,g as G,C as W,a as q}from"./useTrafficChart-DniISzMl.js";import{u as J}from"./useFormatters-CKGG-YVI.js";import{C as K}from"./vendor-charts-Bcjh2pZL.js";const Q={class:"kpi-grid mb-4"},Y={class:"stat-item"},Z={class:"stat-content"},$={class:"stat-item"},tt={class:"stat-content"},et={class:"stat-item"},st={class:"stat-content"},at={class:"card mb-4"},lt={class:"card-header d-flex justify-content-between align-items-center flex-wrap"},ot={class:"chart-header-controls"},nt={class:"d-flex align-items-center"},it={class:"toggle-wrapper me-2"},rt={class:"toggle-switch"},dt={class:"card-body"},ct={class:"chart-container"},ut={class:"row"},ft={class:"col-lg-7"},mt={class:"card"},vt={class:"card-body p-0"},pt={class:"table-responsive"},_t={class:"table"},ht={key:0},gt={key:1},yt={class:"user-select-all fw-bold",style:{color:"var(--text-heading)"}},xt={class:"font-monospace text-muted"},bt={class:"d-flex align-items-center"},Ct={class:"progress flex-grow-1",style:{height:"6px"}},kt={class:"ms-2 small text-muted w-25 text-end"},wt={class:"col-lg-5"},St={class:"card mb-4"},Tt={class:"card-body p-3",style:{"min-height":"120px","max-height":"200px","overflow-y":"auto"}},Rt={key:0,class:"text-muted text-center py-3 mb-0"},At={key:1,class:"text-muted text-center py-3 mb-0"},Dt={key:2,class:"list-group list-group-flush"},Nt={class:"fw-bold small"},Lt={class:"text-muted",style:{"font-size":"0.75rem"}},Ot={class:"badge status-warning text-dark"},Ut={class:"card"},Mt={class:"card-body d-flex align-items-center justify-content-around p-4",style:{"min-height":"200px"}},jt={class:"pie-container",style:{width:"140px",height:"140px",flex:"0 0 auto"}},zt={class:"ms-3 flex-grow-1"},Bt={class:"mb-3"},Et={class:"h5 mb-0",style:{color:"var(--text-heading)"}},It={class:"h5 mb-0",style:{color:"var(--text-heading)"}},Gt={__name:"Analytics",setup(Vt){const{fetchAnalytics:N,fetchCertificates:L}=P(),{formatBytes:f}=J(),{config:O}=E(),C=c(null),v=c(null);let u=null;const U=X(C,{maxPoints:96}),d=T({analytics:!0,certs:!0}),m=c("24h"),p=c(!1),a=T({concurrentUsers:"-",totalTraffic:0,expiringCerts:"-",totalReceived:0,totalSent:0,totalReceivedString:"-",totalSentString:"-"}),_=c([]),h=c([]);let k=[];const g=async()=>{d.analytics=!0;try{const l=await N(m.value);l.success&&M(l.data)}catch(l){console.error(l)}finally{d.analytics=!1}},w=async()=>{d.certs=!0;try{const e=(await L()).filter(s=>!s.is_revoked&&!s.is_expired&&s.days_remaining!=null&&s.days_remaining<=45);a.expiringCerts=e.length,h.value=e.sort((s,j)=>s.days_remaining-j.days_remaining)}catch(l){console.error(l)}finally{d.certs=!1}},M=l=>{a.concurrentUsers=l.max_concurrent_24h||0;const e=l.traffic_distribution||{rx:0,tx:0};a.totalReceived=Number(e.rx||0),a.totalSent=Number(e.tx||0),a.totalTraffic=a.totalReceived+a.totalSent,a.totalReceivedString=f(a.totalReceived),a.totalSentString=f(a.totalSent),_.value=(l.top_clients_24h||[]).map(s=>({name:s.common_name,total:Number(s.total_traffic||0),percent:a.totalTraffic>0?(Number(s.total_traffic)/a.totalTraffic*100).toFixed(1):0})),k=(l.global_history_24h||[]).map(s=>({timestamp:s.timestamp,bytes_received:s.total_rx,bytes_sent:s.total_tx,rx_rate_mbps:s.total_rx_rate,tx_rate_mbps:s.total_tx_rate})),y(),S()},y=()=>{U.render(k,{range:m.value,speedMode:p.value})},S=()=>{if(!v.value)return;u&&u.destroy();const l=v.value.getContext("2d"),e=G().isDark?"#161b22":"#ffffff";u=new K(l,{type:"doughnut",data:{labels:["Received","Sent"],datasets:[{data:[a.totalReceived,a.totalSent],backgroundColor:[W,q],borderColor:e,borderWidth:2,hoverOffset:4}]},options:{responsive:!0,maintainAspectRatio:!1,cutout:"70%",plugins:{legend:{display:!1}}}})};let x;return z(()=>{y(),S()}),B(()=>{g(),w();const l=O.value?.refresh_interval||3e4;x=setInterval(()=>{g(),w()},l)}),I(()=>{x&&clearInterval(x),u&&u.destroy()}),(l,e)=>(i(),n(b,null,[t("div",Q,[t("div",Y,[t("div",Z,[t("h3",null,o(a.concurrentUsers),1),e[2]||(e[2]=t("p",{class:"stat-label"},"Concurrent Users (Peak)",-1))])]),t("div",$,[t("div",tt,[t("h3",null,o(R(f)(a.totalTraffic)),1),e[3]||(e[3]=t("p",{class:"stat-label"},"Traffic Volume (Total)",-1))])]),t("div",et,[t("div",st,[t("h3",null,o(a.expiringCerts),1),e[4]||(e[4]=t("p",{class:"stat-label"},"Expiring Soon (In 45 Days)",-1))])])]),t("div",at,[t("div",lt,[e[8]||(e[8]=t("span",null,[t("i",{class:"fas fa-chart-area me-2"}),r("Traffic Overview")],-1)),t("div",ot,[A(t("select",{class:"form-select form-select-sm",style:{width:"auto"},"onUpdate:modelValue":e[0]||(e[0]=s=>m.value=s),onChange:g},[...e[5]||(e[5]=[t("option",{value:"24h"},"Last 24 Hours",-1),t("option",{value:"7d"},"Last 7 Days",-1),t("option",{value:"30d"},"Last 1 Month",-1)])],544),[[V,m.value]]),t("div",nt,[t("div",it,[t("label",rt,[A(t("input",{type:"checkbox",id:"vizToggle","onUpdate:modelValue":e[1]||(e[1]=s=>p.value=s),onChange:y},nuLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
import{r as _,a as U,o as G,u as Z,b as q,c as r,d as t,t as i,e as I,f as J,g as f,w as z,v as K,h as Q,F as E,i as j,j as Y,k as d,n as $}from"./index-BsVv6gaD.js";import{C as H}from"./vendor-charts-Bcjh2pZL.js";import"./vendor-ui-jlFFG6nm.js";const tt={class:"kpi-grid mb-4"},et={class:"stat-item"},st={class:"stat-content"},at={class:"stat-item"},ot={class:"stat-content"},lt={class:"stat-item"},nt={class:"stat-content"},it={class:"card mb-4"},rt={class:"card-header d-flex justify-content-between align-items-center flex-wrap"},dt={class:"chart-header-controls"},ct={class:"d-flex align-items-center"},ut={class:"toggle-wrapper me-2"},mt={class:"toggle-switch"},ft={class:"card-body"},pt={class:"chart-container"},vt={class:"row"},ht={class:"col-lg-7"},_t={class:"card"},gt={class:"card-body p-0"},bt={class:"table-responsive"},xt={class:"table"},yt={key:0},Ct={key:1},kt={class:"user-select-all fw-bold",style:{color:"var(--text-heading)"}},wt={class:"font-monospace text-muted"},St={class:"d-flex align-items-center"},Rt={class:"progress flex-grow-1",style:{height:"6px"}},Tt={class:"ms-2 small text-muted w-25 text-end"},At={class:"col-lg-5"},Dt={class:"card mb-4"},Mt={class:"card-body p-3",style:{"min-height":"120px","max-height":"200px","overflow-y":"auto"}},Et={key:0,class:"text-muted text-center py-3 mb-0"},Nt={key:1,class:"text-muted text-center py-3 mb-0"},Lt={key:2,class:"list-group list-group-flush"},Bt={class:"fw-bold small"},Ut={class:"text-muted",style:{"font-size":"0.75rem"}},It={class:"badge status-warning text-dark"},zt={class:"card"},jt={class:"card-body d-flex align-items-center justify-content-around p-4",style:{"min-height":"200px"}},Ht={class:"pie-container",style:{width:"140px",height:"140px",flex:"0 0 auto"}},Ot={class:"ms-3 flex-grow-1"},Vt={class:"mb-3"},Ft={class:"h5 mb-0",style:{color:"var(--text-heading)"}},Pt={class:"h5 mb-0",style:{color:"var(--text-heading)"}},Wt=96,Jt={__name:"Analytics",setup(Xt){const{fetchAnalytics:O,fetchCertificates:V}=Y(),{formatBytes:C,parseServerDate:F}=J(),{config:P}=Z(),w=_(null),S=_(null);let g=null,b=null;const p=U({analytics:!0,certs:!0}),x=_("24h"),y=_(!1),o=U({concurrentUsers:"-",totalTraffic:0,expiringCerts:"-",totalReceived:0,totalSent:0,totalReceivedString:"-",totalSentString:"-"}),R=_([]),T=_([]);let N=null;const A=async()=>{p.analytics=!0;try{const a=await O(x.value);a.success&&W(a.data)}catch(a){console.error(a)}finally{p.analytics=!1}},L=async()=>{p.certs=!0;try{const a=await V();if(a.success&&Array.isArray(a.data)){const e=a.data.filter(s=>!s.is_revoked&&!s.is_expired&&s.days_remaining!==null&&s.days_remaining<=45);o.expiringCerts=e.length,T.value=e.sort((s,n)=>(s.days_remaining||0)-(n.days_remaining||0))}}catch(a){console.error(a)}finally{p.certs=!1}},W=a=>{o.concurrentUsers=a.max_concurrent_24h||0;const e=a.traffic_distribution||{rx:0,tx:0};o.totalReceived=Number(e.rx||0),o.totalSent=Number(e.tx||0),o.totalTraffic=o.totalReceived+o.totalSent,o.totalReceivedString=C(o.totalReceived),o.totalSentString=C(o.totalSent),R.value=(a.top_clients_24h||[]).map(s=>({name:s.common_name,total:Number(s.total_traffic||0),percent:o.totalTraffic>0?(Number(s.total_traffic)/o.totalTraffic*100).toFixed(1):0})),N=a.global_history_24h||[],D(),B()},D=()=>{if(!w.value)return;g&&g.destroy();const a=X(N,Wt),e=[],s=[],n=[];a.forEach(c=>{const m=F(c.timestamp);let u="";x.value.includes("h")||x.value==="1d"?u=m.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):u=m.toLocaleDateString([],{month:"short",day:"numeric"})+" "+m.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),e.push(u),y.value?(s.push(c.rx_rate_mbps||0),n.push(c.tx_rate_mbps||0)):(s.push(c.bytes_received/(1024*1024)),n.push(c.bytes_sent/(1024*1024)))});const l=document.documentElement.getAttribute("data-theme")==="dark",v=l?"rgba(240, 246, 252, 0.1)":"rgba(0,0,0,0.05)",h=l?"#8b949e":"#6c757d",k=w.value.getContext("2d");g=new H(k,{type:"line",data:{labels:e,datasets:[{label:y.value?"RX Mbps":"Received (MB)",data:s,borderColor:"#1652B8",backgroundColor:"rgba(22, 82, 184, 0.15)",borderWidth:2,fill:!0,tension:.3,pointRadius:3,pointHoverRadius:4},{label:y.value?"TX Mbps":"Sent (MB)",data:n,borderColor:"#EC7C31",backgroundColor:"rgba(236, 124, 49, 0.15)",borderWidth:2,fill:!0,tension:.3,pointRadius:3,pointHoverRadius:4}]},options:{responsive:!0,maintainAspectRatio:!1,interaction:{mode:"index",intersect:!1},plugins:{legend:{labels:{color:h}}},scales:{x:{ticks:{color:h,maxTicksLimit:8},grid:{color:v}},y:{beginAtZero:!0,ticks:{color:h},grid:{color:v}}}}})},B=()=>{if(!S.value)return;b&&b.destroy();const a=S.value.getContext("2d"),s=document.documentElement.getAttribute("data-theme")==="dark"?"#161b22":"#ffffff";b=new H(a,{type:"doughnut",data:{labels:["Received","Sent"],datasets:[{data:[o.totalReceived,o.totalSent],backgroundColor:["#1652B8","#EC7C31"],borderColor:s,borderWidth:2,hoverOffset:4}]},options:{responsive:!0,maintainAspectRatio:!1,cutout:"70%",plugins:{legend:{display:!1}}}})},X=(a,e)=>{if(!a||a.lLine truncated
|
||||
@@ -0,0 +1,15 @@
|
||||
import{r as v,a as F,p as N,D as ze,o as qe,C as We,c as Ye,d as n,e as t,q as B,g as c,m as u,F as b,i as _,t as o,w as g,x,y as Ge,s as C,v as X,A as q,h as ee,z as ge,j as Je,k as l}from"./index-CH6sppUl.js";import{u as Ze}from"./useFormatters-CKGG-YVI.js";import{_ as ye,a as te}from"./ConfirmModal-XwuF5iM0.js";import"./vendor-ui-Dumif2LN.js";const Qe={class:"backup-page"},Xe={class:"config-card backup-card"},et={class:"d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2"},tt=["disabled"],st={class:"table-responsive"},at={class:"table table-hover mb-0"},nt={key:0},lt={key:1},ot={class:"align-top"},it={class:"fw-semibold",style:{color:"var(--text-heading)"}},rt={class:"text-muted small"},dt={key:0,class:"small mt-1"},ct=["title"],ut={key:1,class:"status-badge status-warning"},pt={key:1,class:"small mt-1"},mt={class:"align-top"},bt={class:"status-badge status-client"},ft={class:"align-top"},gt={class:"align-top"},yt=["title"],vt={key:1,class:"text-muted small"},kt={key:2,class:"text-muted small"},ht={class:"align-top"},_t=["onClick","disabled"],wt={key:0,class:"fas fa-spinner fa-spin"},xt={key:1,class:"fas fa-plug"},St=["onClick","disabled"],Ct=["onClick","disabled"],$t={class:"config-card backup-card"},Tt={class:"d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2"},Pt={key:0,class:"status-badge status-valid"},Nt={key:1,class:"status-badge status-warning"},Vt=["disabled"],It={class:"text-muted small mb-3"},Dt={class:"config-input-group"},Ut=["disabled"],At=["disabled"],Et={class:"text-muted small mt-2 mb-0"},Rt={class:"text-main"},Ft={key:0},Bt={key:1},Mt={key:0,class:"text-muted small mb-3"},jt={key:1,class:"mb-3"},Lt=["id","value","disabled"],Ot=["for"],Ht={class:"text-muted small"},Kt={key:0,class:"text-muted small"},zt={class:"btn-action-group justify-content-center mt-3"},qt=["disabled"],Wt={key:0,class:"fas fa-spinner fa-spin"},Yt={key:1,class:"fas fa-box-archive"},Gt={key:2,class:"nested-box fade-in mt-4"},Jt={class:"nested-label d-flex justify-content-between"},Zt={class:"backup-steps"},Qt={key:0,class:"fas fa-spinner fa-spin me-1"},Xt={class:"fw-semibold ms-2",style:{color:"var(--text-heading)"}},es={key:0,class:"text-muted small ms-1 mt-1"},ts={key:0,class:"text-muted small mt-2"},ss={key:3,class:"mt-4"},as={class:"table-responsive"},ns={class:"table table-hover mb-0"},ls={class:"text-capitalize"},os={class:"small text-muted"},is={class:"config-card backup-card"},rs={class:"config-row"},ds={class:"config-col"},cs={class:"select-container"},us=["disabled"],ps=["value"],ms={key:0,class:"text-muted small mt-2"},bs={key:1,class:"mt-2"},fs={class:"text-muted small mt-1"},gs={key:2,class:"mt-2"},ys={class:"text-muted small ms-2"},vs={class:"config-row"},ks={class:"config-col"},hs={class:"select-container"},_s=["disabled"],ws={value:"",disabled:""},xs=["value"],Ss={key:0,class:"config-row"},Cs={class:"config-col"},$s={class:"btn-action-group justify-content-center"},Ts=["disabled"],Ps={key:0,class:"fas fa-spinner fa-spin"},Ns={key:1,class:"fas fa-rotate-left"},Vs={key:1,class:"nested-box fade-in mt-4"},Is={class:"nested-label d-flex justify-content-between"},Ds={class:"backup-steps"},Us={class:"status-badge status-warning"},As={key:1,class:"mt-3"},Es={class:"mb-3"},Rs={class:"mb-3"},Fs={class:"select-container"},Bs=["value"],Ms={key:0,class:"form-text mt-2 small text-warning"},js={class:"form-label small fw-bold text-muted text-uppercase d-block"},Ls={class:"toggle-wrapper"},Os={class:"toggle-switch"},Hs=["onUpdate:modelValue"],Ks={class:"form-label small fw-bold text-muted text-uppercase"},zs=["onUpdate:modelValue","placeholder"],qs={key:0,class:"form-text mt-1 text-muted small"},Ws={class:"form-label small fw-bold text-muted text-uppercase"},Ys=["onUpdate:modelValue","placeholder"],Gs={class:"form-label small fw-bold text-muted text-uppercase"},Js=["onUpdate:modelValue"],Zs={class:"form-label small fw-bold text-muted text-uppercase"},Qs=["onUpdate:modelValue","placeholder"],Xs={key:0,class:"form-text mt-1 text-muted small"},ea={key:5,class:"form-text mt-2 small text-warning"},ta={key:0,class:"mb-3"},sa={key:0,class:"small text-main",style:{"word-break":"break-all"}},aa={key:1,class:"form-text small text-warning"},na={class:"mb-3"},la={class:"mb-1 d-flex align-items-center"},oa={class:"toggle-wrapper me-2"},ia={class:"toggle-switch"},ra=["disabled"],da={key:0,class:"spinner-border spinner-border-sm me-2"},ca={class:"mb-3"},ua={class:"mb-2"},pa=["disabled"],ma=["disabled"],ba={key:0,class:"spinner-border spinner-border-sm me-2"},ha={__name:"BackupRestore",setup(fa){const{profilesApiClient:y}=Je(),m=We(),{formatBytes:ve}=Ze(),se=v(!0),k=v(!1),M=v(null),p=F({encryption_enabled:!1,default_retention:14,local_root:"",types:[],server_name:"",effective_server_name:"",server_name_source:"hostname"}),P=v(""),V=v([]),W=v([]),$=v([]),i=F({kind:null,state:"idle",stages:[],results:[],warnings:[],message:null,relogin:!1}),j=v(!1),I=v(null),L=v(null),ae=v(null),ne=v(null),le=v(nLine truncated
|
||||
|
||||
`:`The server of "${a.name}" showed this host key. Compare it with the fingerprint you know (ssh-keygen -lf on the server) before you trust it.
|
||||
|
||||
`)+`Type: ${e.key_type}
|
||||
SHA-256: ${e.fingerprint}
|
||||
|
||||
Packages are sent only to a server with exactly this key.`,confirmText:e.key_changed?"Trust the new key":"Trust",confirmBtnClass:e.key_changed?"btn-action-danger":"btn-action-primary",data:{id:a.id,name:a.name,fingerprint:e.fingerprint}})},Ee=async a=>{try{await y.post(`/backup/destinations/${a.id}/trust-host-key`,{fingerprint:a.fingerprint}),m.show(`Host key of ${a.name} trusted. Press Test to check the connection.`,"success"),await T()}catch(e){m.show(w(e),"error")}},Re=a=>{ae.value.open({title:"Delete Destination?",message:`Delete "${a.name}"? Packages already stored there are not deleted.`,confirmText:"Yes, Delete",data:a})},Fe=async a=>{try{await y.delete(`/backup/destinations/${a.id}`),m.show(`${a.name} deleted.`,"success"),d.sourceId===a.id&&(d.sourceId=null),await T()}catch(e){m.show(w(e),"error")}},Be=()=>{S.value="",S.confirm="",L.value.show()},Me=async()=>{if(S.value!==S.confirm){m.show("Passphrases do not match.","error");return}await be({passphrase:S.value},"Passphrase saved.")},je=async()=>{await be({clear_passphrase:!0},"Passphrase removed. New packages are not encrypted.")},me=async()=>{const a=P.value.trim();if(a!==(p.server_name||"")){k.value=!0;try{const e=await y.put("/backup/settings",{server_name:a});Object.assign(p,e.data),P.value=p.server_name||"",m.show(a?"Server name saved.":"Server name cleared.","success")}catch(e){m.show(w(e),"error")}finally{k.value=!1}}},be=async(a,e)=>{k.value=!0;try{const s=await y.put("/backup/settings",a);Object.assign(p,s.data),m.show(e,"success"),L.value.hide(),await T()}catch(s){m.show(w(s),"error")}finally{k.value=!1}},Le=async()=>{try{await y.post("/backup/run",{destination_ids:$.value}),j.value=!1,i.kind="backup",i.state="running",await R(),Z()}catch(a){a.response?.status===409&&await R(),m.show(w(a),"error")}},fe=async()=>{if(d.packages=[],d.packageName="",d.passphrase="",d.sourceError="",d.sourceId!==null){d.checking=!0;try{const a=await y.get(`/backup/destinations/${d.sourceId}/packages`);d.packages=a.data.packages}catch(a){d.sourceError=w(a)}finally{d.checking=!1}}};ze(()=>d.sourceId,fe);const Oe=()=>{const a=E.value;ne.value.open({title:"Restore from Backup?",message:`Package: ${a.server_name}, ${oe(a.created_at)} (${z(a.created_at)} local)
|
||||
|
||||
This replaces:
|
||||
- the monitoring database (statistics, administrator accounts, 2FA),
|
||||
- the profiler database and the server settings,
|
||||
- the PKI (CA, keys, certificates) and the client profiles.
|
||||
|
||||
OpenVPN is stopped and started again; connected clients are disconnected. The current state is saved to a local safety copy first. You will have to log in again.`,confirmText:"Yes, Restore",confirmBtnClass:"btn-action-danger",data:a})},He=async a=>{try{await y.post("/backup/restore",{destination_id:d.sourceId,package:a.name,passphrase:a.encrypted?d.passphrase:null}),j.value=!1,d.passphrase="",i.kind="restore",i.state="running",await R(),Z()}catch(e){m.show(w(e),"error")}},Ke=()=>{localStorage.removeItem("ovpmon_token"),localStorage.removeItem("ovpmon_user"),window.location.href="/login"};return qe(async()=>{try{await Te(),await T(),ce(),await Promise.all([de(),R()])}catch(a){m.show(`Failed to load backup settings: ${w(a)}`,"error")}finally{se.value=!1}}),Ye(ue),(a,e)=>(l(),n("div",Qe,[t("div",Xe,[e[23]||(e[23]=t("div",{class:"config-header"},[t("h1",null,"Backup Destinations")],-1)),t("div",et,[e[14]||(e[14]=t("span",{class:"text-muted small"},"Where backup packages are stored. A backup goes to every selected destination.",-1)),t("button",{type:"button",class:"btn-action btn-action-save btn-sm",onClick:Ne,disabled:!p.types.length},[...e[13]||(e[13]=[t("i",{class:"fas fa-plus"},null,-1),c(" Add destination ",-1)])],8,tt)]),t("div",st,[t("table",at,[e[22]||(e[22]=t("thead",null,[t("tr",null,[t("th",null,"Name"),t("th",null,"Type"),t("th",null,"Status"),t("th",null,"Last result"),t("th",null,"Actions")])],-1)),t("tbody",null,[se.value?(l(),n("tr",nt,[...e[15]||(e[15]=[t("td",{colspan:"5",class:"text-center py-4"},[t("div",{class:"spinner-border spinner-border-sm text-primary",role:"status"},[t("span",{class:"visually-hidden"},"Loading...")])],-1)])])):V.value.length===0?(l(),n("tr",lt,[...e[16]||(e[16]=[t("td",{colspan:"5",class:"empty-state text-center py-4"},[t("i",{class:"fas fa-box-archive fa-2x mb-3 text-muted"}),t("p",{class:"text-muted mb-0"},"No destinations yet. Add one to start making backups.")],-1)])])):u("",!0),(l(!0),n(b,null,_(V.value,s=>(l(),n("tr",{key:s.id},[t("td",ot,[t("div",it,o(s.name),1),t("div",rt,o(we(s)),1),U(s.type)?.pins_host_key?(l(),n("div",dt,[s.params.host_key?(l(),n("span",{key:0,class:"status-badge status-valid",title:s.params.host_key},[...e[17]||(e[17]=[t("i",{class:"fas fa-fingerprint me-1"},null,-1),c("Host key trusted ",-1)])],8,ct)):(l(),n("span",ut,[...e[18]||(e[18]=[t("i",{class:"fas fa-triangle-exclamation me-1"},null,-1),c("Host key not trusted: press Test and confirm it ",-1)])]))])):u("",!0),xe(s)?(l(),n("div",pt,[...e[19]||(e[19]=[t("span",{class:"status-badge status-warning"},[t("i",{class:"fas fa-triangle-exclamation me-1"}),c("No TLS: clear text")],-1)])])):u("",!0)]),t("td",mt,[t("span",bt,o(Y(s.type)),1)]),t("td",ft,[t("span",{class:C(["status-badge",s.enabled?"status-valid":"status-secondary"])},o(s.enabled?"Enabled":"Disabled"),3)]),t("td",gt,[s.last_status?(l(),n("span",{key:0,class:C(["status-badge",s.last_status==="ok"?"status-valid":"status-expired"]),title:s.last_message},o(s.last_status==="ok"?"OK":"Failed"),11,yt)):(l(),n("span",vt,"never used")),s.last_at?(l(),n("div",kt,o(z(s.last_at)),1)):u("",!0)]),t("td",ht,[t("button",{class:"btn btn-sm btn-link text-primary p-0 me-2",title:"Test connection",onClick:f=>Ue(s),disabled:M.value===s.id},[M.value===s.id?(l(),n("i",wt)):(l(),n("i",xt))],8,_t),t("button",{class:"btn btn-sm btn-link text-warning p-0 me-2",title:"Edit",onClick:f=>Ve(s),disabled:h.value},[...e[20]||(e[20]=[t("i",{class:"fas fa-pen"},null,-1)])],8,St),t("button",{class:"btn btn-sm btn-link text-danger p-0",title:"Delete",onClick:f=>Re(s),disabled:h.value},[...e[21]||(e[21]=[t("i",{class:"fas fa-trash"},null,-1)])],8,Ct)])]))),128))])])])]),t("div",$t,[e[34]||(e[34]=t("div",{class:"config-header"},[t("h1",null,"Backup")],-1)),t("div",Tt,[t("div",null,[p.encryption_enabled?(l(),n("span",Pt,[...e[24]||(e[24]=[t("i",{class:"fas fa-lock me-1"},null,-1),c("Packages are encrypted ",-1)])])):(l(),n("span",Nt,[...e[25]||(e[25]=[t("i",{class:"fas fa-triangle-exclamation me-1"},null,-1),c("Packages are NOT encrypted ",-1)])]))]),t("button",{type:"button",class:"btn-action btn-action-secondary btn-sm",onClick:Be,disabled:h.value},[e[26]||(e[26]=t("i",{class:"fas fa-key"},null,-1)),c(" "+o(p.encryption_enabled?"Change passphrase":"Set passphrase"),1)],8,Vt)]),t("p",It,[e[27]||(e[27]=c(" A package contains the CA private key, the certificates and the password hashes of the administrators. ",-1)),p.encryption_enabled?(l(),n(b,{key:1},[c("Keep the passphrase: a package cannot be restored without it, and it is not stored in the package.")],64)):(l(),n(b,{key:0},[c("Remote destinations need an encryption passphrase; a local folder can be used without it.")],64))]),e[35]||(e[35]=t("div",{class:"config-divider"},null,-1)),e[36]||(e[36]=t("label",{class:"config-label"},"Server name",-1)),t("div",Dt,[g(t("input",{type:"text",class:"config-input","onUpdate:modelValue":e[0]||(e[0]=s=>P.value=s),maxlength:"63",autocomplete:"off",placeholder:"e.g. vpn-main",disab
Line truncated
|
||||
@@ -1,15 +0,0 @@
|
||||
import{r as v,a as B,s as N,D as ze,o as qe,B as We,b as Ye,c as n,d as t,A as F,g as c,x as u,F as b,i as _,t as o,w as g,q as x,p as Ge,y as C,v as X,m as q,h as ee,C as ge,j as Je,k as l,f as Ze}from"./index-BsVv6gaD.js";import{_ as ye,a as te}from"./ConfirmModal-CzamKe9d.js";import"./vendor-charts-Bcjh2pZL.js";import"./vendor-ui-jlFFG6nm.js";const Qe={class:"backup-page"},Xe={class:"config-card backup-card"},et={class:"d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2"},tt=["disabled"],st={class:"table-responsive"},at={class:"table table-hover mb-0"},nt={key:0},lt={key:1},ot={class:"fw-semibold",style:{color:"var(--text-heading)"}},it={class:"text-muted small"},rt={key:0,class:"small mt-1"},dt=["title"],ct={key:1,class:"status-badge status-warning"},ut={key:1,class:"small mt-1"},pt={class:"status-badge status-client"},mt=["title"],bt={key:1,class:"text-muted small"},ft={key:2,class:"text-muted small"},gt=["onClick","disabled"],yt={key:0,class:"fas fa-spinner fa-spin"},vt={key:1,class:"fas fa-plug"},kt=["onClick","disabled"],ht=["onClick","disabled"],_t={class:"config-card backup-card"},wt={class:"d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2"},xt={key:0,class:"status-badge status-valid"},St={key:1,class:"status-badge status-warning"},Ct=["disabled"],$t={class:"text-muted small mb-3"},Tt={class:"config-input-group"},Pt=["disabled"],Nt=["disabled"],Vt={class:"text-muted small mt-2 mb-0"},It={class:"text-main"},Dt={key:0},Ut={key:1},At={key:0,class:"text-muted small mb-3"},Et={key:1,class:"mb-3"},Rt=["id","value","disabled"],Bt=["for"],Ft={class:"text-muted small"},Mt={key:0,class:"text-muted small"},jt={class:"btn-action-group justify-content-center mt-3"},Lt=["disabled"],Ot={key:0,class:"fas fa-spinner fa-spin"},Ht={key:1,class:"fas fa-box-archive"},Kt={key:2,class:"nested-box fade-in mt-4"},zt={class:"nested-label d-flex justify-content-between"},qt={class:"backup-steps"},Wt={key:0,class:"fas fa-spinner fa-spin me-1"},Yt={class:"fw-semibold ms-2",style:{color:"var(--text-heading)"}},Gt={key:0,class:"text-muted small ms-1 mt-1"},Jt={key:0,class:"text-muted small mt-2"},Zt={key:3,class:"mt-4"},Qt={class:"table-responsive"},Xt={class:"table table-hover mb-0"},es={class:"text-capitalize"},ts={class:"small text-muted"},ss={class:"config-card backup-card"},as={class:"config-row"},ns={class:"config-col"},ls={class:"select-container"},os=["disabled"],is=["value"],rs={key:0,class:"text-muted small mt-2"},ds={key:1,class:"mt-2"},cs={class:"text-muted small mt-1"},us={key:2,class:"mt-2"},ps={class:"text-muted small ms-2"},ms={class:"config-row"},bs={class:"config-col"},fs={class:"select-container"},gs=["disabled"],ys={value:"",disabled:""},vs=["value"],ks={key:0,class:"config-row"},hs={class:"config-col"},_s={class:"btn-action-group justify-content-center"},ws=["disabled"],xs={key:0,class:"fas fa-spinner fa-spin"},Ss={key:1,class:"fas fa-rotate-left"},Cs={key:1,class:"nested-box fade-in mt-4"},$s={class:"nested-label d-flex justify-content-between"},Ts={class:"backup-steps"},Ps={class:"status-badge status-warning"},Ns={key:1,class:"mt-3"},Vs={class:"mb-3"},Is={class:"mb-3"},Ds={class:"select-container"},Us=["value"],As={key:0,class:"form-text mt-2 small text-warning"},Es={class:"form-label small fw-bold text-muted text-uppercase d-block"},Rs={class:"toggle-wrapper"},Bs={class:"toggle-switch"},Fs=["onUpdate:modelValue"],Ms={class:"form-label small fw-bold text-muted text-uppercase"},js=["onUpdate:modelValue","placeholder"],Ls={key:0,class:"form-text mt-1 text-muted small"},Os={class:"form-label small fw-bold text-muted text-uppercase"},Hs=["onUpdate:modelValue","placeholder"],Ks={class:"form-label small fw-bold text-muted text-uppercase"},zs=["onUpdate:modelValue"],qs={class:"form-label small fw-bold text-muted text-uppercase"},Ws=["onUpdate:modelValue","placeholder"],Ys={key:0,class:"form-text mt-1 text-muted small"},Gs={key:5,class:"form-text mt-2 small text-warning"},Js={key:0,class:"mb-3"},Zs={key:0,class:"small text-main",style:{"word-break":"break-all"}},Qs={key:1,class:"form-text small text-warning"},Xs={class:"mb-3"},ea={class:"mb-1 d-flex align-items-center"},ta={class:"toggle-wrapper me-2"},sa={class:"toggle-switch"},aa=["disabled"],na={key:0,class:"spinner-border spinner-border-sm me-2"},la={class:"mb-3"},oa={class:"mb-2"},ia=["disabled"],ra=["disabled"],da={key:0,class:"spinner-border spinner-border-sm me-2"},fa={__name:"BackupRestore",setup(ca){const{profilesApiClient:y}=Je(),m=We(),{formatBytes:ve}=Ze(),se=v(!0),k=v(!1),M=v(null),p=B({encryption_enabled:!1,default_retention:14,local_root:"",types:[],server_name:"",effective_server_name:"",server_name_source:"hostname"}),P=v(""),V=v([]),W=v([]),$=v([]),i=B({kind:null,state:"idle",stages:[],results:[],warnings:[],message:null,relogin:!1}),j=v(!1),I=v(null),L=v(null),ae=v(null),ne=v(null),le=v(null),r=B({id:null,name:"",type:"local",enabled:!0,retention_count:14,params:{},secrets:{}}),O=v({}),S=B({value:"",cLine truncated
|
||||
|
||||
`:`The server of "${a.name}" showed this host key. Compare it with the fingerprint you know (ssh-keygen -lf on the server) before you trust it.
|
||||
|
||||
`)+`Type: ${e.key_type}
|
||||
SHA-256: ${e.fingerprint}
|
||||
|
||||
Packages are sent only to a server with exactly this key.`,confirmText:e.key_changed?"Trust the new key":"Trust",confirmBtnClass:e.key_changed?"btn-action-danger":"btn-action-primary",data:{id:a.id,name:a.name,fingerprint:e.fingerprint}})},Ee=async a=>{try{await y.post(`/backup/destinations/${a.id}/trust-host-key`,{fingerprint:a.fingerprint}),m.show(`Host key of ${a.name} trusted. Press Test to check the connection.`,"success"),await T()}catch(e){m.show(w(e),"error")}},Re=a=>{ae.value.open({title:"Delete Destination?",message:`Delete "${a.name}"? Packages already stored there are not deleted.`,confirmText:"Yes, Delete",data:a})},Be=async a=>{try{await y.delete(`/backup/destinations/${a.id}`),m.show(`${a.name} deleted.`,"success"),d.sourceId===a.id&&(d.sourceId=null),await T()}catch(e){m.show(w(e),"error")}},Fe=()=>{S.value="",S.confirm="",L.value.show()},Me=async()=>{if(S.value!==S.confirm){m.show("Passphrases do not match.","error");return}await be({passphrase:S.value},"Passphrase saved.")},je=async()=>{await be({clear_passphrase:!0},"Passphrase removed. New packages are not encrypted.")},me=async()=>{const a=P.value.trim();if(a!==(p.server_name||"")){k.value=!0;try{const e=await y.put("/backup/settings",{server_name:a});Object.assign(p,e.data),P.value=p.server_name||"",m.show(a?"Server name saved.":"Server name cleared.","success")}catch(e){m.show(w(e),"error")}finally{k.value=!1}}},be=async(a,e)=>{k.value=!0;try{const s=await y.put("/backup/settings",a);Object.assign(p,s.data),m.show(e,"success"),L.value.hide(),await T()}catch(s){m.show(w(s),"error")}finally{k.value=!1}},Le=async()=>{try{await y.post("/backup/run",{destination_ids:$.value}),j.value=!1,i.kind="backup",i.state="running",await R(),Z()}catch(a){a.response?.status===409&&await R(),m.show(w(a),"error")}},fe=async()=>{if(d.packages=[],d.packageName="",d.passphrase="",d.sourceError="",d.sourceId!==null){d.checking=!0;try{const a=await y.get(`/backup/destinations/${d.sourceId}/packages`);d.packages=a.data.packages}catch(a){d.sourceError=w(a)}finally{d.checking=!1}}};ze(()=>d.sourceId,fe);const Oe=()=>{const a=E.value;ne.value.open({title:"Restore from Backup?",message:`Package: ${a.server_name}, ${oe(a.created_at)} (${z(a.created_at)} local)
|
||||
|
||||
This replaces:
|
||||
- the monitoring database (statistics, administrator accounts, 2FA),
|
||||
- the profiler database and the server settings,
|
||||
- the PKI (CA, keys, certificates) and the client profiles.
|
||||
|
||||
OpenVPN is stopped and started again; connected clients are disconnected. The current state is saved to a local safety copy first. You will have to log in again.`,confirmText:"Yes, Restore",confirmBtnClass:"btn-action-danger",data:a})},He=async a=>{try{await y.post("/backup/restore",{destination_id:d.sourceId,package:a.name,passphrase:a.encrypted?d.passphrase:null}),j.value=!1,d.passphrase="",i.kind="restore",i.state="running",await R(),Z()}catch(e){m.show(w(e),"error")}},Ke=()=>{localStorage.removeItem("ovpmon_token"),localStorage.removeItem("ovpmon_user"),window.location.href="/login"};return qe(async()=>{try{await Te(),await T(),ce(),await Promise.all([de(),R()])}catch(a){m.show(`Failed to load backup settings: ${w(a)}`,"error")}finally{se.value=!1}}),Ye(ue),(a,e)=>(l(),n("div",Qe,[t("div",Xe,[e[23]||(e[23]=t("div",{class:"config-header"},[t("h1",null,"Backup Destinations")],-1)),t("div",et,[e[14]||(e[14]=t("span",{class:"text-muted small"},"Where backup packages are stored. A backup goes to every selected destination.",-1)),t("button",{type:"button",class:"btn-action btn-action-save btn-sm",onClick:Ne,disabled:!p.types.length},[...e[13]||(e[13]=[t("i",{class:"fas fa-plus"},null,-1),c(" Add destination ",-1)])],8,tt)]),t("div",st,[t("table",at,[e[22]||(e[22]=t("thead",null,[t("tr",null,[t("th",null,"Name"),t("th",null,"Type"),t("th",null,"Status"),t("th",null,"Last result"),t("th",null,"Actions")])],-1)),t("tbody",null,[se.value?(l(),n("tr",nt,[...e[15]||(e[15]=[t("td",{colspan:"5",class:"text-center py-4"},[t("div",{class:"spinner-border spinner-border-sm text-primary",role:"status"},[t("span",{class:"visually-hidden"},"Loading...")])],-1)])])):V.value.length===0?(l(),n("tr",lt,[...e[16]||(e[16]=[t("td",{colspan:"5",class:"empty-state text-center py-4"},[t("i",{class:"fas fa-box-archive fa-2x mb-3 text-muted"}),t("p",{class:"text-muted mb-0"},"No destinations yet. Add one to start making backups.")],-1)])])):u("",!0),(l(!0),n(b,null,_(V.value,s=>(l(),n("tr",{key:s.id},[t("td",null,[t("div",ot,o(s.name),1),t("div",it,o(we(s)),1),U(s.type)?.pins_host_key?(l(),n("div",rt,[s.params.host_key?(l(),n("span",{key:0,class:"status-badge status-valid",title:s.params.host_key},[...e[17]||(e[17]=[t("i",{class:"fas fa-fingerprint me-1"},null,-1),c("Host key trusted ",-1)])],8,dt)):(l(),n("span",ct,[...e[18]||(e[18]=[t("i",{class:"fas fa-triangle-exclamation me-1"},null,-1),c("Host key not trusted: press Test and confirm it ",-1)])]))])):u("",!0),xe(s)?(l(),n("div",ut,[...e[19]||(e[19]=[t("span",{class:"status-badge status-warning"},[t("i",{class:"fas fa-triangle-exclamation me-1"}),c("No TLS: clear text")],-1)])])):u("",!0)]),t("td",null,[t("span",pt,o(Y(s.type)),1)]),t("td",null,[t("span",{class:C(["status-badge",s.enabled?"status-valid":"status-secondary"])},o(s.enabled?"Enabled":"Disabled"),3)]),t("td",null,[s.last_status?(l(),n("span",{key:0,class:C(["status-badge",s.last_status==="ok"?"status-valid":"status-expired"]),title:s.last_message},o(s.last_status==="ok"?"OK":"Failed"),11,mt)):(l(),n("span",bt,"never used")),s.last_at?(l(),n("div",ft,o(z(s.last_at)),1)):u("",!0)]),t("td",null,[t("button",{class:"btn btn-sm btn-link text-primary p-0 me-2",title:"Test connection",onClick:f=>Ue(s),disabled:M.value===s.id},[M.value===s.id?(l(),n("i",yt)):(l(),n("i",vt))],8,gt),t("button",{class:"btn btn-sm btn-link text-warning p-0 me-2",title:"Edit",onClick:f=>Ve(s),disabled:h.value},[...e[20]||(e[20]=[t("i",{class:"fas fa-pen"},null,-1)])],8,kt),t("button",{class:"btn btn-sm btn-link text-danger p-0",title:"Delete",onClick:f=>Re(s),disabled:h.value},[...e[21]||(e[21]=[t("i",{class:"fas fa-trash"},null,-1)])],8,ht)])]))),128))])])])]),t("div",_t,[e[34]||(e[34]=t("div",{class:"config-header"},[t("h1",null,"Backup")],-1)),t("div",wt,[t("div",null,[p.encryption_enabled?(l(),n("span",xt,[...e[24]||(e[24]=[t("i",{class:"fas fa-lock me-1"},null,-1),c("Packages are encrypted ",-1)])])):(l(),n("span",St,[...e[25]||(e[25]=[t("i",{class:"fas fa-triangle-exclamation me-1"},null,-1),c("Packages are NOT encrypted ",-1)])]))]),t("button",{type:"button",class:"btn-action btn-action-secondary btn-sm",onClick:Fe,disabled:h.value},[e[26]||(e[26]=t("i",{class:"fas fa-key"},null,-1)),c(" "+o(p.encryption_enabled?"Change passphrase":"Set passphrase"),1)],8,Ct)]),t("p",$t,[e[27]||(e[27]=c(" A package contains the CA private key, the certificates and the password hashes of the administrators. ",-1)),p.encryption_enabled?(l(),n(b,{key:1},[c("Keep the passphrase: a package cannot be restored without it, and it is not stored in the package.")],64)):(l(),n(b,{key:0},[c("Remote destinations need an encryption passphrase; a local folder can be used without it.")],64))]),e[35]||(e[35]=t("div",{class:"config-divider"},null,-1)),e[36]||(e[36]=t("label",{class:"config-label"},"Server name",-1)),t("div",Tt,[g(t("input",{type:"text",class:"config-input","onUpdate:modelValue":e[0]||(e[0]=s=>P.value=s),maxlength:"63",autocomplete:"off",placeholder:"e.g. vpn-m
Line truncated
|
||||
@@ -1 +0,0 @@
|
||||
import{r as m,l as Q,k as i,m as R,d as e,w as D,p as ne,q as j,g as C,s as y,c,x as w,t as n,F as A,y as G,o as oe,z as ie,A as P,e as H,h as re,i as K,j as de,B as ue,C as F}from"./index-BsVv6gaD.js";import{_ as J,a as ce}from"./ConfirmModal-CzamKe9d.js";import{T as pe}from"./vendor-ui-jlFFG6nm.js";import"./vendor-charts-Bcjh2pZL.js";const fe={class:"mb-3"},ve={class:"input-group"},me=["disabled"],_e={__name:"NewClientModal",emits:["create"],setup(r,{expose:d,emit:E}){const T=E,g=m(null),l=m(""),f=m(null),x=()=>{l.value="",g.value.show(),setTimeout(()=>f.value?.focus(),500)},b=()=>{g.value.hide()},k=()=>{l.value&&(T("create",l.value),b())};return d({open:x,close:b}),($,v)=>(i(),Q(J,{id:"newClientModal",title:"Create New Client",ref_key:"modal",ref:g},{body:R(()=>[e("div",fe,[v[2]||(v[2]=e("label",{for:"clientName",class:"form-label small text-muted text-uppercase fw-bold"},"Client Name",-1)),e("div",ve,[v[1]||(v[1]=e("span",{class:"input-group-text"},[e("i",{class:"fas fa-user"})],-1)),D(e("input",{type:"text",class:"form-control",id:"clientName","onUpdate:modelValue":v[0]||(v[0]=p=>l.value=p),placeholder:"e.g. laptop-user",onKeyup:ne(k,["enter"]),ref_key:"inputRef",ref:f},null,544),[[j,l.value]])]),v[3]||(v[3]=e("div",{class:"form-text mt-2 text-muted small"},[e("i",{class:"fas fa-info-circle me-1"}),C(" Use only alphanumeric characters, dashes, or underscores. ")],-1))])]),footer:R(()=>[e("button",{type:"button",class:"btn-action btn-action-secondary",onClick:b},"Cancel"),e("button",{type:"button",class:"btn-action btn-action-save",onClick:k,disabled:!l.value}," Create Client ",8,me)]),_:1},512))}},be={class:"d-flex align-items-center gap-2 flex-wrap"},ge={class:"modal-title fw-bold mb-0",style:{color:"var(--text-heading)"}},ye={key:0},xe={class:"profile-meta"},ke={key:0,class:"text-muted"},he={class:"certificate-file text-muted small text-break mt-0"},Ce={class:"form-text text-end"},we=["disabled"],$e={__name:"ProfileDetailsModal",emits:["save"],setup(r,{expose:d,emit:E}){const T=E,g=m(null),l=m(null),f=m(""),x=y(()=>f.value!==(l.value?.note||"")),b=y(()=>{const u=l.value;return u?.is_revoked?{label:"Revoked",cls:"status-expired"}:u?.is_expired?{label:"Expired",cls:"status-expired"}:u?.days_remaining!=null&&u.days_remaining<=30?{label:"Expiring Soon",cls:"status-warning"}:{label:"Active",cls:"status-valid"}}),k=y(()=>{const u=l.value?.days_remaining;return u==null?"":u>0?`${u} d`:"expired"}),$=u=>{if(!u)return"N/A";const o=new Date(u);if(isNaN(o))return u;const h=V=>String(V).padStart(2,"0");return`${o.getFullYear()}-${h(o.getMonth()+1)}-${h(o.getDate())} ${h(o.getHours())}:${h(o.getMinutes())}`},v=u=>{l.value=u,f.value=u.note||"",g.value.show()},p=()=>{g.value.hide()},S=()=>{T("save",{id:l.value.id,note:f.value}),p()};return d({open:v,close:p}),(u,o)=>(i(),Q(J,{id:"profileDetailsModal",title:"Profile Details",ref_key:"modal",ref:g},{header:R(()=>[e("div",be,[e("h5",ge,n(l.value?.username),1),l.value?(i(),c("span",{key:0,class:G(["status-badge",b.value.cls])},n(b.value.label),3)):w("",!0)])]),body:R(()=>[l.value?(i(),c("div",ye,[e("dl",xe,[o[2]||(o[2]=e("dt",null,"Created",-1)),e("dd",null,n($(l.value.created_at)),1),o[3]||(o[3]=e("dt",null,"Expires",-1)),e("dd",null,[C(n($(l.value.expiration_date)),1),k.value?(i(),c("span",ke," ("+n(k.value)+")",1)):w("",!0)]),l.value.revoked_at?(i(),c(A,{key:0},[o[1]||(o[1]=e("dt",null,"Revoked",-1)),e("dd",null,n($(l.value.revoked_at)),1)],64)):w("",!0),o[4]||(o[4]=e("dt",null,"File",-1)),e("dd",he,n(l.value.file_path||"N/A"),1)]),o[5]||(o[5]=e("label",{for:"profileNote",class:"form-label small text-muted text-uppercase fw-bold"},"Note",-1)),D(e("textarea",{class:"form-control",id:"profileNote",rows:"3",maxlength:"1000","onUpdate:modelValue":o[0]||(o[0]=h=>f.value=h),placeholder:"Add a note about this profile..."},null,512),[[j,f.value]]),e("div",Ce,n(f.value.length)+" / 1000",1)])):w("",!0)]),footer:R(()=>[e("button",{type:"button",class:"btn-action btn-action-secondary",onClick:p},"Close"),e("button",{type:"button",class:"btn-action btn-action-save",onClick:S,disabled:!x.value},"Save",8,we)]),_:1},512))}},O=(r,d)=>{r._noteTooltip=new pe(r,{title:d,placement:"top",container:"body",html:!1,trigger:"hover",customClass:"note-tooltip"})},Y=r=>{r._noteTooltip?.dispose(),r._noteTooltip=null},Ne=r=>r._noteTooltip?.hide(),q={mounted(r,d){r.addEventListener("click",()=>Ne(r)),d.value&&O(r,d.value)},updated(r,d){d.value!==d.oldValue&&(Y(r),d.value&&O(r,d.value))},unmounted(r){Y(r)}},Te={class:"stats-info mb-4",id:"statsInfo"},Me={class:"stat-item"},Ae={class:"stat-value"},De={class:"stat-item"},Ee={class:"stat-value"},Le={class:"stat-item"},Re={class:"stat-value"},Se={class:"stat-item"},Ve={class:"stat-value"},Be={class:"d-flex justify-content-between align-items-center mb-3 flex-wrap gap-3"},He={class:"d-flex gap-3 align-items-center flex-wrap"},Ue={class:"input-group input-group-sm",style:{width:"250px"}},Pe=["disabled","title"],Fe={class:"d-flex align-items-center"},je={Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{r as v,p as g,l as F,k as r,A as S,e,d as c,m as C,w as D,y as O,s as z,x as q,g as k,t as i,F as T,o as oe,B as ie,q as L,f as j,h as re,i as Z,j as de,C as ue,z as V}from"./index-CH6sppUl.js";import{_ as W,a as ce}from"./ConfirmModal-XwuF5iM0.js";import{T as pe}from"./vendor-ui-Dumif2LN.js";const fe={class:"mb-3"},ve={class:"input-group"},me={key:0,class:"text-danger small mt-2"},_e=["disabled"],be={__name:"NewClientModal",emits:["create"],setup(d,{expose:u,emit:x}){const m=x,y=v(null),n=v(""),f=v(null),w=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/,_=g(()=>w.test(n.value)),$=()=>{n.value="",y.value.show()},N=()=>{y.value.hide()},h=()=>{_.value&&(m("create",n.value),N())};return u({open:$,close:N}),(b,a)=>(r(),F(W,{id:"newClientModal",title:"Create New Client",ref_key:"modal",ref:y,onOpened:a[1]||(a[1]=o=>f.value?.focus())},{body:S(()=>[e("div",fe,[a[3]||(a[3]=e("label",{for:"clientName",class:"form-label small text-muted text-uppercase fw-bold"},"Client Name",-1)),e("div",ve,[a[2]||(a[2]=e("span",{class:"input-group-text"},[e("i",{class:"fas fa-user"})],-1)),D(e("input",{type:"text",class:z(["form-control",{"is-invalid":n.value&&!_.value}]),id:"clientName","onUpdate:modelValue":a[0]||(a[0]=o=>n.value=o),placeholder:"e.g. laptop-user",maxlength:"64",autocomplete:"off",onKeyup:O(h,["enter"]),ref_key:"inputRef",ref:f},null,34),[[q,n.value]])]),n.value&&!_.value?(r(),c("div",me," Letters, digits, dashes and underscores only; the first character must be a letter or a digit. ")):C("",!0),a[4]||(a[4]=e("div",{class:"form-text mt-2 text-muted small"},[e("i",{class:"fas fa-info-circle me-1"}),k(" Use only alphanumeric characters, dashes, or underscores. ")],-1))])]),footer:S(()=>[e("button",{type:"button",class:"btn-action btn-action-secondary",onClick:N},"Cancel"),e("button",{type:"button",class:"btn-action btn-action-save",onClick:h,disabled:!_.value}," Create Client ",8,_e)]),_:1},512))}},I={__name:"StatusBadge",props:{profile:{type:Object,required:!0}},setup(d){const u=d,x=g(()=>{const m=u.profile;return m.is_revoked?{label:"Revoked",cls:"status-expired",icon:"fa-ban"}:m.is_expired?{label:"Expired",cls:"status-expired",icon:"fa-times-circle"}:m.days_remaining!=null&&m.days_remaining<=30?{label:"Expiring Soon",cls:"status-warning",icon:"fa-exclamation-triangle"}:{label:"Active",cls:"status-valid",icon:"fa-check-circle"}});return(m,y)=>(r(),c("span",{class:z(["status-badge",x.value.cls])},[e("i",{class:z(["fas me-1",x.value.icon])},null,2),k(i(x.value.label),1)],2))}},ye={class:"d-flex align-items-center gap-2 flex-wrap"},ge={class:"modal-title fw-bold mb-0",style:{color:"var(--text-heading)"}},xe={key:0},he={class:"profile-meta"},ke={key:0,class:"text-muted"},Ce={class:"certificate-file text-muted small text-break mt-0"},we={class:"form-text text-end"},$e=["disabled"],Ne={__name:"ProfileDetailsModal",emits:["save"],setup(d,{expose:u,emit:x}){const m=x,y=v(null),n=v(null),f=v(""),w=g(()=>f.value!==(n.value?.note||"")),_=g(()=>{const a=n.value?.days_remaining;return a==null?"":a>0?`${a} d`:"expired"}),$=a=>{if(!a)return"N/A";const o=new Date(a);if(isNaN(o))return a;const A=U=>String(U).padStart(2,"0");return`${o.getFullYear()}-${A(o.getMonth()+1)}-${A(o.getDate())} ${A(o.getHours())}:${A(o.getMinutes())}`},N=a=>{n.value=a,f.value=a.note||"",y.value.show()},h=()=>{y.value.hide()},b=()=>{m("save",{id:n.value.id,note:f.value}),h()};return u({open:N,close:h}),(a,o)=>(r(),F(W,{id:"profileDetailsModal",title:"Profile Details",ref_key:"modal",ref:y},{header:S(()=>[e("div",ye,[e("h5",ge,i(n.value?.username),1),n.value?(r(),F(I,{key:0,profile:n.value},null,8,["profile"])):C("",!0)])]),body:S(()=>[n.value?(r(),c("div",xe,[e("dl",he,[o[2]||(o[2]=e("dt",null,"Created",-1)),e("dd",null,i($(n.value.created_at)),1),o[3]||(o[3]=e("dt",null,"Expires",-1)),e("dd",null,[k(i($(n.value.expiration_date)),1),_.value?(r(),c("span",ke," ("+i(_.value)+")",1)):C("",!0)]),n.value.revoked_at?(r(),c(T,{key:0},[o[1]||(o[1]=e("dt",null,"Revoked",-1)),e("dd",null,i($(n.value.revoked_at)),1)],64)):C("",!0),o[4]||(o[4]=e("dt",null,"File",-1)),e("dd",Ce,i(n.value.file_path||"N/A"),1)]),o[5]||(o[5]=e("label",{for:"profileNote",class:"form-label small text-muted text-uppercase fw-bold"},"Note",-1)),D(e("textarea",{class:"form-control",id:"profileNote",rows:"3",maxlength:"1000","onUpdate:modelValue":o[0]||(o[0]=A=>f.value=A),placeholder:"Add a note about this profile..."},null,512),[[q,f.value]]),e("div",we,i(f.value.length)+" / 1000",1)])):C("",!0)]),footer:S(()=>[e("button",{type:"button",class:"btn-action btn-action-secondary",onClick:h},"Close"),e("button",{type:"button",class:"btn-action btn-action-save",onClick:b,disabled:!w.value},"Save",8,$e)]),_:1},512))}},Q=(d,u)=>{d._noteTooltip=new pe(d,{title:u,placement:"top",container:"body",html:!1,trigger:"hover",customClass:"note-tooltip"})},G=d=>{d._noteTooltip?.dispose(),d._noteTooltip=null},Ae=d=>d._noteTooltip?.hide(),J={mounted(d,u){d.addEventListener("click",()=>Ae(d)),u.value&&Q(d,u.value)},updLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{r as u,o as F,c as K,l as Q,k as r,e as t,t as n,w as V,g as k,v as J,h as q,d,m as U,T as O,j as G,p as H,b as W,q as X,f as _,s as g,x as Y,y as I,F as N,i as E,z as Z}from"./index-CH6sppUl.js";import{u as tt}from"./useFormatters-CKGG-YVI.js";import{u as st}from"./useTrafficChart-DniISzMl.js";import{M as et}from"./vendor-ui-Dumif2LN.js";import"./vendor-charts-Bcjh2pZL.js";const lt={class:"modal-dialog modal-xl modal-dialog-centered"},at={class:"modal-content"},ot={class:"modal-header"},nt={class:"modal-title"},it={class:"modal-body"},rt={class:"chart-controls"},dt={class:"d-flex align-items-center gap-2"},ut={class:"d-flex align-items-center gap-3 bg-white-custom px-3 py-1 border rounded"},ct={class:"d-flex align-items-center"},vt={class:"toggle-wrapper me-2"},mt={class:"toggle-switch"},pt={class:"text-main user-select-none",style:{cursor:"pointer"},for:"vizToggle"},_t={class:"modal-chart-container"},ft={key:0,class:"position-absolute top-50 start-50 translate-middle"},yt={__name:"HistoryModal",setup(c,{expose:f}){const{fetchClientHistory:h}=G(),M=u(null),R=u(null),A=u(""),m=u("24h"),x=u(!1),C=u(!1);let y=null,b=null,i=0;const D=st(R,{maxPoints:48}),$=w=>{A.value=w,m.value="24h",x.value=!1,y?.show(),S()},T=()=>{y?.hide()},S=async()=>{if(!A.value)return;const w=++i;C.value=!0;try{const a=await h(A.value,m.value);if(w!==i)return;a.success&&a.data.history?(b=a.data.history.map(v=>({timestamp:v.timestamp,bytes_received:v.bytes_received,bytes_sent:v.bytes_sent,rx_rate_mbps:v.bytes_received_rate_mbps,tx_rate_mbps:v.bytes_sent_rate_mbps})),B()):(b=[],D.destroy())}catch(a){w===i&&console.error(a)}finally{w===i&&(C.value=!1)}},B=()=>{b&&D.render(b,{range:m.value,speedMode:x.value})};return F(()=>{y=new et(M.value),M.value.addEventListener("hidden.bs.modal",()=>{i++,C.value=!1,b=null,D.destroy()})}),K(()=>{i++,y?.dispose()}),f({open:$,close:T}),(w,a)=>(r(),Q(O,{to:"body"},[t("div",{class:"modal fade",id:"historyModal",tabindex:"-1","aria-hidden":"true",ref_key:"modalRef",ref:M},[t("div",lt,[t("div",at,[t("div",ot,[t("h5",nt,[a[2]||(a[2]=t("i",{class:"fas fa-chart-area me-2 text-primary"},null,-1)),t("span",null,n(A.value),1)]),a[3]||(a[3]=t("button",{type:"button",class:"btn-close","data-bs-dismiss":"modal","aria-label":"Close"},null,-1))]),t("div",it,[t("div",rt,[t("div",dt,[a[5]||(a[5]=t("label",{class:"text-muted"},[t("i",{class:"far fa-clock me-1"}),k(" Range:")],-1)),V(t("select",{"onUpdate:modelValue":a[0]||(a[0]=v=>m.value=v),class:"form-select form-select-sm",style:{width:"auto","min-width":"200px"},onChange:S},[...a[4]||(a[4]=[t("option",{value:"1h"},"Last 1 Hour (30s agg)",-1),t("option",{value:"3h"},"Last 3 Hours (1m agg)",-1),t("option",{value:"24h"},"Last 24 Hours (15m agg)",-1),t("option",{value:"7d"},"Last 7 Days (1h agg)",-1),t("option",{value:"30d"},"Last 30 Days (6h agg)",-1)])],544),[[J,m.value]])]),t("div",ut,[a[7]||(a[7]=t("span",{class:"small fw-bold text-muted"},"Metric:",-1)),t("div",ct,[t("div",vt,[t("label",mt,[V(t("input",{type:"checkbox",id:"vizToggle","onUpdate:modelValue":a[1]||(a[1]=v=>x.value=v),onChange:B},null,544),[[q,x.value]]),a[6]||(a[6]=t("span",{class:"toggle-slider"},null,-1))])]),t("label",pt,n(x.value?"Speed (Mbps)":"Data Volume"),1)])])]),t("div",_t,[t("canvas",{ref_key:"chartCanvas",ref:R},null,512),C.value?(r(),d("div",ft,[...a[8]||(a[8]=[t("div",{class:"spinner-border text-primary",role:"status"},null,-1)])])):U("",!0)])])])])],512)]))}},j=c=>c.sessions_count>1?`×${c.sessions_count}`:null,bt=(c,f)=>c.includes(f)?c.filter(h=>h!==f):[...c,f],gt=(c,f)=>c.sessions_count>1&&f.includes(c.common_name)?c.sessions||[]:[],ht={class:"stats-info mb-4"},xt={class:"stat-item"},wt={class:"stat-value"},kt={class:"stat-item"},Ct={class:"stat-value"},$t={class:"stat-item"},St={class:"stat-value"},Mt={class:"stat-item"},At={class:"stat-value"},Dt={class:"d-flex justify-content-between align-items-center mb-3 flex-wrap gap-3"},Lt={class:"d-flex gap-3 align-items-center flex-wrap"},Nt={class:"sort-btn-group"},Tt={class:"input-group input-group-sm",style:{width:"250px"}},Bt={class:"d-flex align-items-center"},Rt={class:"toggle-wrapper me-2"},Ut={class:"toggle-switch"},Vt={class:"card"},Ht={class:"card-header d-flex justify-content-between align-items-center"},Et={class:"text-muted"},zt={class:"table-responsive"},It={class:"table table-hover mb-0"},jt={key:0,class:"fas fa-sort-down ms-1"},Ft={key:0,class:"fas fa-sort-down ms-1"},Kt={key:0},qt={key:1},Gt={class:"section-divider"},Pt={colspan:"8"},Qt=["onClick"],Jt={class:"small text-muted"},Ot=["aria-expanded","onClick"],Wt={class:"font-monospace small"},Xt={class:"font-monospace small"},Yt={class:"font-monospace small"},Zt={key:1,class:"text-muted opacity-25"},ts={class:"font-monospace small"},ss={key:1,class:"text-muted opacity-25"},es={class:"small text-muted"},ls={class:"small text-muted ps-4"},as={class:"small text-muted"},os={class:"small text-muted",colspan:"2"},ns={class:"font-monospace small"},is={class:"font-monospace smallLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
import{M as B}from"./vendor-ui-jlFFG6nm.js";import{r as t,o as M,b as $,l as C,k as u,d as e,y as g,e as S,c as k,x as w,K as p,T as z,t as _,m as y}from"./index-BsVv6gaD.js";const T=["id"],E={class:"modal-content"},L={class:"modal-header border-0 pb-0"},N={class:"modal-title fw-bold",style:{color:"var(--text-heading)"}},R={class:"modal-body"},V={key:0,class:"modal-footer border-0 pt-0"},q={__name:"BaseModal",props:{id:{type:String,required:!0},title:{type:String,default:""},size:{type:String,default:""}},emits:["close","opened","closed"],setup(d,{expose:f,emit:b}){const v=d,o=b,s=t(null);let a=null;const i=v.size||"",c=()=>{a?.show()},r=()=>{a?.hide()};return M(()=>{a=new B(s.value),s.value.addEventListener("shown.bs.modal",()=>{o("opened")}),s.value.addEventListener("hidden.bs.modal",()=>{o("closed"),o("close")})}),$(()=>{a?.dispose()}),f({show:c,hide:r}),(n,m)=>(u(),C(z,{to:"body"},[e("div",{class:"modal fade",id:d.id,tabindex:"-1","aria-hidden":"true",ref_key:"modalRef",ref:s},[e("div",{class:g(["modal-dialog modal-dialog-centered",S(i)])},[e("div",E,[e("div",L,[p(n.$slots,"header",{},()=>[e("h5",N,_(d.title),1)]),m[0]||(m[0]=e("button",{type:"button",class:"btn-close","data-bs-dismiss":"modal","aria-label":"Close"},null,-1))]),e("div",R,[p(n.$slots,"body")]),n.$slots.footer?(u(),k("div",V,[p(n.$slots,"footer")])):w("",!0)])],2)],8,T)]))}},A={class:"text-main",style:{"white-space":"pre-line"}},j={__name:"ConfirmModal",emits:["confirm"],setup(d,{expose:f,emit:b}){const v=b,o=t(null),s=t(""),a=t(""),i=t("Confirm"),c=t("btn-action-danger"),r=t(!0),n=t(null),m=l=>{s.value=l.title||"Are you sure?",a.value=l.message||"",i.value=l.confirmText||"Confirm",c.value=l.confirmBtnClass||"btn-action-danger",r.value=l.showCancel!==!1,n.value=l.data||null,o.value.show()},h=()=>{o.value.hide()},x=()=>{v("confirm",n.value),h()};return f({open:m,close:h}),(l,D)=>(u(),C(q,{id:"confirmModal",title:s.value,ref_key:"modal",ref:o},{body:y(()=>[e("p",A,_(a.value),1)]),footer:y(()=>[r.value?(u(),k("button",{key:0,type:"button",class:"btn-action btn-action-secondary",onClick:h},"Cancel")):w("",!0),e("button",{type:"button",class:g(["btn-action",c.value]),onClick:x},_(i.value),3)]),_:1},8,["title"]))}};export{q as _,j as a};
|
||||
@@ -0,0 +1 @@
|
||||
import{M as $}from"./vendor-ui-Dumif2LN.js";import{r as o,p as M,o as S,c as z,l as C,k as u,e,s as g,d as k,m as w,K as p,T,t as _,L as E,A as y}from"./index-CH6sppUl.js";const L=["id"],A={class:"modal-content"},I={class:"modal-header border-0 pb-0"},N={class:"modal-title fw-bold",style:{color:"var(--text-heading)"}},R={class:"modal-body"},V={key:0,class:"modal-footer border-0 pt-0"},q={__name:"BaseModal",props:{id:{type:String,required:!0},title:{type:String,default:""},size:{type:String,default:""}},emits:["opened","closed"],setup(d,{expose:f,emit:v}){const b=d,i=v,t=o(null);let s=null;const c=M(()=>b.size||""),r=()=>{s?.show()},m=()=>{s?.hide()};return S(()=>{s=new $(t.value),t.value.addEventListener("shown.bs.modal",()=>{i("opened")}),t.value.addEventListener("hidden.bs.modal",()=>{i("closed")})}),z(()=>{s?.dispose()}),f({show:r,hide:m}),(a,l)=>(u(),C(T,{to:"body"},[e("div",{class:"modal fade",id:d.id,tabindex:"-1","aria-hidden":"true",ref_key:"modalRef",ref:t},[e("div",{class:g(["modal-dialog modal-dialog-centered",c.value])},[e("div",A,[e("div",I,[p(a.$slots,"header",{},()=>[e("h5",N,_(d.title),1)]),l[0]||(l[0]=e("button",{type:"button",class:"btn-close","data-bs-dismiss":"modal","aria-label":"Close"},null,-1))]),e("div",R,[p(a.$slots,"body")]),a.$slots.footer?(u(),k("div",V,[p(a.$slots,"footer")])):w("",!0)])],2)],8,L)]))}},D={class:"text-main",style:{"white-space":"pre-line"}},F={__name:"ConfirmModal",emits:["confirm"],setup(d,{expose:f,emit:v}){const b=`confirm-${E()}`,i=v,t=o(null),s=o(""),c=o(""),r=o("Confirm"),m=o("btn-action-danger"),a=o(!0),l=o(null),x=n=>{s.value=n.title||"Are you sure?",c.value=n.message||"",r.value=n.confirmText||"Confirm",m.value=n.confirmBtnClass||"btn-action-danger",a.value=n.showCancel!==!1,l.value=n.data||null,t.value.show()},h=()=>{t.value.hide()},B=()=>{i("confirm",l.value),h()};return f({open:x,close:h}),(n,K)=>(u(),C(q,{id:b,title:s.value,ref_key:"modal",ref:t},{body:y(()=>[e("p",D,_(c.value),1)]),footer:y(()=>[a.value?(u(),k("button",{key:0,type:"button",class:"btn-action btn-action-secondary",onClick:h},"Cancel")):w("",!0),e("button",{type:"button",class:g(["btn-action",m.value]),onClick:B},_(r.value),3)]),_:1},8,["title"]))}};export{q as _,F as a};
|
||||
@@ -1 +0,0 @@
|
||||
import{a as I,r as P,s as m,o as A,b as T,c,d as t,C as D,x as N,w as l,q as a,v as V,h as B,g as w,t as R,j as L,B as M,z as O,k as p}from"./index-BsVv6gaD.js";import"./vendor-charts-Bcjh2pZL.js";import"./vendor-ui-jlFFG6nm.js";const G={class:"config-wrapper"},j={class:"config-card"},F={class:"config-row"},Q={class:"config-col"},Y={class:"config-col"},H={class:"config-row"},X={class:"config-col",style:{"max-width":"50%"}},J={class:"select-container"},W={class:"config-row"},Z={class:"config-col"},h={class:"config-col"},ss={class:"config-row"},ts={class:"config-col"},es={class:"config-col"},ns={class:"config-row"},is={class:"config-col"},ls={class:"config-col"},as={class:"config-row"},os={class:"config-col"},rs={class:"select-container"},us={class:"config-col"},ds={class:"number-input-container"},cs={class:"number-input-controls"},ps={class:"config-row"},fs={class:"config-col"},ys={class:"number-input-container"},vs={class:"number-input-controls"},gs={class:"config-col"},bs={class:"number-input-container"},_s={class:"number-input-controls"},ms={class:"config-row"},ws={class:"config-col"},Cs={class:"number-input-container"},ks={class:"number-input-controls"},xs={class:"config-col"},qs={class:"toggle-wrapper"},Is={class:"toggle-switch"},Ps={class:"btn-action-group"},Vs=["disabled"],zs=["disabled","title"],Us={key:0,class:"fas fa-spinner fa-spin"},Ss={key:1,class:"fas fa-play-circle"},Ks=["disabled"],Es={key:0,class:"fas fa-spinner fa-spin"},$s={key:1,class:"fas fa-trash-alt"},As={key:0,class:"config-label"},Rs={__name:"PKIConfig",setup(Ts){const{profilesApiClient:f}=L(),z=M(),{refresh:C}=O(),n=I({fqdn_ca:"",fqdn_server:"",easyrsa_dn:"cn_only",easyrsa_req_country:"",easyrsa_req_province:"",easyrsa_req_city:"",easyrsa_req_org:"",easyrsa_req_email:"",easyrsa_req_ou:"",easyrsa_key_size:2048,easyrsa_ca_expire:null,easyrsa_cert_expire:null,easyrsa_cert_renew:null,easyrsa_crl_days:null,easyrsa_batch:!0}),r=P(!1),u=P(""),o=I({state:"idle",step:null,initialized:!1,error:null}),g=m(()=>o.state==="running"||u.value==="init"),b=m(()=>r.value||g.value),U={"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..."},S=m(()=>U[o.step]||"Initializing PKI...");let y=null;const d=(i,s="success")=>z.show(i,s),K=async()=>{try{const s=(await f.get("/config",{params:{section:"pki"}})).data,e=s.pki?s.pki:s;Object.keys(e).forEach(_=>{n.hasOwnProperty(_)&&(n[_]=e[_])})}catch(i){console.error(i),d("Failed to load PKI config from Management API.","error")}},k=()=>{y&&(clearInterval(y),y=null)},x=()=>{y||(y=setInterval(()=>v(),3e3))},v=async(i=!1)=>{const s=o.state==="running";try{const e=await f.get("/system/init/status");Object.assign(o,e.data)}catch(e){console.error(e);return}if(o.state==="running"){x();return}k(),s&&C(),s&&o.state==="done"?d("PKI initialized successfully!","success"):(s||i)&&o.state==="error"&&d(`Error initializing: ${o.error}`,"error")},q=async()=>{r.value=!0,u.value="save";try{await f.put("/config/pki",n),d("Configuration saved successfully!","success")}catch(i){d(`Error saving: ${i.message}`,"error")}finally{r.value=!1,u.value=""}},E=async()=>{if(confirm("Are you sure you want to Initialize system? This will start the PKI initialization process.")){r.value=!0,u.value="init";try{await f.post("/system/init"),o.state="running",x()}catch(i){i.response&&i.response.status===409?await v():d(`Error initializing: ${i.response?.data?.detail||i.message}`,"error")}finally{r.value=!1,u.value=""}}},$=async()=>{if(confirm("Are you sure you want to CLEAR PKI? This will delete all certificates and cannot be undone.")){r.value=!0,u.value="clear";try{const s=(await f.delete("/system/pki")).data;d(s.message||"PKI cleared successfully!","warning"),await v(),C()}catch(i){d(`Error clearing PKI: ${i.response?.data?.detail||i.message}`,"error")}finally{r.value=!1,u.value=""}}};return A(()=>{K(),v(!0)}),T(k),(i,s)=>(p(),c("div",G,[t("div",j,[s[58]||(s[58]=t("div",{class:"config-header"},[t("h1",null,"PKI Infrastructure Configuration")],-1)),t("form",{onSubmit:D(q,["prevent"])},[t("div",F,[t("div",Q,[s[23]||(s[23]=t("label",{class:"config-label"},"FQDN: CA Cert CN",-1)),l(t("input",{type:"text",class:"config-input","onUpdate:modelValue":s[0]||(s[0]=e=>n.fqdn_ca=e)},null,512),[[a,n.fqdn_ca]])]),t("div",Y,[s[24]||(s[24]=t("label",{class:"config-label"},"FQDN: Server Cert CN",-1)),l(t("input",{type:"text",class:"config-input","onUpdate:modelValue":s[1]||(s[1]=e=>n.fqdn_server=e)},null,512),[[a,n.fqdn_server]])])]),s[55]||(s[55]=t("div",{class:"config-divider"},null,-1)),t("div",H,[t("div",X,[s[27]||(s[27]=t("label",{class:"config-label"},"EASYRSA DN",-1)),t("div",J,[l(t("select",{class:"config-select","onUpdate:modelValue":s[2]||(s[2]=e=>n.easyrsa_dn=e)},[...s[25]||(s[25]=[t("option",{value:"cn_only"},"CN_ONLY",-1),t("option",{value:"org"},"ORG",-1)])],512),[[V,n.easyrsa_dn]]),s[26]|Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{a as V,r as g,p as w,o as O,c as R,d as c,e,q as K,z as L,m as j,w as l,x as a,v as U,h as G,g as C,t as Y,j as F,C as Q,B as H,k as p}from"./index-CH6sppUl.js";import{a as S}from"./ConfirmModal-XwuF5iM0.js";import"./vendor-ui-Dumif2LN.js";const X={class:"config-wrapper"},J={class:"config-card"},W={class:"config-row"},Z={class:"config-col"},h={class:"config-col"},ss={class:"config-row"},es={class:"config-col",style:{"max-width":"50%"}},ts={class:"select-container"},ns={class:"config-row"},is={class:"config-col"},ls={class:"config-col"},as={class:"config-row"},os={class:"config-col"},rs={class:"config-col"},us={class:"config-row"},ds={class:"config-col"},cs={class:"config-col"},ps={class:"config-row"},fs={class:"config-col"},ys={class:"select-container"},vs={class:"config-col"},gs={class:"number-input-container"},bs={class:"number-input-controls"},ms={class:"config-row"},_s={class:"config-col"},ws={class:"number-input-container"},Cs={class:"number-input-controls"},ks={class:"config-col"},xs={class:"number-input-container"},Is={class:"number-input-controls"},qs={class:"config-row"},Ps={class:"config-col"},zs={class:"number-input-container"},Vs={class:"number-input-controls"},Ks={class:"config-col"},Us={class:"toggle-wrapper"},Ss={class:"toggle-switch"},Es={class:"btn-action-group"},Ts=["disabled"],$s=["disabled","title"],As={key:0,class:"fas fa-spinner fa-spin"},Bs={key:1,class:"fas fa-play-circle"},Ms=["disabled"],Ns={key:0,class:"fas fa-spinner fa-spin"},Ds={key:1,class:"fas fa-trash-alt"},Os={key:0,class:"config-label"},Ys={__name:"PKIConfig",setup(Rs){const{profilesApiClient:f}=F(),E=Q(),{refresh:k}=H(),n=V({fqdn_ca:"",fqdn_server:"",easyrsa_dn:"cn_only",easyrsa_req_country:"",easyrsa_req_province:"",easyrsa_req_city:"",easyrsa_req_org:"",easyrsa_req_email:"",easyrsa_req_ou:"",easyrsa_key_size:2048,easyrsa_ca_expire:null,easyrsa_cert_expire:null,easyrsa_cert_renew:null,easyrsa_crl_days:null,easyrsa_batch:!0}),x=g(null),I=g(null),r=g(!1),u=g(""),o=V({state:"idle",step:null,initialized:!1,error:null}),b=w(()=>o.state==="running"||u.value==="init"),m=w(()=>r.value||b.value),T={"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..."},$=w(()=>T[o.step]||"Initializing PKI...");let y=null;const d=(i,s="success")=>E.show(i,s),A=async()=>{try{const s=(await f.get("/config",{params:{section:"pki"}})).data,t=s.pki?s.pki:s;Object.keys(t).forEach(_=>{Object.hasOwn(n,_)&&(n[_]=t[_])})}catch(i){console.error(i),d("Failed to load PKI config from Management API.","error")}},q=()=>{y&&(clearInterval(y),y=null)},P=()=>{y||(y=setInterval(()=>v(),3e3))},v=async(i=!1)=>{const s=o.state==="running";try{const t=await f.get("/system/init/status");Object.assign(o,t.data)}catch(t){console.error(t);return}if(o.state==="running"){P();return}q(),s&&k(),s&&o.state==="done"?d("PKI initialized successfully!","success"):(s||i)&&o.state==="error"&&d(`Error initializing: ${o.error}`,"error")},z=async()=>{r.value=!0,u.value="save";try{await f.put("/config/pki",n),d("Configuration saved successfully!","success")}catch(i){d(`Error saving: ${i.message}`,"error")}finally{r.value=!1,u.value=""}},B=()=>{x.value.open({title:"Initialize PKI?",message:"Are you sure you want to initialize the system? This will start the PKI initialization process.",confirmText:"Yes, initialize",confirmBtnClass:"btn-action-primary"})},M=async()=>{r.value=!0,u.value="init";try{await f.post("/system/init"),o.state="running",P()}catch(i){i.response&&i.response.status===409?await v():d(`Error initializing: ${i.response?.data?.detail||i.message}`,"error")}finally{r.value=!1,u.value=""}},N=()=>{I.value.open({title:"Clear PKI?",message:"Are you sure you want to CLEAR the PKI? This will delete all certificates and cannot be undone.",confirmText:"Yes, clear",confirmBtnClass:"btn-action-danger"})},D=async()=>{r.value=!0,u.value="clear";try{const s=(await f.delete("/system/pki")).data;d(s.message||"PKI cleared successfully!","warning"),await v(),k()}catch(i){d(`Error clearing PKI: ${i.response?.data?.detail||i.message}`,"error")}finally{r.value=!1,u.value=""}};return O(()=>{A(),v(!0)}),R(q),(i,s)=>(p(),c("div",X,[e("div",J,[s[58]||(s[58]=e("div",{class:"config-header"},[e("h1",null,"PKI Infrastructure Configuration")],-1)),e("form",{onSubmit:L(z,["prevent"])},[e("div",W,[e("div",Z,[s[23]||(s[23]=e("label",{class:"config-label"},"FQDN: CA Cert CN",-1)),l(e("input",{type:"text",class:"config-input","onUpdate:modelValue":s[0]||(s[0]=t=>n.fqdn_ca=t)},null,512),[[a,n.fqdn_ca]])]),e("div",h,[s[24]||(s[24]=e("label",{class:"config-label"},"FQDN: Server Cert CN",-1)),l(e("input",{type:"text",class:"config-input","onUpdate:modelValue":s[1]||(s[1]=t=>n.fqdn_server=t)},null,512),[[a,n.fqdn_server]])])]),s[55]||(s[55]=e("div",{class:"config-divider"},null,-1)),e("div",ss,[e("div",es,[s[27]||(s[27]=e("label",{class:"confiLine truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{p as w,B as M,a as x,r as f,o as A,c as I,d as o,e as t,q as N,t as c,n as P,s as U,f as h,g as _,j as B,k as i,C as j}from"./index-CH6sppUl.js";import{a as T}from"./ConfirmModal-XwuF5iM0.js";import"./vendor-ui-Dumif2LN.js";const V={class:"config-wrapper"},z={class:"config-card"},F={class:"stats-grid mb-4"},O={class:"stat-item full-width cpu-progress"},R={class:"stat-label d-flex justify-content-between"},D={class:"progress"},E=["aria-valuenow"],L={class:"stat-item"},q={class:"d-flex align-items-center"},H={class:"stat-item"},K={class:"stat-value"},Y={class:"stat-item"},G={class:"stat-value"},J={class:"stat-item"},Q={class:"stat-value monospace"},W={class:"btn-action-group justify-content-center"},X=["disabled","title"],Z={key:0,class:"fas fa-spinner fa-spin"},ss={key:1,class:"fas fa-play"},ts=["disabled","title"],es={key:0,class:"fas fa-spinner fa-spin"},as={key:1,class:"fas fa-sync-alt"},ns=["disabled"],os={key:0,class:"fas fa-spinner fa-spin"},is={key:1,class:"fas fa-stop"},ds={__name:"ServerManagement",setup(rs){const{profilesApiClient:b}=B(),S=j(),{status:r,refresh:k}=M(),m=w(()=>r.server_ready?"":r.pki_ready&&r.missing.length?`Missing server files: ${r.missing.join(", ")}`:"Initialize PKI first"),a=x({status:"unknown",pid:null,cpu_percent:0,memory_mb:0,uptime:null}),g=f(null),n=f(!1),l=f("");let d=null;const y=(e,s="success")=>S.show(e,s),p=async()=>{try{const e=await b.get("/server/process/stats");Object.assign(a,e.data)}catch(e){console.error("Failed to fetch stats:",e)}},C={start:"btn-action-primary",restart:"btn-action-save",stop:"btn-action-danger"},v=e=>{g.value.open({title:`${e.charAt(0).toUpperCase()}${e.slice(1)} the service?`,message:`Are you sure you want to ${e.toUpperCase()} the OpenVPN service?`,confirmText:`Yes, ${e}`,confirmBtnClass:C[e],data:e})},$=async e=>{n.value=!0,l.value=e;try{const s=await b.post(`/server/process/${e}`);y(s.data.message||`Service ${e} successful`,"success"),setTimeout(p,1e3)}catch(s){const u=s.response?.data?.detail||s.message;y(`Failed to ${e}: ${u}`,"error")}finally{n.value=!1,l.value=""}};return A(()=>{k(),p(),d=setInterval(p,5e3)}),I(()=>{d&&clearInterval(d)}),(e,s)=>(i(),o("div",V,[t("div",z,[s[11]||(s[11]=t("div",{class:"config-header"},[t("h1",null,"Server Process Management")],-1)),t("div",F,[t("div",O,[t("label",R,[s[3]||(s[3]=t("span",null,"CPU Usage",-1)),t("span",null,c(a.cpu_percent)+"%",1)]),t("div",D,[t("div",{class:"progress-bar progress-bar-brand",role:"progressbar",style:P({width:Math.min(a.cpu_percent,100)+"%"}),"aria-valuenow":a.cpu_percent,"aria-valuemin":"0","aria-valuemax":"100"},null,12,E)])]),t("div",L,[s[4]||(s[4]=t("label",{class:"stat-label"},"Status",-1)),t("div",q,[t("span",{class:U(["status-badge","status-"+(a.status==="running"?"active":"revoked")])},c(a.status.toUpperCase()),3)])]),t("div",H,[s[5]||(s[5]=t("label",{class:"stat-label"},"Process ID",-1)),t("div",K,c(a.pid||"N/A"),1)]),t("div",Y,[s[6]||(s[6]=t("label",{class:"stat-label"},"Memory (RSS)",-1)),t("div",G,c(a.memory_mb)+" MB",1)]),t("div",J,[s[7]||(s[7]=t("label",{class:"stat-label"},"Uptime",-1)),t("div",Q,c(a.uptime||"N/A"),1)])]),t("div",W,[t("button",{type:"button",class:"btn-action btn-action-primary",onClick:s[0]||(s[0]=u=>v("start")),disabled:n.value||a.status==="running"||!h(r).server_ready,title:m.value},[n.value&&l.value==="start"?(i(),o("i",Z)):(i(),o("i",ss)),s[8]||(s[8]=_(" Start Service ",-1))],8,X),t("button",{type:"button",class:"btn-action btn-action-save",onClick:s[1]||(s[1]=u=>v("restart")),disabled:n.value||!h(r).server_ready,title:m.value},[n.value&&l.value==="restart"?(i(),o("i",es)):(i(),o("i",as)),s[9]||(s[9]=_(" Restart Service ",-1))],8,ts),t("button",{type:"button",class:"btn-action btn-action-danger",onClick:s[2]||(s[2]=u=>v("stop")),disabled:n.value||a.status!=="running"},[n.value&&l.value==="stop"?(i(),o("i",os)):(i(),o("i",is)),s[10]||(s[10]=_(" Stop Service ",-1))],8,ns)])]),N(T,{ref_key:"confirmModal",ref:g,onConfirm:$},null,512)]))}};export{ds as default};
|
||||
@@ -1 +0,0 @@
|
||||
import{s as S,z as w,a as C,r as g,o as M,b as $,c as o,d as t,t as c,n as P,y as x,e as y,g as _,j as I,B as U,k as i}from"./index-BsVv6gaD.js";import"./vendor-charts-Bcjh2pZL.js";import"./vendor-ui-jlFFG6nm.js";const j={class:"config-wrapper"},A={class:"config-card"},B={class:"stats-grid mb-4"},N={class:"stat-item full-width cpu-progress"},z={class:"stat-label d-flex justify-content-between"},T={class:"progress"},V=["aria-valuenow"],D={class:"stat-item"},F={class:"d-flex align-items-center"},O={class:"stat-item"},R={class:"stat-value"},E={class:"stat-item"},H={class:"stat-value"},K={class:"stat-item"},L={class:"stat-value monospace"},q={class:"btn-action-group justify-content-center"},G=["disabled","title"],J={key:0,class:"fas fa-spinner fa-spin"},Q={key:1,class:"fas fa-play"},W=["disabled","title"],X={key:0,class:"fas fa-spinner fa-spin"},Y={key:1,class:"fas fa-sync-alt"},Z=["disabled"],ss={key:0,class:"fas fa-spinner fa-spin"},ts={key:1,class:"fas fa-stop"},is={__name:"ServerManagement",setup(es){const{profilesApiClient:f}=I(),h=U(),{status:r,refresh:k}=w(),b=S(()=>r.server_ready?"":r.pki_ready&&r.missing.length?`Missing server files: ${r.missing.join(", ")}`:"Initialize PKI first"),a=C({status:"unknown",pid:null,cpu_percent:0,memory_mb:0,uptime:null}),n=g(!1),l=g("");let d=null;const m=(e,s="success")=>h.show(e,s),p=async()=>{try{const e=await f.get("/server/process/stats");Object.assign(a,e.data)}catch(e){console.error("Failed to fetch stats:",e)}},v=async e=>{if(confirm(`Are you sure you want to ${e.toUpperCase()} the OpenVPN service?`)){n.value=!0,l.value=e;try{const s=await f.post(`/server/process/${e}`);m(s.data.message||`Service ${e} successful`,"success"),setTimeout(p,1e3)}catch(s){const u=s.response?.data?.detail||s.message;m(`Failed to ${e}: ${u}`,"error")}finally{n.value=!1,l.value=""}}};return M(()=>{k(),p(),d=setInterval(p,5e3)}),$(()=>{d&&clearInterval(d)}),(e,s)=>(i(),o("div",j,[t("div",A,[s[11]||(s[11]=t("div",{class:"config-header"},[t("h1",null,"Server Process Management")],-1)),t("div",B,[t("div",N,[t("label",z,[s[3]||(s[3]=t("span",null,"CPU Usage",-1)),t("span",null,c(a.cpu_percent)+"%",1)]),t("div",T,[t("div",{class:"progress-bar progress-bar-brand",role:"progressbar",style:P({width:Math.min(a.cpu_percent,100)+"%"}),"aria-valuenow":a.cpu_percent,"aria-valuemin":"0","aria-valuemax":"100"},null,12,V)])]),t("div",D,[s[4]||(s[4]=t("label",{class:"stat-label"},"Status",-1)),t("div",F,[t("span",{class:x(["status-badge","status-"+(a.status==="running"?"active":"revoked")])},c(a.status.toUpperCase()),3)])]),t("div",O,[s[5]||(s[5]=t("label",{class:"stat-label"},"Process ID",-1)),t("div",R,c(a.pid||"N/A"),1)]),t("div",E,[s[6]||(s[6]=t("label",{class:"stat-label"},"Memory (RSS)",-1)),t("div",H,c(a.memory_mb)+" MB",1)]),t("div",K,[s[7]||(s[7]=t("label",{class:"stat-label"},"Uptime",-1)),t("div",L,c(a.uptime||"N/A"),1)])]),t("div",q,[t("button",{type:"button",class:"btn-action btn-action-primary",onClick:s[0]||(s[0]=u=>v("start")),disabled:n.value||a.status==="running"||!y(r).server_ready,title:b.value},[n.value&&l.value==="start"?(i(),o("i",J)):(i(),o("i",Q)),s[8]||(s[8]=_(" Start Service ",-1))],8,G),t("button",{type:"button",class:"btn-action btn-action-save",onClick:s[1]||(s[1]=u=>v("restart")),disabled:n.value||!y(r).server_ready,title:b.value},[n.value&&l.value==="restart"?(i(),o("i",X)):(i(),o("i",Y)),s[9]||(s[9]=_(" Restart Service ",-1))],8,W),t("button",{type:"button",class:"btn-action btn-action-danger",onClick:s[2]||(s[2]=u=>v("stop")),disabled:n.value||a.status!=="running"},[n.value&&l.value==="stop"?(i(),o("i",ss)):(i(),o("i",ts)),s[10]||(s[10]=_(" Stop Service ",-1))],8,Z)])])]))}};export{is as default};
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user