Compare commits

...
14 Commits
Author SHA1 Message Date
ayurishchevandClaude Sonnet 5.5 00eacbbca8 Docs: plan and summary for the average speed over 24 hours, API and data architecture notes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KC7BXv32Jwj8mY5sKX8u2F
2026-10-07 14:30:01 +03:00
ayurishchevandClaude Sonnet 5.5 b3466f9c61 History and Analytics: average speed from bytes for periods over 24 hours
The aggregate tables (stats_*) keep only bytes, and the queries returned 0 as speed, so the Speed
mode was empty for 7d and 30d. Speed is now the bucket average: bytes * 8 / 1e6 / bucket seconds;
for the current incomplete bucket the duration is min(bucket length, time since its start), at least
1 s. Series are labelled "RX Mbps (avg)" / "TX Mbps (avg)" for ranges over 24h. One test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KC7BXv32Jwj8mY5sKX8u2F
2026-10-07 14:28:02 +03:00
ayurishchevandClaude Sonnet 5.5 e364a40e4b Backup UI: plan and summary for the badges alignment
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KC7BXv32Jwj8mY5sKX8u2F
2026-10-07 14:11:32 +03:00
ayurishchevandClaude Sonnet 5.5 87d8bbcd8c Backup UI: align badges in the Destinations table to the top of the row
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KC7BXv32Jwj8mY5sKX8u2F
2026-10-07 14:10:31 +03:00
ayurishchevandClaude Sonnet 5.5 b61989bd22 UI delivery: plan, summary and docs (CSP origins, --csp-connect-extra, nginx-unprivileged)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:33:27 +03:00
ayurishchevandClaude Sonnet 5.5 3347fffe8e UI delivery, stage D: app-ui image on nginx-unprivileged (user nginx, port 8080)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:31:53 +03:00
ayurishchevandClaude Sonnet 5.5 71ea4c5945 UI delivery, stage C: npm ci in the all-in-one image build
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:29:45 +03:00
ayurishchevandClaude Sonnet 5.5 d5e83eaff5 UI delivery, stage B: single CSP with optional connect-src origins (OVPMON_CSP_CONNECT_EXTRA)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:28:30 +03:00
ayurishchevandClaude Sonnet 5.5 d38acd74de UI delivery, stage A: rebuild deploy/ui-dist from current APP_UI sources
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:19:27 +03:00
ayurishchevandClaude Sonnet 5.5 9443ab6fce UI review: docs, summary and plan
Summary of U1-U18, change log row, APP_UI README, UI architecture,
accepted risk of the token in localStorage.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:14:40 +03:00
ayurishchevandClaude Sonnet 5.5 32d6b0e525 UI review, stage 4: accessibility, product name, favicon, ESLint
Login: label for/id, autocomplete, inputmode for the 2FA code; clickable
table rows, headers and client links work from the keyboard. One product
name (OpenVPN Controller), own favicon (logo.svg) instead of vite.svg,
footer text fixed. Minimal ESLint config (npm run lint, clean).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:13:25 +03:00
ayurishchevandClaude Sonnet 5.5 897c82ab88 UI review, stage 3: cleanup, shared chart code, confirmations, routing
useTrafficChart composable replaces the duplicated chart code in Analytics
and HistoryModal; theme observer is released on unmount; blob URLs are
revoked. ConfirmModal gets a unique id; confirm() in Server/PKI and
SweetAlert2 in Account are replaced by ConfirmModal and toasts, sweetalert2
and sass removed. Separate authApiClient for /api/auth. 404 redirect, lazy
Clients, token-based isAuthenticated, theme from prefers-color-scheme set
before mount. BaseModal reactive size, NewClientModal name check and focus
on opened, HistoryModal ignores stale answers. Login.vue.bak, the dead
global axios interceptor and empty <p> removed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:10:41 +03:00
ayurishchevandClaude Sonnet 5.5 600119cdd1 UI review, stage 2: nginx security headers, gzip, cache; npm ci; no v-html
default.conf.template: X-Content-Type-Options, X-Frame-Options,
Referrer-Policy, CSP, gzip, immutable cache for /assets/, no-cache for
index.html and config.json, server_tokens off, drop proxy_pass_header.
Dockerfile uses npm ci, .dockerignore added (nginx stays root: the image
entrypoint and port 80 need it). Status badge is a component instead of
v-html.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:07:16 +03:00
ayurishchevandClaude Sonnet 5.5 b78de98f26 UI review, stage 1: 401 on /auth/*, expiring certs, VPN netmask, formatBytes
401 from change-password/change-username no longer logs the user out;
Analytics reads the plain /profiles array; VPN settings send vpn_netmask
with vpn_network (the API reset it to 255.255.255.0); formatBytes guards
null/NaN/negative; Certificates sorts 0 days correctly. Vitest added for
formatters, CIDR parsing and the 401 interceptor.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-07 13:05:55 +03:00
99 changed files with 3160 additions and 954 deletions

No files matched your search

+27 -3
View File
@@ -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:
@@ -322,8 +345,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 +500,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
+45
View File
@@ -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)
+6
View File
@@ -0,0 +1,6 @@
node_modules
dist
.vscode
.git
*.bak
*.log
+12 -4
View File
@@ -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
View File
@@ -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.
+51
View File
@@ -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
+40 -3
View File
@@ -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)
@@ -34,4 +71,4 @@ server {
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
+26
View File
@@ -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
View File
@@ -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>
+1594 -16
View File
File diff suppressed because it is too large. Load diff
+9 -4
View File
@@ -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
View File
@@ -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
View File
@@ -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,15 +205,10 @@ 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');
+5
View File
@@ -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;
+3 -4
View File
@@ -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');
});
});
+4 -2
View File
@@ -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);
+27 -137
View File
@@ -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 });
+14 -7
View File
@@ -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 '';
+27
View File
@@ -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>
+31 -18
View File
@@ -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';
}
}
return Promise.reject(error);
}
);
if (endSessionOn401) {
instance.interceptors.response.use(response => response, handleUnauthorized);
}
};
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,
+57
View File
@@ -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');
});
});
+6 -4
View File
@@ -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');
});
});
+43
View File
@@ -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());
}
+142
View File
@@ -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
View File
@@ -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);
+6 -2
View File
@@ -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: '/'
}
];
+34
View File
@@ -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;
}
+36
View File
@@ -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();
}
});
});
+29 -91
View File
@@ -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>
+34 -151
View File
@@ -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 => {
// 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;
});
kpi.expiringCerts = list.length;
expiringCertsList.value = list.sort((a,b) => (a.days_remaining || 0) - (b.days_remaining || 0));
}
// 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;
});
kpi.expiringCerts = list.length;
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,65 +281,18 @@ 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(() => {
@@ -419,7 +303,6 @@ onMounted(() => {
onUnmounted(() => {
if (intervalId) clearInterval(intervalId);
if (mainChartInstance) mainChartInstance.destroy();
if (pieChartInstance) pieChartInstance.destroy();
});
</script>
+5 -5
View File
@@ -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>
+9 -23
View File
@@ -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');
}
+4 -4
View File
@@ -52,10 +52,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>
@@ -80,7 +80,7 @@
</tr>
<tr v-for="c in group.items" :key="c.common_name">
<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>
@@ -126,7 +126,7 @@ import { useFormatters } from '../composables/useFormatters';
import HistoryModal from '../components/HistoryModal.vue';
import { useAppConfig } from '../composables/useAppConfig';
const { fetchStats, apiClient } = useApi();
const { fetchStats } = useApi();
const { formatBytes, formatRate, parseServerDate } = useFormatters();
const { config } = useAppConfig();
+14 -9
View File
@@ -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">&copy; 2026 Admin Dashboard</p>
<p class="small text-muted">&copy; 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
});
-251
View File
@@ -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">&copy; 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>
+25 -6
View File
@@ -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 {
+16 -2
View File
@@ -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;
+18 -18
View File
@@ -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');
+1 -1
View File
@@ -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`.
+4
View File
@@ -25,3 +25,7 @@ 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) |
+3
View File
@@ -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.
@@ -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
+1 -1
View File
@@ -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.
+4 -3
View File
@@ -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:
@@ -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.
+6 -3
View File
@@ -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
+18 -4
View File
@@ -7,13 +7,16 @@ 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
@@ -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).
+1 -1
View File
@@ -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 |
+3 -2
View File
@@ -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)
+13 -3
View File
@@ -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)"
+1
View File
@@ -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"
+44
View 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
+9 -2
View File
@@ -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)"
+52 -4
View File
@@ -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
+6 -1
View File
@@ -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;
+15 -2
View File
@@ -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"
@@ -480,7 +492,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 +522,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
View File
@@ -1 +1 @@
796072800fd2abd0a674c02ef1c626b796e587b263818d13f1159561c7a7d724
8d9379ee7d6e1c766f9c3ebd363a0ea9f504703683fbc9f05dcf7c5e07c6538a
@@ -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-BfAhXdi6.js";import{a as ce,_ as ee}from"./ConfirmModal-wSxjHDVn.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
@@ -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 @@
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-BfAhXdi6.js";import{u as X,g as G,C as W,a as q}from"./useTrafficChart-69f2EcZB.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
@@ -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-BfAhXdi6.js";import{u as Ze}from"./useFormatters-CKGG-YVI.js";import{_ as ye,a as te}from"./ConfirmModal-wSxjHDVn.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-BfAhXdi6.js";import{_ as W,a as ce}from"./ConfirmModal-wSxjHDVn.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 z,c as E,l as K,k as i,e as t,t as r,w as T,g as $,v as q,h as I,d,m as V,T as G,j,p as U,b as P,q as Q,f as C,s as b,x as J,y as H,F as N,i as B,z as O}from"./index-BfAhXdi6.js";import{u as W}from"./useFormatters-CKGG-YVI.js";import{u as X}from"./useTrafficChart-69f2EcZB.js";import{M as Y}from"./vendor-ui-Dumif2LN.js";import"./vendor-charts-Bcjh2pZL.js";const Z={class:"modal-dialog modal-xl modal-dialog-centered"},tt={class:"modal-content"},et={class:"modal-header"},st={class:"modal-title"},lt={class:"modal-body"},at={class:"chart-controls"},ot={class:"d-flex align-items-center gap-2"},nt={class:"d-flex align-items-center gap-3 bg-white-custom px-3 py-1 border rounded"},it={class:"d-flex align-items-center"},rt={class:"toggle-wrapper me-2"},dt={class:"toggle-switch"},ut={class:"text-main user-select-none",style:{cursor:"pointer"},for:"vizToggle"},ct={class:"modal-chart-container"},vt={key:0,class:"position-absolute top-50 start-50 translate-middle"},mt={__name:"HistoryModal",setup(F,{expose:R}){const{fetchClientHistory:h}=j(),x=u(null),D=u(null),w=u(""),m=u("24h"),y=u(!1),g=u(!1);let p=null,f=null,o=0;const k=X(D,{maxPoints:48}),A=_=>{w.value=_,m.value="24h",y.value=!1,p?.show(),S()},M=()=>{p?.hide()},S=async()=>{if(!w.value)return;const _=++o;g.value=!0;try{const l=await h(w.value,m.value);if(_!==o)return;l.success&&l.data.history?(f=l.data.history.map(c=>({timestamp:c.timestamp,bytes_received:c.bytes_received,bytes_sent:c.bytes_sent,rx_rate_mbps:c.bytes_received_rate_mbps,tx_rate_mbps:c.bytes_sent_rate_mbps})),L()):(f=[],k.destroy())}catch(l){_===o&&console.error(l)}finally{_===o&&(g.value=!1)}},L=()=>{f&&k.render(f,{range:m.value,speedMode:y.value})};return z(()=>{p=new Y(x.value),x.value.addEventListener("hidden.bs.modal",()=>{o++,g.value=!1,f=null,k.destroy()})}),E(()=>{o++,p?.dispose()}),R({open:A,close:M}),(_,l)=>(i(),K(G,{to:"body"},[t("div",{class:"modal fade",id:"historyModal",tabindex:"-1","aria-hidden":"true",ref_key:"modalRef",ref:x},[t("div",Z,[t("div",tt,[t("div",et,[t("h5",st,[l[2]||(l[2]=t("i",{class:"fas fa-chart-area me-2 text-primary"},null,-1)),t("span",null,r(w.value),1)]),l[3]||(l[3]=t("button",{type:"button",class:"btn-close","data-bs-dismiss":"modal","aria-label":"Close"},null,-1))]),t("div",lt,[t("div",at,[t("div",ot,[l[5]||(l[5]=t("label",{class:"text-muted"},[t("i",{class:"far fa-clock me-1"}),$(" Range:")],-1)),T(t("select",{"onUpdate:modelValue":l[0]||(l[0]=c=>m.value=c),class:"form-select form-select-sm",style:{width:"auto","min-width":"200px"},onChange:S},[...l[4]||(l[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),[[q,m.value]])]),t("div",nt,[l[7]||(l[7]=t("span",{class:"small fw-bold text-muted"},"Metric:",-1)),t("div",it,[t("div",rt,[t("label",dt,[T(t("input",{type:"checkbox",id:"vizToggle","onUpdate:modelValue":l[1]||(l[1]=c=>y.value=c),onChange:L},null,544),[[I,y.value]]),l[6]||(l[6]=t("span",{class:"toggle-slider"},null,-1))])]),t("label",ut,r(y.value?"Speed (Mbps)":"Data Volume"),1)])])]),t("div",ct,[t("canvas",{ref_key:"chartCanvas",ref:D},null,512),g.value?(i(),d("div",vt,[...l[8]||(l[8]=[t("div",{class:"spinner-border text-primary",role:"status"},null,-1)])])):V("",!0)])])])])],512)]))}},pt={class:"stats-info mb-4"},ft={class:"stat-item"},_t={class:"stat-value"},yt={class:"stat-item"},bt={class:"stat-value"},gt={class:"stat-item"},ht={class:"stat-value"},xt={class:"d-flex justify-content-between align-items-center mb-3 flex-wrap gap-3"},wt={class:"d-flex gap-3 align-items-center flex-wrap"},kt={class:"sort-btn-group"},Ct={class:"input-group input-group-sm",style:{width:"250px"}},$t={class:"d-flex align-items-center"},At={class:"toggle-wrapper me-2"},Mt={class:"toggle-switch"},St={class:"card"},Dt={class:"card-header d-flex justify-content-between align-items-center"},Lt={class:"text-muted"},Nt={class:"table-responsive"},Tt={class:"table table-hover mb-0"},Rt={key:0,class:"fas fa-sort-down ms-1"},Ut={key:0,class:"fas fa-sort-down ms-1"},Vt={key:0},Ht={key:1},Bt={class:"section-divider"},zt={colspan:"8"},Et=["onClick"],It={class:"small text-muted"},jt={class:"font-monospace small"},Ft={class:"font-monospace small"},Kt={class:"font-monospace small"},qt={key:1,class:"text-muted opacity-25"},Gt={class:"font-monospace small"},Pt={key:1,class:"text-muted opacity-25"},Qt={class:"small text-muted"},te={__name:"Clients",setup(F){const{fetchStats:R}=j(),{formatBytes:h,formatRate:x,parseServerDate:D}=W(),{config:w}=P(),m=u([]),y=u(!0),g=u("Updating..."),p=u(""),f=u(!1),o=u("sent"),k=u(null);let A=null;const M=U(()=>{let s=0,e=0,a=0;return m.value.forEach(v=>{s+=v.total_bytes_received||0,e+=v.total_bytes_sent||0,v.status==="Active"&&a++}),{totalReceived:s,totalSent:e,activeClients:a}}),S=U(()=>m.value.filter(s=>!(f.value&&s.status!=="ALine 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-BfAhXdi6.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-BfAhXdi6.js";import{a as S}from"./ConfirmModal-wSxjHDVn.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-BfAhXdi6.js";import{a as T}from"./ConfirmModal-wSxjHDVn.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};
@@ -0,0 +1 @@
import{a as A,r as V,D as E,o as R,B as j,d as a,f as B,e as t,q as O,g as k,A as z,E as K,m as x,w as i,v as q,x as p,h as b,F as U,i as F,z as G,j as X,C as H,k as r}from"./index-BfAhXdi6.js";const P=/^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;function J(c){const d=Number(c);if(c===""||c===null||!Number.isInteger(d)||d<0||d>32)return null;const u=d===0?0:4294967295<<32-d>>>0;return[24,16,8,0].map(v=>u>>>v&255).join(".")}function Q(c){if(typeof c!="string"||!P.test(c))return null;const d=c.split(".").reduce((m,n)=>(m<<8|Number(n))>>>0,0);let u=0;for(;u<32&&d&2147483648>>>u;)u++;const v=u===0?0:4294967295<<32-u>>>0;return d===v?u:null}function W(c){const d=String(c??"").trim(),[u,v,...m]=d.split("/");if(m.length||!P.test(u))return null;if(v===void 0)return{network:u,netmask:null};const n=J(v);return n?{network:u,netmask:n}:null}const Y={class:"config-wrapper"},Z={key:0,class:"config-card"},h={key:1,class:"config-card"},ss={class:"config-row"},ts={class:"config-col"},ns={class:"select-container"},es={class:"config-col"},os={class:"number-input-container"},ls={class:"number-input-controls"},is={class:"config-row"},as={class:"config-col"},rs={class:"config-col"},ds={class:"config-row"},us={class:"config-col"},ps={class:"number-input-container"},cs={class:"number-input-controls"},fs={class:"config-col"},vs={class:"number-input-container"},gs={class:"number-input-controls"},bs={class:"config-row"},ms={class:"config-col"},_s={class:"toggle-wrapper"},ys={class:"toggle-switch"},ks={key:0,class:"nested-box fade-in"},ws={class:"config-row mb-2"},Cs={class:"config-col"},xs={class:"list-container"},Ss=["onUpdate:modelValue"],Vs=["onClick"],Us={class:"config-row"},Fs={class:"config-col"},Ps={class:"toggle-wrapper"},Is={class:"toggle-switch"},Ds={key:1,class:"nested-box fade-in"},Ns={class:"config-row mb-2"},Ts={class:"config-col"},$s={class:"list-container"},Ls=["onUpdate:modelValue"],Ms=["onClick"],As={class:"config-row"},Es={class:"config-col"},Rs={class:"toggle-wrapper"},js={class:"toggle-switch"},Bs={class:"config-col"},Os={class:"toggle-wrapper"},zs={class:"toggle-switch"},Ks={class:"config-col"},qs={class:"toggle-wrapper"},Gs={class:"toggle-switch"},Xs={class:"config-row"},Hs={class:"config-col"},Js={class:"toggle-wrapper"},Qs={class:"toggle-switch"},Ws={key:2,class:"nested-box fade-in"},Ys={class:"config-row"},Zs={class:"config-col"},hs={class:"config-row mt-3"},st={class:"config-col"},tt={class:"config-row mt-4"},nt={class:"config-col"},et={class:"toggle-wrapper"},ot={class:"toggle-switch"},lt={key:3,class:"nested-box fade-in"},it={class:"config-row"},at={class:"config-col"},rt={class:"config-col"},dt={class:"number-input-container"},ut={class:"number-input-controls"},pt={class:"btn-action-group"},ct=["disabled"],ft={key:0,class:"fas fa-spinner fa-spin"},vt={key:1,class:"fas fa-save"},gt=["disabled"],bt={key:0,class:"fas fa-spinner fa-spin"},mt={key:1,class:"fas fa-rocket"},yt={__name:"VPNConfig",setup(c){const{profilesApiClient:d}=X(),u=H(),{status:v,refresh:m}=j(),n=A({protocol:"udp",port:1194,vpn_network:"",public_ip:"",tun_mtu:0,mssfix:0,tunnel_type:"FULL",split_routes:[],user_defined_dns:!1,dns_servers:[],duplicate_cn:!1,client_to_client:!1,crl_verify:!1,user_defined_cdscripts:!1,connect_script:"",disconnect_script:"",management_interface:!1,management_interface_address:"",management_port:7505}),w=V(!1),g=V(!1),_=V("");E(w,o=>{n.tunnel_type=o?"SPLIT":"FULL"});let S="";const y=(o,s="success")=>u.show(o,s),I=()=>n.split_routes.push(""),D=o=>n.split_routes.splice(o,1),N=()=>n.dns_servers.push(""),T=o=>n.dns_servers.splice(o,1),$=async()=>{try{const s=(await d.get("/config",{params:{section:"server"}})).data,l=s.server?s.server:s;if(Object.keys(l).forEach(e=>{Object.hasOwn(n,e)&&(e==="tunnel_type"&&(w.value=l[e]==="SPLIT"),n[e]=l[e])}),S=l.vpn_netmask||"",l.vpn_network&&l.vpn_netmask){const e=Q(l.vpn_netmask);e!==null&&(n.vpn_network=`${l.vpn_network}/${e}`)}}catch(o){console.error(o),y("Failed to load Server config from Management API.","error")}},L=async()=>{const o=W(n.vpn_network);if(!o){y("VPN subnet must be an IPv4 network in CIDR format, e.g. 172.20.1.0/24","error");return}g.value=!0,_.value="save";const s={...n};s.split_routes=s.split_routes.filter(l=>l&&l.trim()!==""),s.dns_servers=s.dns_servers.filter(l=>l&&l.trim()!==""),s.vpn_network=o.network,s.vpn_netmask=o.netmask||S||"255.255.255.0";try{await d.put("/config/server",s),S=s.vpn_netmask,y("Server configuration saved!","success")}catch(l){y(`Error saving: ${l.response?.data?.detail||l.message}`,"error")}finally{g.value=!1,_.value=""}},M=async()=>{g.value=!0,_.value="apply";try{const s=(await d.post("/server/configure")).data;y(s.message||"Configuration applied!","success")}catch(o){y(`Error applying: ${o.response?.data?.detail||o.message}`,"error"),m()}finally{g.value=!1,_.value=""}};return R(()=>{m(),$()}),(o,s)=>{const l=K("router-link");return r(),a("div",Y,[B(v).pki_ready?(r(),a("div",h,[s[75]||(s[75]=t("div",{class:"config-Line truncated
@@ -1 +0,0 @@
import{a as N,r as k,D as A,o as E,z as F,c as i,e as R,d as t,A as B,g as v,m as j,E as z,x as _,w as l,v as K,q as u,h as c,F as C,i as x,C as O,j as q,B as G,k as a}from"./index-BsVv6gaD.js";import"./vendor-charts-Bcjh2pZL.js";import"./vendor-ui-jlFFG6nm.js";const X={class:"config-wrapper"},H={key:0,class:"config-card"},J={key:1,class:"config-card"},Q={class:"config-row"},W={class:"config-col"},Y={class:"select-container"},Z={class:"config-col"},h={class:"number-input-container"},ss={class:"number-input-controls"},ts={class:"config-row"},ns={class:"config-col"},os={class:"config-col"},es={class:"config-row"},ls={class:"config-col"},is={class:"number-input-container"},as={class:"number-input-controls"},rs={class:"config-col"},ds={class:"number-input-container"},us={class:"number-input-controls"},ps={class:"config-row"},cs={class:"config-col"},fs={class:"toggle-wrapper"},vs={class:"toggle-switch"},gs={key:0,class:"nested-box fade-in"},bs={class:"config-row mb-2"},ms={class:"config-col"},_s={class:"list-container"},ys=["onUpdate:modelValue"],ks=["onClick"],ws={class:"config-row"},Cs={class:"config-col"},xs={class:"toggle-wrapper"},Ss={class:"toggle-switch"},Vs={key:1,class:"nested-box fade-in"},Us={class:"config-row mb-2"},Ps={class:"config-col"},Ds={class:"list-container"},Ts=["onUpdate:modelValue"],$s=["onClick"],Is={class:"config-row"},Ls={class:"config-col"},Ms={class:"toggle-wrapper"},Ns={class:"toggle-switch"},As={class:"config-col"},Es={class:"toggle-wrapper"},Fs={class:"toggle-switch"},Rs={class:"config-col"},Bs={class:"toggle-wrapper"},js={class:"toggle-switch"},zs={class:"config-row"},Ks={class:"config-col"},Os={class:"toggle-wrapper"},qs={class:"toggle-switch"},Gs={key:2,class:"nested-box fade-in"},Xs={class:"config-row"},Hs={class:"config-col"},Js={class:"config-row mt-3"},Qs={class:"config-col"},Ws={class:"config-row mt-4"},Ys={class:"config-col"},Zs={class:"toggle-wrapper"},hs={class:"toggle-switch"},st={key:3,class:"nested-box fade-in"},tt={class:"config-row"},nt={class:"config-col"},ot={class:"config-col"},et={class:"number-input-container"},lt={class:"number-input-controls"},it={class:"btn-action-group"},at=["disabled"],rt={key:0,class:"fas fa-spinner fa-spin"},dt={key:1,class:"fas fa-save"},ut=["disabled"],pt={key:0,class:"fas fa-spinner fa-spin"},ct={key:1,class:"fas fa-rocket"},mt={__name:"VPNConfig",setup(ft){const{profilesApiClient:y}=q(),S=G(),{status:V,refresh:w}=F(),n=N({protocol:"udp",port:1194,vpn_network:"",public_ip:"",tun_mtu:0,mssfix:0,tunnel_type:"FULL",split_routes:[],user_defined_dns:!1,dns_servers:[],duplicate_cn:!1,client_to_client:!1,crl_verify:!1,user_defined_cdscripts:!1,connect_script:"",disconnect_script:"",management_interface:!1,management_interface_address:"",management_port:7505}),g=k(!1),p=k(!1),f=k("");A(g,e=>{n.tunnel_type=e?"SPLIT":"FULL"});function U(e){if(!e)return"";const s=e.split(".");let r=0;const o={255:8,254:7,252:6,248:5,240:4,224:3,192:2,128:1,0:0};for(let d of s)r+=o[parseInt(d)]||0;return r}const b=(e,s="success")=>S.show(e,s),P=()=>n.split_routes.push(""),D=e=>n.split_routes.splice(e,1),T=()=>n.dns_servers.push(""),$=e=>n.dns_servers.splice(e,1),I=async()=>{try{const s=(await y.get("/config",{params:{section:"server"}})).data,r=s.server?s.server:s;if(Object.keys(r).forEach(o=>{n.hasOwnProperty(o)&&(o==="tunnel_type"&&(g.value=r[o]==="SPLIT"),n[o]=r[o])}),r.vpn_network&&r.vpn_netmask){const o=U(r.vpn_netmask);o&&(n.vpn_network=`${r.vpn_network}/${o}`)}}catch(e){console.error(e),b("Failed to load Server config from Management API.","error")}},L=async()=>{p.value=!0,f.value="save";const e={...n};if(e.split_routes=e.split_routes.filter(s=>s&&s.trim()!==""),e.dns_servers=e.dns_servers.filter(s=>s&&s.trim()!==""),e.vpn_network.includes("/")){const[s,r]=e.vpn_network.split("/");e.vpn_network=s}try{await y.put("/config/server",e),b("Server configuration saved!","success")}catch(s){b(`Error saving: ${s.response?.data?.detail||s.message}`,"error")}finally{p.value=!1,f.value=""}},M=async()=>{p.value=!0,f.value="apply";try{const s=(await y.post("/server/configure")).data;b(s.message||"Configuration applied!","success")}catch(e){b(`Error applying: ${e.response?.data?.detail||e.message}`,"error"),w()}finally{p.value=!1,f.value=""}};return E(()=>{w(),I()}),(e,s)=>{const r=z("router-link");return a(),i("div",X,[R(V).pki_ready?(a(),i("div",J,[s[75]||(s[75]=t("div",{class:"config-header"},[t("h1",null,"Server Infrastructure Configuration")],-1)),t("form",{onSubmit:O(L,["prevent"])},[t("div",Q,[t("div",W,[s[30]||(s[30]=t("label",{class:"config-label"},"Tunnel Protocol",-1)),t("div",Y,[l(t("select",{class:"config-select","onUpdate:modelValue":s[0]||(s[0]=o=>n.protocol=o)},[...s[28]||(s[28]=[t("option",{value:"tcp"},"TCP",-1),t("option",{value:"udp"},"UDP",-1)])],512),[[K,n.protocol]]),s[29]||(s[29]=t("div",{class:"select-arrow"},[t("i",{class:"fas fa-chevron-down"})],-1))])]),t("div",Z,[s[33]||(s[33]=t("label",{class:"config-label"},"Tunnel Port",-1)),t("div",h,[l(Line truncated
@@ -1 +1 @@
@charset "UTF-8";:root,[data-bs-theme=light]{--bs-blue:#0d6efd;--bs-indigo:#6610f2;--bs-purple:#6f42c1;--bs-pink:#d63384;--bs-red:#dc3545;--bs-orange:#fd7e14;--bs-yellow:#ffc107;--bs-green:#198754;--bs-teal:#20c997;--bs-cyan:#0dcaf0;--bs-black:#000;--bs-white:#fff;--bs-gray:#6c757d;--bs-gray-dark:#343a40;--bs-gray-100:#f8f9fa;--bs-gray-200:#e9ecef;--bs-gray-300:#dee2e6;--bs-gray-400:#ced4da;--bs-gray-500:#adb5bd;--bs-gray-600:#6c757d;--bs-gray-700:#495057;--bs-gray-800:#343a40;--bs-gray-900:#212529;--bs-primary:#0d6efd;--bs-secondary:#6c757d;--bs-success:#198754;--bs-info:#0dcaf0;--bs-warning:#ffc107;--bs-danger:#dc3545;--bs-light:#f8f9fa;--bs-dark:#212529;--bs-primary-rgb:13,110,253;--bs-secondary-rgb:108,117,125;--bs-success-rgb:25,135,84;--bs-info-rgb:13,202,240;--bs-warning-rgb:255,193,7;--bs-danger-rgb:220,53,69;--bs-light-rgb:248,249,250;--bs-dark-rgb:33,37,41;--bs-primary-text-emphasis:#052c65;--bs-secondary-text-emphasis:#2b2f32;--bs-success-text-emphasis:#0a3622;--bs-info-text-emphasis:#055160;--bs-warning-text-emphasis:#664d03;--bs-danger-text-emphasis:#58151c;--bs-light-text-emphasis:#495057;--bs-dark-text-emphasis:#495057;--bs-primary-bg-subtle:#cfe2ff;--bs-secondary-bg-subtle:#e2e3e5;--bs-success-bg-subtle:#d1e7dd;--bs-info-bg-subtle:#cff4fc;--bs-warning-bg-subtle:#fff3cd;--bs-danger-bg-subtle:#f8d7da;--bs-light-bg-subtle:#fcfcfd;--bs-dark-bg-subtle:#ced4da;--bs-primary-border-subtle:#9ec5fe;--bs-secondary-border-subtle:#c4c8cb;--bs-success-border-subtle:#a3cfbb;--bs-info-border-subtle:#9eeaf9;--bs-warning-border-subtle:#ffe69c;--bs-danger-border-subtle:#f1aeb5;--bs-light-border-subtle:#e9ecef;--bs-dark-border-subtle:#adb5bd;--bs-white-rgb:255,255,255;--bs-black-rgb:0,0,0;--bs-font-sans-serif:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue","Noto Sans","Liberation Sans",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--bs-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--bs-gradient:linear-gradient(180deg, rgba(255, 255, 255, .15), rgba(255, 255, 255, 0));--bs-body-font-family:var(--bs-font-sans-serif);--bs-body-font-size:1rem;--bs-body-font-weight:400;--bs-body-line-height:1.5;--bs-body-color:#212529;--bs-body-color-rgb:33,37,41;--bs-body-bg:#fff;--bs-body-bg-rgb:255,255,255;--bs-emphasis-color:#000;--bs-emphasis-color-rgb:0,0,0;--bs-secondary-color:rgba(33, 37, 41, .75);--bs-secondary-color-rgb:33,37,41;--bs-secondary-bg:#e9ecef;--bs-secondary-bg-rgb:233,236,239;--bs-tertiary-color:rgba(33, 37, 41, .5);--bs-tertiary-color-rgb:33,37,41;--bs-tertiary-bg:#f8f9fa;--bs-tertiary-bg-rgb:248,249,250;--bs-heading-color:inherit;--bs-link-color:#0d6efd;--bs-link-color-rgb:13,110,253;--bs-link-decoration:underline;--bs-link-hover-color:#0a58ca;--bs-link-hover-color-rgb:10,88,202;--bs-code-color:#d63384;--bs-highlight-color:#212529;--bs-highlight-bg:#fff3cd;--bs-border-width:1px;--bs-border-style:solid;--bs-border-color:#dee2e6;--bs-border-color-translucent:rgba(0, 0, 0, .175);--bs-border-radius:.375rem;--bs-border-radius-sm:.25rem;--bs-border-radius-lg:.5rem;--bs-border-radius-xl:1rem;--bs-border-radius-xxl:2rem;--bs-border-radius-2xl:var(--bs-border-radius-xxl);--bs-border-radius-pill:50rem;--bs-box-shadow:0 .5rem 1rem rgba(0, 0, 0, .15);--bs-box-shadow-sm:0 .125rem .25rem rgba(0, 0, 0, .075);--bs-box-shadow-lg:0 1rem 3rem rgba(0, 0, 0, .175);--bs-box-shadow-inset:inset 0 1px 2px rgba(0, 0, 0, .075);--bs-focus-ring-width:.25rem;--bs-focus-ring-opacity:.25;--bs-focus-ring-color:rgba(13, 110, 253, .25);--bs-form-valid-color:#198754;--bs-form-valid-border-color:#198754;--bs-form-invalid-color:#dc3545;--bs-form-invalid-border-color:#dc3545}[data-bs-theme=dark]{color-scheme:dark;--bs-body-color:#dee2e6;--bs-body-color-rgb:222,226,230;--bs-body-bg:#212529;--bs-body-bg-rgb:33,37,41;--bs-emphasis-color:#fff;--bs-emphasis-color-rgb:255,255,255;--bs-secondary-color:rgba(222, 226, 230, .75);--bs-secondary-color-rgb:222,226,230;--bs-secondary-bg:#343a40;--bs-secondary-bg-rgb:52,58,64;--bs-tertiary-color:rgba(222, 226, 230, .5);--bs-tertiary-color-rgb:222,226,230;--bs-tertiary-bg:#2b3035;--bs-tertiary-bg-rgb:43,48,53;--bs-primary-text-emphasis:#6ea8fe;--bs-secondary-text-emphasis:#a7acb1;--bs-success-text-emphasis:#75b798;--bs-info-text-emphasis:#6edff6;--bs-warning-text-emphasis:#ffda6a;--bs-danger-text-emphasis:#ea868f;--bs-light-text-emphasis:#f8f9fa;--bs-dark-text-emphasis:#dee2e6;--bs-primary-bg-subtle:#031633;--bs-secondary-bg-subtle:#161719;--bs-success-bg-subtle:#051b11;--bs-info-bg-subtle:#032830;--bs-warning-bg-subtle:#332701;--bs-danger-bg-subtle:#2c0b0e;--bs-light-bg-subtle:#343a40;--bs-dark-bg-subtle:#1a1d20;--bs-primary-border-subtle:#084298;--bs-secondary-border-subtle:#41464b;--bs-success-border-subtle:#0f5132;--bs-info-border-subtle:#087990;--bs-warning-border-subtle:#997404;--bs-danger-border-subtle:#842029;--bs-light-border-subtle:#495057;--bs-dark-border-subtle:#343a40;--bs-heading-color:inherit;--Line truncated
@charset "UTF-8";:root,[data-bs-theme=light]{--bs-blue:#0d6efd;--bs-indigo:#6610f2;--bs-purple:#6f42c1;--bs-pink:#d63384;--bs-red:#dc3545;--bs-orange:#fd7e14;--bs-yellow:#ffc107;--bs-green:#198754;--bs-teal:#20c997;--bs-cyan:#0dcaf0;--bs-black:#000;--bs-white:#fff;--bs-gray:#6c757d;--bs-gray-dark:#343a40;--bs-gray-100:#f8f9fa;--bs-gray-200:#e9ecef;--bs-gray-300:#dee2e6;--bs-gray-400:#ced4da;--bs-gray-500:#adb5bd;--bs-gray-600:#6c757d;--bs-gray-700:#495057;--bs-gray-800:#343a40;--bs-gray-900:#212529;--bs-primary:#0d6efd;--bs-secondary:#6c757d;--bs-success:#198754;--bs-info:#0dcaf0;--bs-warning:#ffc107;--bs-danger:#dc3545;--bs-light:#f8f9fa;--bs-dark:#212529;--bs-primary-rgb:13,110,253;--bs-secondary-rgb:108,117,125;--bs-success-rgb:25,135,84;--bs-info-rgb:13,202,240;--bs-warning-rgb:255,193,7;--bs-danger-rgb:220,53,69;--bs-light-rgb:248,249,250;--bs-dark-rgb:33,37,41;--bs-primary-text-emphasis:#052c65;--bs-secondary-text-emphasis:#2b2f32;--bs-success-text-emphasis:#0a3622;--bs-info-text-emphasis:#055160;--bs-warning-text-emphasis:#664d03;--bs-danger-text-emphasis:#58151c;--bs-light-text-emphasis:#495057;--bs-dark-text-emphasis:#495057;--bs-primary-bg-subtle:#cfe2ff;--bs-secondary-bg-subtle:#e2e3e5;--bs-success-bg-subtle:#d1e7dd;--bs-info-bg-subtle:#cff4fc;--bs-warning-bg-subtle:#fff3cd;--bs-danger-bg-subtle:#f8d7da;--bs-light-bg-subtle:#fcfcfd;--bs-dark-bg-subtle:#ced4da;--bs-primary-border-subtle:#9ec5fe;--bs-secondary-border-subtle:#c4c8cb;--bs-success-border-subtle:#a3cfbb;--bs-info-border-subtle:#9eeaf9;--bs-warning-border-subtle:#ffe69c;--bs-danger-border-subtle:#f1aeb5;--bs-light-border-subtle:#e9ecef;--bs-dark-border-subtle:#adb5bd;--bs-white-rgb:255,255,255;--bs-black-rgb:0,0,0;--bs-font-sans-serif:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue","Noto Sans","Liberation Sans",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--bs-font-monospace:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--bs-gradient:linear-gradient(180deg, rgba(255, 255, 255, .15), rgba(255, 255, 255, 0));--bs-body-font-family:var(--bs-font-sans-serif);--bs-body-font-size:1rem;--bs-body-font-weight:400;--bs-body-line-height:1.5;--bs-body-color:#212529;--bs-body-color-rgb:33,37,41;--bs-body-bg:#fff;--bs-body-bg-rgb:255,255,255;--bs-emphasis-color:#000;--bs-emphasis-color-rgb:0,0,0;--bs-secondary-color:rgba(33, 37, 41, .75);--bs-secondary-color-rgb:33,37,41;--bs-secondary-bg:#e9ecef;--bs-secondary-bg-rgb:233,236,239;--bs-tertiary-color:rgba(33, 37, 41, .5);--bs-tertiary-color-rgb:33,37,41;--bs-tertiary-bg:#f8f9fa;--bs-tertiary-bg-rgb:248,249,250;--bs-heading-color:inherit;--bs-link-color:#0d6efd;--bs-link-color-rgb:13,110,253;--bs-link-decoration:underline;--bs-link-hover-color:#0a58ca;--bs-link-hover-color-rgb:10,88,202;--bs-code-color:#d63384;--bs-highlight-color:#212529;--bs-highlight-bg:#fff3cd;--bs-border-width:1px;--bs-border-style:solid;--bs-border-color:#dee2e6;--bs-border-color-translucent:rgba(0, 0, 0, .175);--bs-border-radius:.375rem;--bs-border-radius-sm:.25rem;--bs-border-radius-lg:.5rem;--bs-border-radius-xl:1rem;--bs-border-radius-xxl:2rem;--bs-border-radius-2xl:var(--bs-border-radius-xxl);--bs-border-radius-pill:50rem;--bs-box-shadow:0 .5rem 1rem rgba(0, 0, 0, .15);--bs-box-shadow-sm:0 .125rem .25rem rgba(0, 0, 0, .075);--bs-box-shadow-lg:0 1rem 3rem rgba(0, 0, 0, .175);--bs-box-shadow-inset:inset 0 1px 2px rgba(0, 0, 0, .075);--bs-focus-ring-width:.25rem;--bs-focus-ring-opacity:.25;--bs-focus-ring-color:rgba(13, 110, 253, .25);--bs-form-valid-color:#198754;--bs-form-valid-border-color:#198754;--bs-form-invalid-color:#dc3545;--bs-form-invalid-border-color:#dc3545}[data-bs-theme=dark]{color-scheme:dark;--bs-body-color:#dee2e6;--bs-body-color-rgb:222,226,230;--bs-body-bg:#212529;--bs-body-bg-rgb:33,37,41;--bs-emphasis-color:#fff;--bs-emphasis-color-rgb:255,255,255;--bs-secondary-color:rgba(222, 226, 230, .75);--bs-secondary-color-rgb:222,226,230;--bs-secondary-bg:#343a40;--bs-secondary-bg-rgb:52,58,64;--bs-tertiary-color:rgba(222, 226, 230, .5);--bs-tertiary-color-rgb:222,226,230;--bs-tertiary-bg:#2b3035;--bs-tertiary-bg-rgb:43,48,53;--bs-primary-text-emphasis:#6ea8fe;--bs-secondary-text-emphasis:#a7acb1;--bs-success-text-emphasis:#75b798;--bs-info-text-emphasis:#6edff6;--bs-warning-text-emphasis:#ffda6a;--bs-danger-text-emphasis:#ea868f;--bs-light-text-emphasis:#f8f9fa;--bs-dark-text-emphasis:#dee2e6;--bs-primary-bg-subtle:#031633;--bs-secondary-bg-subtle:#161719;--bs-success-bg-subtle:#051b11;--bs-info-bg-subtle:#032830;--bs-warning-bg-subtle:#332701;--bs-danger-bg-subtle:#2c0b0e;--bs-light-bg-subtle:#343a40;--bs-dark-bg-subtle:#1a1d20;--bs-primary-border-subtle:#084298;--bs-secondary-border-subtle:#41464b;--bs-success-border-subtle:#0f5132;--bs-info-border-subtle:#087990;--bs-warning-border-subtle:#997404;--bs-danger-border-subtle:#842029;--bs-light-border-subtle:#495057;--bs-dark-border-subtle:#343a40;--bs-heading-color:inherit;--Line truncated
+7
View File
@@ -0,0 +1,7 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Analytics-wS3sZsf7.js","assets/useTrafficChart-69f2EcZB.js","assets/vendor-charts-Bcjh2pZL.js","assets/useFormatters-CKGG-YVI.js","assets/Clients-B4FTmkE-.js","assets/vendor-ui-Dumif2LN.js","assets/Certificates-Q5PSlJMg.js","assets/ConfirmModal-wSxjHDVn.js","assets/PKIConfig-aTZFQ7nU.js","assets/ServerManagement-BrgZCXB4.js","assets/BackupRestore-b-fUBt2d.js","assets/Account-D3bmpB1v.js"])))=>i.map(i=>d[i]);
(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&s(l)}).observe(document,{childList:!0,subtree:!0});function n(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=n(r);fetch(r.href,o)}})();function bl(e){const t=Object.create(null);for(const n of e.split(","))t[n]=1;return n=>n in t}const $e={},Ls=[],hn=()=>{},Gu=()=>!1,xi=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),yl=e=>e.startsWith("onUpdate:"),Ze=Object.assign,vl=(e,t)=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)},lm=Object.prototype.hasOwnProperty,Re=(e,t)=>lm.call(e,t),re=Array.isArray,Ds=e=>xr(e)==="[object Map]",Ws=e=>xr(e)==="[object Set]",Sc=e=>xr(e)==="[object Date]",pe=e=>typeof e=="function",ze=e=>typeof e=="string",Xt=e=>typeof e=="symbol",Me=e=>e!==null&&typeof e=="object",Ju=e=>(Me(e)||pe(e))&&pe(e.then)&&pe(e.catch),Xu=Object.prototype.toString,xr=e=>Xu.call(e),am=e=>xr(e).slice(8,-1),Yu=e=>xr(e)==="[object Object]",wl=e=>ze(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,ar=bl(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),Oi=e=>{const t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},cm=/-\w/g,Wt=Oi(e=>e.replace(cm,t=>t.slice(1).toUpperCase())),um=/\B([A-Z])/g,qn=Oi(e=>e.replace(um,"-$1").toLowerCase()),Ri=Oi(e=>e.charAt(0).toUpperCase()+e.slice(1)),xo=Oi(e=>e?`on${Ri(e)}`:""),Un=(e,t)=>!Object.is(e,t),ai=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},Qu=(e,t,n,s=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:s,value:n})},Pi=e=>{const t=parseFloat(e);return isNaN(t)?e:t},fm=e=>{const t=ze(e)?Number(e):NaN;return isNaN(t)?e:t};let Tc;const Ni=()=>Tc||(Tc=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function Ii(e){if(re(e)){const t={};for(let n=0;n<e.length;n++){const s=e[n],r=ze(s)?mm(s):Ii(s);if(r)for(const o in r)t[o]=r[o]}return t}else if(ze(e)||Me(e))return e}const dm=/;(?![^(]*\))/g,hm=/:([^]+)/,pm=/\/\*[^]*?\*\//g;function mm(e){const t={};return e.replace(pm,"").split(dm).forEach(n=>{if(n){const s=n.split(hm);s.length>1&&(t[s[0].trim()]=s[1].trim())}}),t}function An(e){let t="";if(ze(e))t=e;else if(re(e))for(let n=0;n<e.length;n++){const s=An(e[n]);s&&(t+=s+" ")}else if(Me(e))for(const n in e)e[n]&&(t+=n+" ");return t.trim()}const gm="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly",_m=bl(gm);function Zu(e){return!!e||e===""}function bm(e,t){if(e.length!==t.length)return!1;let n=!0;for(let s=0;n&&s<e.length;s++)n=Or(e[s],t[s]);return n}function Or(e,t){if(e===t)return!0;let n=Sc(e),s=Sc(t);if(n||s)return n&&s?e.getTime()===t.getTime():!1;if(n=Xt(e),s=Xt(t),n||s)return e===t;if(n=re(e),s=re(t),n||s)return n&&s?bm(e,t):!1;if(n=Me(e),s=Me(t),n||s){if(!n||!s)return!1;const r=Object.keys(e).length,o=Object.keys(t).length;if(r!==o)return!1;for(const l in e){const c=e.hasOwnProperty(l),u=t.hasOwnProperty(l);if(c&&!u||!c&&u||!Or(e[l],t[l]))return!1}}return String(e)===String(t)}function El(e,t){return e.findIndex(n=>Or(n,t))}const ef=e=>!!(e&&e.__v_isRef===!0),cs=e=>ze(e)?e:e==null?"":re(e)||Me(e)&&(e.toString===Xu||!pe(e.toString))?ef(e)?cs(e.value):JSON.stringify(e,tf,2):String(e),tf=(e,t)=>ef(t)?tf(e,t.value):Ds(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((n,[s,r],o)=>(n[Oo(s,o)+" =>"]=r,n),{})}:Ws(t)?{[`Set(${t.size})`]:[...t.values()].map(n=>Oo(n))}:Xt(t)?Oo(t):Me(t)&&!re(t)&&!Yu(t)?String(t):t,Oo=(e,t="")=>{var n;return Xt(e)?`Symbol(${(n=e.description)!=null?n:t})`:e};let St;class ym{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=St,!t&&St&&(this.index=(St.scopes||(St.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,n;if(this.scopes)for(t=0,n=this.scopes.length;t<n;t++)this.scopes[t].pause();for(t=0,n=this.effects.length;t<n;t++)this.effects[t].pause()}}resume(){if(this._active&&this._isPaused){this._isPaused=!1;let t,n;if(this.scopes)for(t=0,n=this.scopes.length;t<n;t++)this.scopes[t].resume();for(t=0,n=this.effects.length;t<n;t++)this.effects[t].resume()}}run(t){if(this._active){const n=St;try{return St=this,t()}finally{St=n}}}on(){++this._on===1&&(this.prevScope=St,St=this)}off(){this._on>0&&--this._on===0&&(St=this.prevScope,this.prevScope=void 0)}stop(t){if(this._active){this._active=!1;let n,s;for(n=0,s=this.effects.length;n<s;n+Line truncated
`).forEach(function(l){r=l.indexOf(":"),n=l.substring(0,r).trim().toLowerCase(),s=l.substring(r+1).trim(),!(!n||t[n]&&Vb[n])&&(n==="set-cookie"?t[n]?t[n].push(s):t[n]=[s]:t[n]=t[n]?t[n]+", "+s:s)}),t},bu=Symbol("internals");function sr(e){return e&&String(e).trim().toLowerCase()}function mi(e){return e===!1||e==null?e:C.isArray(e)?e.map(mi):String(e)}function Wb(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=n.exec(e);)t[s[1]]=s[2];return t}const Kb=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Ho(e,t,n,s,r){if(C.isFunction(s))return s.call(this,t,n);if(r&&(t=n),!!C.isString(t)){if(C.isString(s))return t.indexOf(s)!==-1;if(C.isRegExp(s))return s.test(t)}}function zb(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,s)=>n.toUpperCase()+s)}function Gb(e,t){const n=C.toCamelCase(" "+t);["get","set","has"].forEach(s=>{Object.defineProperty(e,s+n,{value:function(r,o,l){return this[s].call(this,t,r,o,l)},configurable:!0})})}let Ot=class{constructor(t){t&&this.set(t)}set(t,n,s){const r=this;function o(c,u,h){const d=sr(u);if(!d)throw new Error("header name must be a non-empty string");const m=C.findKey(r,d);(!m||r[m]===void 0||h===!0||h===void 0&&r[m]!==!1)&&(r[m||u]=mi(c))}const l=(c,u)=>C.forEach(c,(h,d)=>o(h,d,u));if(C.isPlainObject(t)||t instanceof this.constructor)l(t,n);else if(C.isString(t)&&(t=t.trim())&&!Kb(t))l(qb(t),n);else if(C.isObject(t)&&C.isIterable(t)){let c={},u,h;for(const d of t){if(!C.isArray(d))throw TypeError("Object iterator must return a key-value pair");c[h=d[0]]=(u=c[h])?C.isArray(u)?[...u,d[1]]:[u,d[1]]:d[1]}l(c,n)}else t!=null&&o(n,t,s);return this}get(t,n){if(t=sr(t),t){const s=C.findKey(this,t);if(s){const r=this[s];if(!n)return r;if(n===!0)return Wb(r);if(C.isFunction(n))return n.call(this,r,s);if(C.isRegExp(n))return n.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=sr(t),t){const s=C.findKey(this,t);return!!(s&&this[s]!==void 0&&(!n||Ho(this,this[s],s,n)))}return!1}delete(t,n){const s=this;let r=!1;function o(l){if(l=sr(l),l){const c=C.findKey(s,l);c&&(!n||Ho(s,s[c],c,n))&&(delete s[c],r=!0)}}return C.isArray(t)?t.forEach(o):o(t),r}clear(t){const n=Object.keys(this);let s=n.length,r=!1;for(;s--;){const o=n[s];(!t||Ho(this,this[o],o,t,!0))&&(delete this[o],r=!0)}return r}normalize(t){const n=this,s={};return C.forEach(this,(r,o)=>{const l=C.findKey(s,o);if(l){n[l]=mi(r),delete n[o];return}const c=t?zb(o):String(o).trim();c!==o&&delete n[o],n[c]=mi(r),s[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return C.forEach(this,(s,r)=>{s!=null&&s!==!1&&(n[r]=t&&C.isArray(s)?s.join(", "):s)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const s=new this(t);return n.forEach(r=>s.set(r)),s}static accessor(t){const s=(this[bu]=this[bu]={accessors:{}}).accessors,r=this.prototype;function o(l){const c=sr(l);s[c]||(Gb(r,l),s[c]=!0)}return C.isArray(t)?t.forEach(o):o(t),this}};Ot.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);C.reduceDescriptors(Ot.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(s){this[n]=s}}});C.freezeMethods(Ot);function Uo(e,t){const n=this||Lr,s=t||n,r=Ot.from(s.headers);let o=s.data;return C.forEach(e,function(c){o=c.call(n,o,r.normalize(),t?t.status:void 0)}),r.normalize(),o}function Sd(e){return!!(e&&e.__CANCEL__)}function zs(e,t,n){me.call(this,e??"canceled",me.ERR_CANCELED,t,n),this.name="CanceledError"}C.inherits(zs,me,{__CANCEL__:!0});function Td(e,t,n){const s=n.config.validateStatus;!n.status||!s||s(n.status)?e(n):t(new me("Request failed with status code "+n.status,[me.ERR_BAD_REQUEST,me.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Jb(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Xb(e,t){e=e||10;const n=new Array(e),s=new Array(e);let r=0,o=0,l;return t=t!==void 0?t:1e3,function(u){const h=Date.now(),d=s[o];l||(l=h),n[r]=u,s[r]=h;let m=o,_=0;for(;m!==r;)_+=n[m++],m=m%e;if(r=(r+1)%e,r===o&&(o=(o+1)%e),h-l<t)return;const y=d&&h-d;return y?Math.round(_*1e3/y):void 0}}function Yb(e,t){let n=0,s=1e3/t,r,o;const l=(h,d=Date.now())=>{n=d,r=null,o&&(clearTimeout(o),o=null),e(...h)};return[(...h)=>{const d=Date.now(),m=d-n;m>=s?l(h,d):(r=h,o||(o=setTimeout(()=>{o=null,l(r)},s-m)))},()=>r&&l(r)]}const Ti=(e,t,n=3)=>{let s=0;const r=Xb(50,250);return Yb(o=>{const l=o.loaded,c=o.lengthComputable?o.total:void 0,u=l-s,h=r(u),d=l<=c;s=l;const m={loaded:l,total:c,progress:c?l/c:void 0,bytes:u,rate:h||void 0,estimated:h&&c&&d?(c-l)/h:void 0,event:o,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(m)},n)},yu=(e,t)=>{const n=e!=null;return[s=>t[0]({lengthComputable:n,total:e,loaded:s}),t[1]]},vu=e=>(...t)=>C.asap(()=>e(...t)),Qb=ft.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,ft.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(ft.origin),ft.navigator&&/(msie|trident)/i.test(ft.navigator.userAgent)):()=>!0,Zb=ft.hasStandardBrowserEnv?{write(e,t,n,s,r,o,l){if(typeof document>"u")return;const c=[`${e}=${encodeURIComponent(t)}`];C.isNumber(n)&&c.push(`expires=${new Date(n).toUTCString()}`),C.isString(s)&&c.push(`path=${s}`),C.isString(r)&&c.push(`domain=${r}`),o===!0&&c.push("secure"),C.isString(l)&&c.push(`SameSite=${l}`),document.cookie=c.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function ey(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function ty(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function xd(e,t,n){let s=!ey(t);return e&&(s||n==!1)?ty(e,t):t}const wu=e=>e instanceof Ot?{...e}:e;function ps(e,t){t=t||{};const n={};function s(h,d,m,_){return C.isPlainObject(h)&&C.isPlainObject(d)?C.merge.call({caseless:_},h,d):C.isPlainObject(d)?C.merge({},d):C.isArray(d)?d.slice():d}function r(h,d,m,_){if(C.isUndefined(d)){if(!C.isUndefined(h))return s(void 0,h,m,_)}else return s(h,d,m,_)}function o(h,d){if(!C.isUndefined(d))return s(void 0,d)}function l(h,d){if(C.isUndefined(d)){if(!C.isUndefined(h))return s(void 0,h)}else return s(void 0,d)}function c(h,d,m){if(m in t)return s(h,d);if(m in e)return s(void 0,h)}const u={url:o,method:o,data:o,baseURL:l,transformRequest:l,transformResponse:l,paramsSerializer:l,timeout:l,timeoutMessage:l,withCredentials:l,withXSRFToken:l,adapter:l,responseType:l,xsrfCookieName:l,xsrfHeaderName:l,onUploadProgress:l,onDownloadProgress:l,decompress:l,maxContentLength:l,maxBodyLength:l,beforeRedirect:l,transport:l,httpAgent:l,httpsAgent:l,cancelToken:l,socketPath:l,responseEncoding:l,validateStatus:c,headers:(h,d,m)=>r(wu(h),wu(d),m,!0)};return C.forEach(Object.keys({...e,...t}),function(d){const m=u[d]||r,_=m(e[d],t[d],d);C.isUndefined(_)&&m!==c||(n[d]=_)}),n}const Od=e=>{const t=ps({},e);let{data:n,withXSRFToken:s,xsrfHeaderName:r,xsrfCookieName:o,headers:l,auth:c}=t;if(t.headers=l=Ot.from(l),t.url=Ed(xd(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&l.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),C.isFormData(n)){if(ft.hasStandardBrowserEnv||ft.hasStandardBrowserWebWorkerEnv)l.setContentType(void 0);else if(C.isFunction(n.getHeaders)){const u=n.getHeaders(),h=["content-type","content-length"];Object.entries(u).forEach(([d,m])=>{h.inclu Line truncated
`+l.map(xu).join(`
`):" "+xu(l[0]):"as no adapter specified";throw new me("There is no suitable adapter to dispatch the request "+c,"ERR_NOT_SUPPORT")}return r}const Pd={getAdapter:dy,adapters:Ul};function Vo(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new zs(null,e)}function Ou(e){return Vo(e),e.headers=Ot.from(e.headers),e.data=Uo.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Pd.getAdapter(e.adapter||Lr.adapter,e)(e).then(function(s){return Vo(e),s.data=Uo.call(e,e.transformResponse,s),s.headers=Ot.from(s.headers),s},function(s){return Sd(s)||(Vo(e),s&&s.response&&(s.response.data=Uo.call(e,e.transformResponse,s.response),s.response.headers=Ot.from(s.response.headers))),Promise.reject(s)})}const Nd="1.13.2",qi={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{qi[e]=function(s){return typeof s===e||"a"+(t<1?"n ":" ")+e}});const Ru={};qi.transitional=function(t,n,s){function r(o,l){return"[Axios v"+Nd+"] Transitional option '"+o+"'"+l+(s?". "+s:"")}return(o,l,c)=>{if(t===!1)throw new me(r(l," has been removed"+(n?" in "+n:"")),me.ERR_DEPRECATED);return n&&!Ru[l]&&(Ru[l]=!0,console.warn(r(l," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(o,l,c):!0}};qi.spelling=function(t){return(n,s)=>(console.warn(`${s} is likely a misspelling of ${t}`),!0)};function hy(e,t,n){if(typeof e!="object")throw new me("options must be an object",me.ERR_BAD_OPTION_VALUE);const s=Object.keys(e);let r=s.length;for(;r-- >0;){const o=s[r],l=t[o];if(l){const c=e[o],u=c===void 0||l(c,o,e);if(u!==!0)throw new me("option "+o+" must be "+u,me.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new me("Unknown option "+o,me.ERR_BAD_OPTION)}}const gi={assertOptions:hy,validators:qi},an=gi.validators;let ds=class{constructor(t){this.defaults=t||{},this.interceptors={request:new _u,response:new _u}}async request(t,n){try{return await this._request(t,n)}catch(s){if(s instanceof Error){let r={};Error.captureStackTrace?Error.captureStackTrace(r):r=new Error;const o=r.stack?r.stack.replace(/^.+\n/,""):"";try{s.stack?o&&!String(s.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(s.stack+=`
`+o):s.stack=o}catch{}}throw s}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ps(this.defaults,n);const{transitional:s,paramsSerializer:r,headers:o}=n;s!==void 0&&gi.assertOptions(s,{silentJSONParsing:an.transitional(an.boolean),forcedJSONParsing:an.transitional(an.boolean),clarifyTimeoutError:an.transitional(an.boolean)},!1),r!=null&&(C.isFunction(r)?n.paramsSerializer={serialize:r}:gi.assertOptions(r,{encode:an.function,serialize:an.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),gi.assertOptions(n,{baseUrl:an.spelling("baseURL"),withXsrfToken:an.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let l=o&&C.merge(o.common,o[n.method]);o&&C.forEach(["delete","get","head","post","put","patch","common"],w=>{delete o[w]}),n.headers=Ot.concat(l,o);const c=[];let u=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(n)===!1||(u=u&&S.synchronous,c.unshift(S.fulfilled,S.rejected))});const h=[];this.interceptors.response.forEach(function(S){h.push(S.fulfilled,S.rejected)});let d,m=0,_;if(!u){const w=[Ou.bind(this),void 0];for(w.unshift(...c),w.push(...h),_=w.length,d=Promise.resolve(n);m<_;)d=d.then(w[m++],w[m++]);return d}_=c.length;let y=n;for(;m<_;){const w=c[m++],S=c[m++];try{y=w(y)}catch(x){S.call(this,x);break}}try{d=Ou.call(this,y)}catch(w){return Promise.reject(w)}for(m=0,_=h.length;m<_;)d=d.then(h[m++],h[m++]);return d}getUri(t){t=ps(this.defaults,t);const n=xd(t.baseURL,t.url,t.allowAbsoluteUrls);return Ed(n,t.params,t.paramsSerializer)}};C.forEach(["delete","get","head","options"],function(t){ds.prototype[t]=function(n,s){return this.request(ps(s||{},{method:t,url:n,data:(s||{}).data}))}});C.forEach(["post","put","patch"],function(t){function n(s){return function(o,l,c){return this.request(ps(c||{},{method:t,headers:s?{"Content-Type":"multipart/form-data"}:{},url:o,data:l}))}}ds.prototype[t]=n(),ds.prototype[t+"Form"]=n(!0)});let py=class Id{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});const s=this;this.promise.then(r=>{if(!s._listeners)return;let o=s._listeners.length;for(;o-- >0;)s._listeners[o](r);s._listeners=null}),this.promise.then=r=>{let o;const l=new Promise(c=>{s.subscribe(c),o=c}).then(r);return l.cancel=function(){s.unsubscribe(o)},l},t(function(o,l,c){s.reason||(s.reason=new zs(o,l,c),n(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=s=>{t.abort(s)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Id(function(r){t=r}),cancel:t}}};function my(e){return function(n){return e.apply(null,n)}}function gy(e){return C.isObject(e)&&e.isAxiosError===!0}const dl={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(dl).forEach(([e,t])=>{dl[t]=e});function kd(e){const t=new ds(e),n=ud(ds.prototype.request,t);return C.extend(n,ds.prototype,t,{allOwnKeys:!0}),C.extend(n,t,null,{allOwnKeys:!0}),n.create=function(r){return kd(ps(e,r))},n}const qe=kd(Lr);qe.Axios=ds;qe.CanceledError=zs;qe.CancelToken=py;qe.isCancel=Sd;qe.VERSION=Nd;qe.toFormData=Vi;qe.AxiosError=me;qe.Cancel=qe.CanceledError;qe.all=function(t){return Promise.all(t)};qe.spread=my;qe.isAxiosError=gy;qe.mergeConfig=ps;qe.AxiosH Line truncated
-7
View File
@@ -1,7 +0,0 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Analytics-D8_MsU7I.js","assets/vendor-charts-Bcjh2pZL.js","assets/vendor-ui-jlFFG6nm.js","assets/Certificates-DI1YjC4x.js","assets/ConfirmModal-CzamKe9d.js","assets/PKIConfig-DcX7kknv.js","assets/VPNConfig-hH9toHBV.js","assets/ServerManagement-DcQnn0e_.js","assets/BackupRestore-p02MFVQ3.js","assets/Account-D01xrOy_.js"])))=>i.map(i=>d[i]);
import{C as zu,r as om}from"./vendor-charts-Bcjh2pZL.js";import{M as lm}from"./vendor-ui-jlFFG6nm.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&s(l)}).observe(document,{childList:!0,subtree:!0});function n(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=n(r);fetch(r.href,o)}})();function wl(e){const t=Object.create(null);for(const n of e.split(","))t[n]=1;return n=>n in t}const Be={},Ds=[],gn=()=>{},Gu=()=>!1,ki=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),El=e=>e.startsWith("onUpdate:"),rt=Object.assign,Al=(e,t)=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)},am=Object.prototype.hasOwnProperty,ke=(e,t)=>am.call(e,t),oe=Array.isArray,Ms=e=>Or(e)==="[object Map]",zs=e=>Or(e)==="[object Set]",Cc=e=>Or(e)==="[object Date]",me=e=>typeof e=="function",Xe=e=>typeof e=="string",Zt=e=>typeof e=="symbol",$e=e=>e!==null&&typeof e=="object",Ju=e=>($e(e)||me(e))&&me(e.then)&&me(e.catch),Xu=Object.prototype.toString,Or=e=>Xu.call(e),cm=e=>Or(e).slice(8,-1),Yu=e=>Or(e)==="[object Object]",Cl=e=>Xe(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,ur=wl(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),Ni=e=>{const t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},um=/-\w/g,zt=Ni(e=>e.replace(um,t=>t.slice(1).toUpperCase())),fm=/\B([A-Z])/g,qn=Ni(e=>e.replace(fm,"-$1").toLowerCase()),Ii=Ni(e=>e.charAt(0).toUpperCase()+e.slice(1)),ko=Ni(e=>e?`on${Ii(e)}`:""),Un=(e,t)=>!Object.is(e,t),fi=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},Qu=(e,t,n,s=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:s,value:n})},Li=e=>{const t=parseFloat(e);return isNaN(t)?e:t},dm=e=>{const t=Xe(e)?Number(e):NaN;return isNaN(t)?e:t};let xc;const Di=()=>xc||(xc=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function Mi(e){if(oe(e)){const t={};for(let n=0;n<e.length;n++){const s=e[n],r=Xe(s)?gm(s):Mi(s);if(r)for(const o in r)t[o]=r[o]}return t}else if(Xe(e)||$e(e))return e}const hm=/;(?![^(]*\))/g,pm=/:([^]+)/,mm=/\/\*[^]*?\*\//g;function gm(e){const t={};return e.replace(mm,"").split(hm).forEach(n=>{if(n){const s=n.split(pm);s.length>1&&(t[s[0].trim()]=s[1].trim())}}),t}function ft(e){let t="";if(Xe(e))t=e;else if(oe(e))for(let n=0;n<e.length;n++){const s=ft(e[n]);s&&(t+=s+" ")}else if($e(e))for(const n in e)e[n]&&(t+=n+" ");return t.trim()}const _m="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly",bm=wl(_m);function Zu(e){return!!e||e===""}function vm(e,t){if(e.length!==t.length)return!1;let n=!0;for(let s=0;n&&s<e.length;s++)n=Rr(e[s],t[s]);return n}function Rr(e,t){if(e===t)return!0;let n=Cc(e),s=Cc(t);if(n||s)return n&&s?e.getTime()===t.getTime():!1;if(n=Zt(e),s=Zt(t),n||s)return e===t;if(n=oe(e),s=oe(t),n||s)return n&&s?vm(e,t):!1;if(n=$e(e),s=$e(t),n||s){if(!n||!s)return!1;const r=Object.keys(e).length,o=Object.keys(t).length;if(r!==o)return!1;for(const l in e){const c=e.hasOwnProperty(l),u=t.hasOwnProperty(l);if(c&&!u||!c&&u||!Rr(e[l],t[l]))return!1}}return String(e)===String(t)}function xl(e,t){return e.findIndex(n=>Rr(n,t))}const ef=e=>!!(e&&e.__v_isRef===!0),Ge=e=>Xe(e)?e:e==null?"":oe(e)||$e(e)&&(e.toString===Xu||!me(e.toString))?ef(e)?Ge(e.value):JSON.stringify(e,tf,2):String(e),tf=(e,t)=>ef(t)?tf(e,t.value):Ms(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((n,[s,r],o)=>(n[No(s,o)+" =>"]=r,n),{})}:zs(t)?{[`Set(${t.size})`]:[...t.values()].map(n=>No(n))}:Zt(t)?No(t):$e(t)&&!oe(t)&&!Yu(t)?String(t):t,No=(e,t="")=>{var n;return Zt(e)?`Symbol(${(n=e.description)!=null?n:t})`:e};let Rt;class ym{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=Rt,!t&&Rt&&(this.index=(Rt.scopes||(Rt.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,n;if(this.scopes)for(t=0,n=this.scopes.length;t<n;t++)this.scopes[t].pause();for(t=0,n=this.effects.length;t<n;t++)this.effects[t].pause()}}resume(){if(this._active&&this._isPaused){this._isPaused=!1;let t,n;if(this.scopes)for(t=0,n=this.scopes.length;t<n;t++)this.scopes[t].resume();for(t=0,n=this.effects.length;t<n;t++)this.effects[t].resume()}}run(t){if(this._active){const n=Rt;try{return Rt=this,t()}finally{Rt=n}}}on(){++this._on===1&&(this.prevScope=Rt,Rt=this)}off(){this._on>0&&--this._on===0&&(Rt=this.prevScope,this.pLine truncated
`).forEach(function(l){r=l.indexOf(":"),n=l.substring(0,r).trim().toLowerCase(),s=l.substring(r+1).trim(),!(!n||t[n]&&Wb[n])&&(n==="set-cookie"?t[n]?t[n].push(s):t[n]=[s]:t[n]=t[n]?t[n]+", "+s:s)}),t},_u=Symbol("internals");function ir(e){return e&&String(e).trim().toLowerCase()}function vi(e){return e===!1||e==null?e:S.isArray(e)?e.map(vi):String(e)}function zb(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let s;for(;s=n.exec(e);)t[s[1]]=s[2];return t}const Gb=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Vo(e,t,n,s,r){if(S.isFunction(s))return s.call(this,t,n);if(r&&(t=n),!!S.isString(t)){if(S.isString(s))return t.indexOf(s)!==-1;if(S.isRegExp(s))return s.test(t)}}function Jb(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,s)=>n.toUpperCase()+s)}function Xb(e,t){const n=S.toCamelCase(" "+t);["get","set","has"].forEach(s=>{Object.defineProperty(e,s+n,{value:function(r,o,l){return this[s].call(this,t,r,o,l)},configurable:!0})})}let kt=class{constructor(t){t&&this.set(t)}set(t,n,s){const r=this;function o(c,u,h){const d=ir(u);if(!d)throw new Error("header name must be a non-empty string");const p=S.findKey(r,d);(!p||r[p]===void 0||h===!0||h===void 0&&r[p]!==!1)&&(r[p||u]=vi(c))}const l=(c,u)=>S.forEach(c,(h,d)=>o(h,d,u));if(S.isPlainObject(t)||t instanceof this.constructor)l(t,n);else if(S.isString(t)&&(t=t.trim())&&!Gb(t))l(Kb(t),n);else if(S.isObject(t)&&S.isIterable(t)){let c={},u,h;for(const d of t){if(!S.isArray(d))throw TypeError("Object iterator must return a key-value pair");c[h=d[0]]=(u=c[h])?S.isArray(u)?[...u,d[1]]:[u,d[1]]:d[1]}l(c,n)}else t!=null&&o(n,t,s);return this}get(t,n){if(t=ir(t),t){const s=S.findKey(this,t);if(s){const r=this[s];if(!n)return r;if(n===!0)return zb(r);if(S.isFunction(n))return n.call(this,r,s);if(S.isRegExp(n))return n.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ir(t),t){const s=S.findKey(this,t);return!!(s&&this[s]!==void 0&&(!n||Vo(this,this[s],s,n)))}return!1}delete(t,n){const s=this;let r=!1;function o(l){if(l=ir(l),l){const c=S.findKey(s,l);c&&(!n||Vo(s,s[c],c,n))&&(delete s[c],r=!0)}}return S.isArray(t)?t.forEach(o):o(t),r}clear(t){const n=Object.keys(this);let s=n.length,r=!1;for(;s--;){const o=n[s];(!t||Vo(this,this[o],o,t,!0))&&(delete this[o],r=!0)}return r}normalize(t){const n=this,s={};return S.forEach(this,(r,o)=>{const l=S.findKey(s,o);if(l){n[l]=vi(r),delete n[o];return}const c=t?Jb(o):String(o).trim();c!==o&&delete n[o],n[c]=vi(r),s[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return S.forEach(this,(s,r)=>{s!=null&&s!==!1&&(n[r]=t&&S.isArray(s)?s.join(", "):s)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const s=new this(t);return n.forEach(r=>s.set(r)),s}static accessor(t){const s=(this[_u]=this[_u]={accessors:{}}).accessors,r=this.prototype;function o(l){const c=ir(l);s[c]||(Xb(r,l),s[c]=!0)}return S.isArray(t)?t.forEach(o):o(t),this}};kt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);S.reduceDescriptors(kt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(s){this[n]=s}}});S.freezeMethods(kt);function qo(e,t){const n=this||Mr,s=t||n,r=kt.from(s.headers);let o=s.data;return S.forEach(e,function(c){o=c.call(n,o,r.normalize(),t?t.status:void 0)}),r.normalize(),o}function Sd(e){return!!(e&&e.__CANCEL__)}function Js(e,t,n){ge.call(this,e??"canceled",ge.ERR_CANCELED,t,n),this.name="CanceledError"}S.inherits(Js,ge,{__CANCEL__:!0});function Td(e,t,n){const s=n.config.validateStatus;!n.status||!s||s(n.status)?e(n):t(new ge("Request failed with status code "+n.status,[ge.ERR_BAD_REQUEST,ge.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Yb(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Qb(e,t){e=e||10;const n=new Array(e),s=new Array(e);let r=0,o=0,l;return t=t!==void 0?t:1e3,function(u){const h=Date.now(),d=s[o];l||(l=h),n[r]=u,s[r]=h;let p=o,_=0;for(;p!==r;)_+=n[p++],p=p%e;if(r=(r+1)%e,r===o&&(o=(o+1)%e),h-l<t)return;const v=d&&h-d;return v?Math.round(_*1e3/v):void 0}}function Zb(e,t){let n=0,s=1e3/t,r,o;const l=(h,d=Date.now())=>{n=d,r=null,o&&(clearTimeout(o),o=null),e(...h)};return[(...h)=>{const d=Date.now(),p=d-n;p>=s?l(h,d):(r=h,o||(o=setTimeout(()=>{o=null,l(r)},s-p)))},()=>r&&l(r)]}const Pi=(e,t,n=3)=>{let s=0;const r=Qb(50,250);return Zb(o=>{const l=o.loaded,c=o.lengthComputable?o.total:void 0,u=l-s,h=r(u),d=l<=c;s=l;const p={loaded:l,total:c,progress:c?l/c:void 0,bytes:u,rate:h||void 0,estimated:h&&c&&d?(c-l)/h:void 0,event:o,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(p)},n)},bu=(e,t)=>{const n=e!=null;return[s=>t[0]({lengthComputable:n,total:e,loaded:s}),t[1]]},vu=e=>(...t)=>S.asap(()=>e(...t)),ev=gt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,gt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(gt.origin),gt.navigator&&/(msie|trident)/i.test(gt.navigator.userAgent)):()=>!0,tv=gt.hasStandardBrowserEnv?{write(e,t,n,s,r,o,l){if(typeof document>"u")return;const c=[`${e}=${encodeURIComponent(t)}`];S.isNumber(n)&&c.push(`expires=${new Date(n).toUTCString()}`),S.isString(s)&&c.push(`path=${s}`),S.isString(r)&&c.push(`domain=${r}`),o===!0&&c.push("secure"),S.isString(l)&&c.push(`SameSite=${l}`),document.cookie=c.join("; ")},read(e){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function nv(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function sv(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Od(e,t,n){let s=!nv(t);return e&&(s||n==!1)?sv(e,t):t}const yu=e=>e instanceof kt?{...e}:e;function ms(e,t){t=t||{};const n={};function s(h,d,p,_){return S.isPlainObject(h)&&S.isPlainObject(d)?S.merge.call({caseless:_},h,d):S.isPlainObject(d)?S.merge({},d):S.isArray(d)?d.slice():d}function r(h,d,p,_){if(S.isUndefined(d)){if(!S.isUndefined(h))return s(void 0,h,p,_)}else return s(h,d,p,_)}function o(h,d){if(!S.isUndefined(d))return s(void 0,d)}function l(h,d){if(S.isUndefined(d)){if(!S.isUndefined(h))return s(void 0,h)}else return s(void 0,d)}function c(h,d,p){if(p in t)return s(h,d);if(p in e)return s(void 0,h)}const u={url:o,method:o,data:o,baseURL:l,transformRequest:l,transformResponse:l,paramsSerializer:l,timeout:l,timeoutMessage:l,withCredentials:l,withXSRFToken:l,adapter:l,responseType:l,xsrfCookieName:l,xsrfHeaderName:l,onUploadProgress:l,onDownloadProgress:l,decompress:l,maxContentLength:l,maxBodyLength:l,beforeRedirect:l,transport:l,httpAgent:l,httpsAgent:l,cancelToken:l,socketPath:l,responseEncoding:l,validateStatus:c,headers:(h,d,p)=>r(yu(h),yu(d),p,!0)};return S.forEach(Object.keys({...e,...t}),function(d){const p=u[d]||r,_=p(e[d],t[d],d);S.isUndefined(_)&&p!==c||(n[d]=_)}),n}const Rd=e=>{const t=ms({},e);let{data:n,withXSRFToken:s,xsrfHeaderName:r,xsrfCookieName:o,headers:l,auth:c}=t;if(t.headers=l=kt.from(l),t.url=Ad(Od(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&l.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),S.isFormData(n)){if(gt.hasStandardBrowserEnv||gt.hasStandardBrowserWebWorkerEnv)l.setContentType(void 0);else if(S.isFunction(n.getHeaders)){const u=n.getHeaders(),h=["content-type","content-length"];Object.entries(u).forEach(([d,p])=>{h.inclu Line truncated
`+l.map(Su).join(`
`):" "+Su(l[0]):"as no adapter specified";throw new ge("There is no suitable adapter to dispatch the request "+c,"ERR_NOT_SUPPORT")}return r}const kd={getAdapter:pv,adapters:ql};function Wo(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Js(null,e)}function Tu(e){return Wo(e),e.headers=kt.from(e.headers),e.data=qo.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),kd.getAdapter(e.adapter||Mr.adapter,e)(e).then(function(s){return Wo(e),s.data=qo.call(e,e.transformResponse,s),s.headers=kt.from(s.headers),s},function(s){return Sd(s)||(Wo(e),s&&s.response&&(s.response.data=qo.call(e,e.transformResponse,s.response),s.response.headers=kt.from(s.response.headers))),Promise.reject(s)})}const Nd="1.13.2",Gi={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Gi[e]=function(s){return typeof s===e||"a"+(t<1?"n ":" ")+e}});const Ou={};Gi.transitional=function(t,n,s){function r(o,l){return"[Axios v"+Nd+"] Transitional option '"+o+"'"+l+(s?". "+s:"")}return(o,l,c)=>{if(t===!1)throw new ge(r(l," has been removed"+(n?" in "+n:"")),ge.ERR_DEPRECATED);return n&&!Ou[l]&&(Ou[l]=!0,console.warn(r(l," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(o,l,c):!0}};Gi.spelling=function(t){return(n,s)=>(console.warn(`${s} is likely a misspelling of ${t}`),!0)};function mv(e,t,n){if(typeof e!="object")throw new ge("options must be an object",ge.ERR_BAD_OPTION_VALUE);const s=Object.keys(e);let r=s.length;for(;r-- >0;){const o=s[r],l=t[o];if(l){const c=e[o],u=c===void 0||l(c,o,e);if(u!==!0)throw new ge("option "+o+" must be "+u,ge.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ge("Unknown option "+o,ge.ERR_BAD_OPTION)}}const yi={assertOptions:mv,validators:Gi},fn=yi.validators;let hs=class{constructor(t){this.defaults=t||{},this.interceptors={request:new gu,response:new gu}}async request(t,n){try{return await this._request(t,n)}catch(s){if(s instanceof Error){let r={};Error.captureStackTrace?Error.captureStackTrace(r):r=new Error;const o=r.stack?r.stack.replace(/^.+\n/,""):"";try{s.stack?o&&!String(s.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(s.stack+=`
`+o):s.stack=o}catch{}}throw s}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ms(this.defaults,n);const{transitional:s,paramsSerializer:r,headers:o}=n;s!==void 0&&yi.assertOptions(s,{silentJSONParsing:fn.transitional(fn.boolean),forcedJSONParsing:fn.transitional(fn.boolean),clarifyTimeoutError:fn.transitional(fn.boolean)},!1),r!=null&&(S.isFunction(r)?n.paramsSerializer={serialize:r}:yi.assertOptions(r,{encode:fn.function,serialize:fn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),yi.assertOptions(n,{baseUrl:fn.spelling("baseURL"),withXsrfToken:fn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let l=o&&S.merge(o.common,o[n.method]);o&&S.forEach(["delete","get","head","post","put","patch","common"],y=>{delete o[y]}),n.headers=kt.concat(l,o);const c=[];let u=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(n)===!1||(u=u&&x.synchronous,c.unshift(x.fulfilled,x.rejected))});const h=[];this.interceptors.response.forEach(function(x){h.push(x.fulfilled,x.rejected)});let d,p=0,_;if(!u){const y=[Tu.bind(this),void 0];for(y.unshift(...c),y.push(...h),_=y.length,d=Promise.resolve(n);p<_;)d=d.then(y[p++],y[p++]);return d}_=c.length;let v=n;for(;p<_;){const y=c[p++],x=c[p++];try{v=y(v)}catch(O){x.call(this,O);break}}try{d=Tu.call(this,v)}catch(y){return Promise.reject(y)}for(p=0,_=h.length;p<_;)d=d.then(h[p++],h[p++]);return d}getUri(t){t=ms(this.defaults,t);const n=Od(t.baseURL,t.url,t.allowAbsoluteUrls);return Ad(n,t.params,t.paramsSerializer)}};S.forEach(["delete","get","head","options"],function(t){hs.prototype[t]=function(n,s){return this.request(ms(s||{},{method:t,url:n,data:(s||{}).data}))}});S.forEach(["post","put","patch"],function(t){function n(s){return function(o,l,c){return this.request(ms(c||{},{method:t,headers:s?{"Content-Type":"multipart/form-data"}:{},url:o,data:l}))}}hs.prototype[t]=n(),hs.prototype[t+"Form"]=n(!0)});let gv=class Id{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(o){n=o});const s=this;this.promise.then(r=>{if(!s._listeners)return;let o=s._listeners.length;for(;o-- >0;)s._listeners[o](r);s._listeners=null}),this.promise.then=r=>{let o;const l=new Promise(c=>{s.subscribe(c),o=c}).then(r);return l.cancel=function(){s.unsubscribe(o)},l},t(function(o,l,c){s.reason||(s.reason=new Js(o,l,c),n(s.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=s=>{t.abort(s)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Id(function(r){t=r}),cancel:t}}};function _v(e){return function(n){return e.apply(null,n)}}function bv(e){return S.isObject(e)&&e.isAxiosError===!0}const ml={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(ml).forEach(([e,t])=>{ml[t]=e});function Ld(e){const t=new hs(e),n=fd(hs.prototype.request,t);return S.extend(n,hs.prototype,t,{allOwnKeys:!0}),S.extend(n,t,null,{allOwnKeys:!0}),n.create=function(r){return Ld(ms(e,r))},n}const Ke=Ld(Mr);Ke.Axios=hs;Ke.CanceledError=Js;Ke.CancelToken=gv;Ke.isCancel=Sd;Ke.VERSION=Nd;Ke.toFormData=zi;Ke.AxiosError=ge;Ke.Cancel=Ke.CanceledError;Ke.all=function(t){return Promise.all(t)};Ke.spread=_v;Ke.isAxiosError=bv;Ke.mergeConfig=ms;Ke.AxiosH Line truncated
@@ -0,0 +1 @@
function p(){function l(t,n=2){const e=Number(t);if(!Number.isFinite(e)||e<=0)return"0 B";const r=1024,a=n<0?0:n,i=["B","KB","MB","GB","TB"],o=Math.min(Math.max(Math.floor(Math.log(e)/Math.log(r)),0),i.length-1);return parseFloat((e/Math.pow(r,o)).toFixed(a))+" "+i[o]}function m(t){return(parseFloat(t)||0).toFixed(3)+" Mbps"}function c(t){if(!t)return null;if(t.endsWith("Z"))return new Date(t);const[n,e]=t.split(" ");if(!n||!e){let s=t.replace(" ","T");return!s.endsWith("Z")&&!s.includes("+")&&(s+="Z"),new Date(s)}const[r,a,i]=n.split("-").map(Number),[o,f,u]=e.split(":").map(Number);return new Date(Date.UTC(r,a-1,i,o,f,u!==void 0?u:0))}return{formatBytes:l,formatRate:m,parseServerDate:c}}export{p as u};
@@ -0,0 +1 @@
import{C as p,r as v}from"./vendor-charts-Bcjh2pZL.js";import{u as T}from"./useFormatters-CKGG-YVI.js";import{c as k}from"./index-BfAhXdi6.js";p.register(...v);const L="#1652B8",M="#EC7C31",_=1024*1024,S=()=>{const e=document.documentElement.getAttribute("data-theme")==="dark";return{isDark:e,gridColor:e?"rgba(240, 246, 252, 0.1)":"rgba(0,0,0,0.05)",textColor:e?"#8b949e":"#6c757d"}},A=(e,o)=>{if(!e||e.length===0)return[];if(e.length<=o)return e;const u=Math.ceil(e.length/o),n=[];for(let a=0;a<e.length;a+=u){const l=e.slice(a,a+u);if(l.length===0)continue;let m=0,c=0,s=0,t=0;l.forEach(r=>{m+=r.bytes_received||0,c+=r.bytes_sent||0,s=Math.max(s,r.rx_rate_mbps||0),t=Math.max(t,r.tx_rate_mbps||0)}),n.push({timestamp:l[0].timestamp,bytes_received:m,bytes_sent:c,rx_rate_mbps:s,tx_rate_mbps:t})}return n},B=e=>{const o=/^(\d+)([hd])$/.exec(e||"");return o?Number(o[1])*(o[2]==="d"?24:1)>24:!1};function D(e,{maxPoints:o}){const{parseServerDate:u}=T();let n=null;const a=()=>{n&&(n.destroy(),n=null)},l=(c,s)=>{const t=u(c),r=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return s.includes("h")||s==="1d"?r:t.toLocaleDateString([],{month:"short",day:"numeric"})+" "+r},m=(c,{range:s,speedMode:t})=>{if(!e.value)return;a();const r=[],d=[],b=[];A(c,o).forEach(i=>{r.push(l(i.timestamp,s)),t?(d.push(i.rx_rate_mbps||0),b.push(i.tx_rate_mbps||0)):(d.push(i.bytes_received/_),b.push(i.bytes_sent/_))});const{gridColor:h,textColor:g}=S(),x=B(s)?" (avg)":"",f=(i,C,R,y)=>({label:i,data:C,borderColor:R,backgroundColor:y,borderWidth:2,fill:!0,tension:.3,pointRadius:3,pointHoverRadius:4});n=new p(e.value.getContext("2d"),{type:"line",data:{labels:r,datasets:[f(t?`RX Mbps${x}`:"Received (MB)",d,L,"rgba(22, 82, 184, 0.15)"),f(t?`TX Mbps${x}`:"Sent (MB)",b,M,"rgba(236, 124, 49, 0.15)")]},options:{responsive:!0,maintainAspectRatio:!1,interaction:{mode:"index",intersect:!1},plugins:{legend:{labels:{color:g}}},scales:{x:{ticks:{color:g,maxTicksLimit:8},grid:{color:h}},y:{beginAtZero:!0,ticks:{color:g},grid:{color:h}}}}})};return k(a),{render:m,destroy:a}}export{L as C,M as a,S as g,D as u};
@@ -0,0 +1 @@
var L="top",R="bottom",x="right",I="left",fe="auto",It=[L,R,x,I],pt="start",Ot="end",is="clippingParents",Ge="viewport",At="popper",rs="reference",Be=It.reduce(function(n,t){return n.concat([t+"-"+pt,t+"-"+Ot])},[]),qe=[].concat(It,[fe]).reduce(function(n,t){return n.concat([t,t+"-"+pt,t+"-"+Ot])},[]),os="beforeRead",as="read",cs="afterRead",ls="beforeMain",us="main",hs="afterMain",ds="beforeWrite",fs="write",ps="afterWrite",_s=[os,as,cs,ls,us,hs,ds,fs,ps];function z(n){return n?(n.nodeName||"").toLowerCase():null}function k(n){if(n==null)return window;if(n.toString()!=="[object Window]"){var t=n.ownerDocument;return t&&t.defaultView||window}return n}function _t(n){var t=k(n).Element;return n instanceof t||n instanceof Element}function V(n){var t=k(n).HTMLElement;return n instanceof t||n instanceof HTMLElement}function Xe(n){if(typeof ShadowRoot>"u")return!1;var t=k(n).ShadowRoot;return n instanceof t||n instanceof ShadowRoot}function ui(n){var t=n.state;Object.keys(t.elements).forEach(function(e){var s=t.styles[e]||{},i=t.attributes[e]||{},r=t.elements[e];!V(r)||!z(r)||(Object.assign(r.style,s),Object.keys(i).forEach(function(o){var a=i[o];a===!1?r.removeAttribute(o):r.setAttribute(o,a===!0?"":a)}))})}function hi(n){var t=n.state,e={popper:{position:t.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(t.elements.popper.style,e.popper),t.styles=e,t.elements.arrow&&Object.assign(t.elements.arrow.style,e.arrow),function(){Object.keys(t.elements).forEach(function(s){var i=t.elements[s],r=t.attributes[s]||{},o=Object.keys(t.styles.hasOwnProperty(s)?t.styles[s]:e[s]),a=o.reduce(function(l,h){return l[h]="",l},{});!V(i)||!z(i)||(Object.assign(i.style,a),Object.keys(r).forEach(function(l){i.removeAttribute(l)}))})}}const Qe={name:"applyStyles",enabled:!0,phase:"write",fn:ui,effect:hi,requires:["computeStyles"]};function Y(n){return n.split("-")[0]}var ft=Math.max,le=Math.min,Ct=Math.round;function je(){var n=navigator.userAgentData;return n!=null&&n.brands&&Array.isArray(n.brands)?n.brands.map(function(t){return t.brand+"/"+t.version}).join(" "):navigator.userAgent}function ms(){return!/^((?!chrome|android).)*safari/i.test(je())}function Nt(n,t,e){t===void 0&&(t=!1),e===void 0&&(e=!1);var s=n.getBoundingClientRect(),i=1,r=1;t&&V(n)&&(i=n.offsetWidth>0&&Ct(s.width)/n.offsetWidth||1,r=n.offsetHeight>0&&Ct(s.height)/n.offsetHeight||1);var o=_t(n)?k(n):window,a=o.visualViewport,l=!ms()&&e,h=(s.left+(l&&a?a.offsetLeft:0))/i,u=(s.top+(l&&a?a.offsetTop:0))/r,p=s.width/i,_=s.height/r;return{width:p,height:_,top:u,right:h+p,bottom:u+_,left:h,x:h,y:u}}function Ze(n){var t=Nt(n),e=n.offsetWidth,s=n.offsetHeight;return Math.abs(t.width-e)<=1&&(e=t.width),Math.abs(t.height-s)<=1&&(s=t.height),{x:n.offsetLeft,y:n.offsetTop,width:e,height:s}}function gs(n,t){var e=t.getRootNode&&t.getRootNode();if(n.contains(t))return!0;if(e&&Xe(e)){var s=t;do{if(s&&n.isSameNode(s))return!0;s=s.parentNode||s.host}while(s)}return!1}function X(n){return k(n).getComputedStyle(n)}function di(n){return["table","td","th"].indexOf(z(n))>=0}function st(n){return((_t(n)?n.ownerDocument:n.document)||window.document).documentElement}function pe(n){return z(n)==="html"?n:n.assignedSlot||n.parentNode||(Xe(n)?n.host:null)||st(n)}function Tn(n){return!V(n)||X(n).position==="fixed"?null:n.offsetParent}function fi(n){var t=/firefox/i.test(je()),e=/Trident/i.test(je());if(e&&V(n)){var s=X(n);if(s.position==="fixed")return null}var i=pe(n);for(Xe(i)&&(i=i.host);V(i)&&["html","body"].indexOf(z(i))<0;){var r=X(i);if(r.transform!=="none"||r.perspective!=="none"||r.contain==="paint"||["transform","perspective"].indexOf(r.willChange)!==-1||t&&r.willChange==="filter"||t&&r.filter&&r.filter!=="none")return i;i=i.parentNode}return null}function Ft(n){for(var t=k(n),e=Tn(n);e&&di(e)&&X(e).position==="static";)e=Tn(e);return e&&(z(e)==="html"||z(e)==="body"&&X(e).position==="static")?t:e||fi(n)||t}function Je(n){return["top","bottom"].indexOf(n)>=0?"x":"y"}function Wt(n,t,e){return ft(n,le(t,e))}function pi(n,t,e){var s=Wt(n,t,e);return s>e?e:s}function Es(){return{top:0,right:0,bottom:0,left:0}}function vs(n){return Object.assign({},Es(),n)}function bs(n,t){return t.reduce(function(e,s){return e[s]=n,e},{})}var _i=function(t,e){return t=typeof t=="function"?t(Object.assign({},e.rects,{placement:e.placement})):t,vs(typeof t!="number"?t:bs(t,It))};function mi(n){var t,e=n.state,s=n.name,i=n.options,r=e.elements.arrow,o=e.modifiersData.popperOffsets,a=Y(e.placement),l=Je(a),h=[I,x].indexOf(a)>=0,u=h?"height":"width";if(!(!r||!o)){var p=_i(i.padding,e),_=Ze(r),f=l==="y"?L:I,A=l==="y"?R:x,m=e.rects.reference[u]+e.rects.reference[l]-o[l]-e.rects.popper[u],E=o[l]-e.rects.reference[l],T=Ft(r),w=T?l==="y"?T.clientHeight||0:T.clientWidth||0:0,O=m/2-E/2,g=p[f],v=w-_[u]-p[A],b=w/2-_[u]/2+O,y=Wt(g,b,v),S=l;e.modifiersData[s]=(t={},t[S]=y,t.centerOffset=y-b,t)}}function gi(n){var t=n.state,e=n.options,s=e.element,i=s===void 0?"[Line truncated
@@ -1,63 +0,0 @@
var H="top",U="bottom",q="right",j="left",un="auto",lt=[H,U,q,j],Re="start",Je="end",Vs="clippingParents",oo="viewport",qe="popper",Hs="reference",Yn=lt.reduce(function(t,e){return t.concat([e+"-"+Re,e+"-"+Je])},[]),so=[].concat(lt,[un]).reduce(function(t,e){return t.concat([e,e+"-"+Re,e+"-"+Je])},[]),js="beforeRead",Ws="read",Fs="afterRead",zs="beforeMain",Ks="main",Ys="afterMain",Us="beforeWrite",qs="write",Gs="afterWrite",Xs=[js,Ws,Fs,zs,Ks,Ys,Us,qs,Gs];function ue(t){return t?(t.nodeName||"").toLowerCase():null}function G(t){if(t==null)return window;if(t.toString()!=="[object Window]"){var e=t.ownerDocument;return e&&e.defaultView||window}return t}function Ve(t){var e=G(t).Element;return t instanceof e||t instanceof Element}function J(t){var e=G(t).HTMLElement;return t instanceof e||t instanceof HTMLElement}function io(t){if(typeof ShadowRoot>"u")return!1;var e=G(t).ShadowRoot;return t instanceof e||t instanceof ShadowRoot}function Vr(t){var e=t.state;Object.keys(e.elements).forEach(function(n){var o=e.styles[n]||{},s=e.attributes[n]||{},i=e.elements[n];!J(i)||!ue(i)||(Object.assign(i.style,o),Object.keys(s).forEach(function(r){var a=s[r];a===!1?i.removeAttribute(r):i.setAttribute(r,a===!0?"":a)}))})}function Hr(t){var e=t.state,n={popper:{position:e.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(e.elements.popper.style,n.popper),e.styles=n,e.elements.arrow&&Object.assign(e.elements.arrow.style,n.arrow),function(){Object.keys(e.elements).forEach(function(o){var s=e.elements[o],i=e.attributes[o]||{},r=Object.keys(e.styles.hasOwnProperty(o)?e.styles[o]:n[o]),a=r.reduce(function(c,f){return c[f]="",c},{});!J(s)||!ue(s)||(Object.assign(s.style,a),Object.keys(i).forEach(function(c){s.removeAttribute(c)}))})}}const ro={name:"applyStyles",enabled:!0,phase:"write",fn:Vr,effect:Hr,requires:["computeStyles"]};function le(t){return t.split("-")[0]}var Me=Math.max,Xt=Math.min,et=Math.round;function Un(){var t=navigator.userAgentData;return t!=null&&t.brands&&Array.isArray(t.brands)?t.brands.map(function(e){return e.brand+"/"+e.version}).join(" "):navigator.userAgent}function Qs(){return!/^((?!chrome|android).)*safari/i.test(Un())}function tt(t,e,n){e===void 0&&(e=!1),n===void 0&&(n=!1);var o=t.getBoundingClientRect(),s=1,i=1;e&&J(t)&&(s=t.offsetWidth>0&&et(o.width)/t.offsetWidth||1,i=t.offsetHeight>0&&et(o.height)/t.offsetHeight||1);var r=Ve(t)?G(t):window,a=r.visualViewport,c=!Qs()&&n,f=(o.left+(c&&a?a.offsetLeft:0))/s,d=(o.top+(c&&a?a.offsetTop:0))/i,g=o.width/s,w=o.height/i;return{width:g,height:w,top:d,right:f+g,bottom:d+w,left:f,x:f,y:d}}function ao(t){var e=tt(t),n=t.offsetWidth,o=t.offsetHeight;return Math.abs(e.width-n)<=1&&(n=e.width),Math.abs(e.height-o)<=1&&(o=e.height),{x:t.offsetLeft,y:t.offsetTop,width:n,height:o}}function Zs(t,e){var n=e.getRootNode&&e.getRootNode();if(t.contains(e))return!0;if(n&&io(n)){var o=e;do{if(o&&t.isSameNode(o))return!0;o=o.parentNode||o.host}while(o)}return!1}function me(t){return G(t).getComputedStyle(t)}function jr(t){return["table","td","th"].indexOf(ue(t))>=0}function Ce(t){return((Ve(t)?t.ownerDocument:t.document)||window.document).documentElement}function dn(t){return ue(t)==="html"?t:t.assignedSlot||t.parentNode||(io(t)?t.host:null)||Ce(t)}function Yo(t){return!J(t)||me(t).position==="fixed"?null:t.offsetParent}function Wr(t){var e=/firefox/i.test(Un()),n=/Trident/i.test(Un());if(n&&J(t)){var o=me(t);if(o.position==="fixed")return null}var s=dn(t);for(io(s)&&(s=s.host);J(s)&&["html","body"].indexOf(ue(s))<0;){var i=me(s);if(i.transform!=="none"||i.perspective!=="none"||i.contain==="paint"||["transform","perspective"].indexOf(i.willChange)!==-1||e&&i.willChange==="filter"||e&&i.filter&&i.filter!=="none")return s;s=s.parentNode}return null}function At(t){for(var e=G(t),n=Yo(t);n&&jr(n)&&me(n).position==="static";)n=Yo(n);return n&&(ue(n)==="html"||ue(n)==="body"&&me(n).position==="static")?e:n||Wr(t)||e}function lo(t){return["top","bottom"].indexOf(t)>=0?"x":"y"}function _t(t,e,n){return Me(t,Xt(e,n))}function Fr(t,e,n){var o=_t(t,e,n);return o>n?n:o}function Js(){return{top:0,right:0,bottom:0,left:0}}function ei(t){return Object.assign({},Js(),t)}function ti(t,e){return e.reduce(function(n,o){return n[o]=t,n},{})}var zr=function(e,n){return e=typeof e=="function"?e(Object.assign({},n.rects,{placement:n.placement})):e,ei(typeof e!="number"?e:ti(e,lt))};function Kr(t){var e,n=t.state,o=t.name,s=t.options,i=n.elements.arrow,r=n.modifiersData.popperOffsets,a=le(n.placement),c=lo(a),f=[j,q].indexOf(a)>=0,d=f?"height":"width";if(!(!i||!r)){var g=zr(s.padding,n),w=ao(i),m=c==="y"?H:j,C=c==="y"?U:q,b=n.rects.reference[d]+n.rects.reference[c]-r[c]-n.rects.popper[d],_=r[c]-n.rects.reference[c],k=At(i),x=k?c==="y"?k.clientHeight||0:k.clientWidth||0:0,$=b/2-_/2,v=g[m],A=x-w[d]-g[C],T=x/2-w[d]/2+$,S=_t(v,T,A),M=c;n.modifiersData[o]=(e={},e[M]=S,e.centerOffset=S-T,e)}}function Yr(t){var e=t.state,n=t.options,o=n.elementLine truncated
a[href],
area[href],
input:not([disabled]),
select:not([disabled]),
textarea:not([disabled]),
button:not([disabled]),
iframe,
object,
embed,
[tabindex="0"],
[contenteditable],
audio[controls],
video[controls],
summary
`,So=()=>{const t=y();if(!t)return[];const e=t.querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])'),n=Array.from(e).sort((i,r)=>{const a=parseInt(i.getAttribute("tabindex")||"0"),c=parseInt(r.getAttribute("tabindex")||"0");return a>c?1:a<c?-1:0}),o=t.querySelectorAll(Gd),s=Array.from(o).filter(i=>i.getAttribute("tabindex")!=="-1");return[...new Set(n.concat(s))].filter(i=>K(i))},xo=()=>pe(document.body,l.shown)&&!pe(document.body,l["toast-shown"])&&!pe(document.body,l["no-backdrop"]),En=()=>{const t=y();return t?pe(t,l.toast):!1},Xd=()=>{const t=y();return t?t.hasAttribute("data-loading"):!1},Z=(t,e)=>{if(t.textContent="",e){const o=new DOMParser().parseFromString(e,"text/html"),s=o.querySelector("head");s&&Array.from(s.childNodes).forEach(r=>{t.appendChild(r)});const i=o.querySelector("body");i&&Array.from(i.childNodes).forEach(r=>{r instanceof HTMLVideoElement||r instanceof HTMLAudioElement?t.appendChild(r.cloneNode(!0)):t.appendChild(r)})}},pe=(t,e)=>{if(!e)return!1;const n=e.split(/\s+/);for(let o=0;o<n.length;o++)if(!t.classList.contains(n[o]))return!1;return!0},Qd=(t,e)=>{Array.from(t.classList).forEach(n=>{!Object.values(l).includes(n)&&!Object.values(en).includes(n)&&!Object.values(e.showClass||{}).includes(n)&&t.classList.remove(n)})},X=(t,e,n)=>{if(Qd(t,e),!e.customClass)return;const o=e.customClass[n];if(o){if(typeof o!="string"&&!o.forEach){W(`Invalid type of customClass.${n}! Expected string or iterable object, got "${typeof o}"`);return}E(t,o)}},yn=(t,e)=>{if(!e)return null;switch(e){case"select":case"textarea":case"file":return t.querySelector(`.${l.popup} > .${l[e]}`);case"checkbox":return t.querySelector(`.${l.popup} > .${l.checkbox} input`);case"radio":return t.querySelector(`.${l.popup} > .${l.radio} input:checked`)||t.querySelector(`.${l.popup} > .${l.radio} input:first-child`);case"range":return t.querySelector(`.${l.popup} > .${l.range} input`);default:return t.querySelector(`.${l.popup} > .${l.input}`)}},Yi=t=>{if(t.focus(),t.type!=="file"){const e=t.value;t.value="",t.value=e}},Ui=(t,e,n)=>{!t||!e||(typeof e=="string"&&(e=e.split(/\s+/).filter(Boolean)),e.forEach(o=>{Array.isArray(t)?t.forEach(s=>{n?s.classList.add(o):s.classList.remove(o)}):n?t.classList.add(o):t.classList.remove(o)}))},E=(t,e)=>{Ui(t,e,!0)},ne=(t,e)=>{Ui(t,e,!1)},ve=(t,e)=>{const n=Array.from(t.children);for(let o=0;o<n.length;o++){const s=n[o];if(s instanceof HTMLElement&&pe(s,e))return s}},Be=(t,e,n)=>{n===`${parseInt(`${n}`)}`&&(n=parseInt(n)),n||parseInt(`${n}`)===0?t.style.setProperty(e,typeof n=="number"?`${n}px`:n):t.style.removeProperty(e)},P=(t,e="flex")=>{t&&(t.style.display=e)},R=t=>{t&&(t.style.display="none")},$o=(t,e="block")=>{t&&new MutationObserver(()=>{Lt(t,t.innerHTML,e)}).observe(t,{childList:!0,subtree:!0})},$s=(t,e,n,o)=>{const s=t.querySelector(e);s&&s.style.setProperty(n,o)},Lt=(t,e,n="flex")=>{e?P(t,n):R(t)},K=t=>!!(t&&(t.offsetWidth||t.offsetHeight||t.getClientRects().length)),Zd=()=>!K(de())&&!K(ze())&&!K(ht()),Jn=t=>t.scrollHeight>t.clientHeight,Jd=(t,e)=>{let n=t;for(;n&&n!==e;){if(Jn(n))return!0;n=n.parentElement}return!1},qi=t=>{const e=window.getComputedStyle(t),n=parseFloat(e.getPropertyValue("animation-duration")||"0"),o=parseFloat(e.getPropertyValue("transition-duration")||"0");return n>0||o>0},Lo=(t,e=!1)=>{const n=_n();n&&K(n)&&(e&&(n.style.transition="none",n.style.width="100%"),setTimeout(()=>{n.style.transition=`width ${t/1e3}s linear`,n.style.width="0%"},10))},ef=()=>{const t=_n();if(!t)return;const e=parseInt(window.getComputedStyle(t).width);t.style.removeProperty("transition"),t.style.width="100%";const n=parseInt(window.getComputedStyle(t).width),o=e/n*100;t.style.width=`${o}%`},tf=()=>typeof window>"u"||typeof document>"u",nf=`
<div aria-labelledby="${l.title}" aria-describedby="${l["html-container"]}" class="${l.popup}" tabindex="-1">
<button type="button" class="${l.close}"></button>
<ul class="${l["progress-steps"]}"></ul>
<div class="${l.icon}"></div>
<img class="${l.image}" />
<h2 class="${l.title}" id="${l.title}"></h2>
<div class="${l["html-container"]}" id="${l["html-container"]}"></div>
<input class="${l.input}" id="${l.input}" />
<input type="file" class="${l.file}" />
<div class="${l.range}">
<input type="range" />
<output></output>
</div>
<select class="${l.select}" id="${l.select}"></select>
<div class="${l.radio}"></div>
<label class="${l.checkbox}">
<input type="checkbox" id="${l.checkbox}" />
<span class="${l.label}"></span>
</label>
<textarea class="${l.textarea}" id="${l.textarea}"></textarea>
<div class="${l["validation-message"]}" id="${l["validation-message"]}"></div>
<div class="${l.actions}">
<div class="${l.loader}"></div>
<button type="button" class="${l.confirm}"></button>
<button type="button" class="${l.deny}"></button>
<button type="button" class="${l.cancel}"></button>
</div>
<div class="${l.footer}"></div>
<div class="${l["timer-progress-bar-container"]}">
<div class="${l["timer-progress-bar"]}"></div>
</div>
</div>
`.replace(/(^|\n)\s*/g,""),of=()=>{const t=F();return t?(t.remove(),ne([document.documentElement,document.body],[l["no-backdrop"],l["toast-shown"],l["has-column"]]),!0):!1},De=()=>{h.currentInstance&&h.currentInstance.resetValidationMessage()},sf=()=>{const t=y();if(!t)return;const e=ve(t,l.input),n=ve(t,l.file),o=t.querySelector(`.${l.range} input`),s=t.querySelector(`.${l.range} output`),i=ve(t,l.select),r=t.querySelector(`.${l.checkbox} input`),a=ve(t,l.textarea);e&&(e.oninput=De),n&&(n.onchange=De),i&&(i.onchange=De),r&&(r.onchange=De),a&&(a.oninput=De),o&&s&&(o.oninput=()=>{De(),s.value=o.value},o.onchange=()=>{De(),s.value=o.value})},rf=t=>{if(typeof t=="string"){const e=document.querySelector(t);if(!e)throw new Error(`Target element "${t}" not found`);return e}return t},af=t=>{const e=y();e&&(e.setAttribute("role",t.toast?"alert":"dialog"),e.setAttribute("aria-live",t.toast?"polite":"assertive"),t.toast||e.setAttribute("aria-modal","true"))},lf=t=>{window.getComputedStyle(t).direction==="rtl"&&(E(F(),l.rtl),h.isRTL=!0)},cf=t=>{const e=of();if(tf()){Fe("SweetAlert2 requires document to initialize");return}const n=document.createElement("div");n.className=l.container,e&&E(n,l["no-transition"]),Z(n,nf),n.dataset.swal2Theme=t.theme;const o=rf(t.target||"body");o.appendChild(n),t.topLayer&&(n.setAttribute("popover",""),n.showPopover()),af(t),lf(o),sf()},No=(t,e)=>{t instanceof HTMLElement?e.appendChild(t):typeof t=="object"?uf(t,e):t&&Z(e,t)},uf=(t,e)=>{"jquery"in t?df(e,t):Z(e,t.toString())},df=(t,e)=>{if(t.textContent="",0 in e)for(let n=0;n in e;n++)t.appendChild(e[n].cloneNode(!0));else t.appendChild(e.cloneNode(!0))},ff=(t,e)=>{const n=$t(),o=pt();!n||!o||(!e.showConfirmButton&&!e.showDenyButton&&!e.showCancelButton?R(n):P(n),X(n,e,"actions"),hf(n,o,e),Z(o,e.loaderHtml||""),X(o,e,"loader"))};function hf(t,e,n){const o=de(),s=ze(),i=ht();!o||!s||!i||(zn(o,"confirm",n),zn(s,"deny",n),zn(i,"cancel",n),pf(o,s,i,n),n.reverseButtons&&(n.toast?(t.insertBefore(i,o),t.insertBefore(s,o)):(t.insertBefore(i,e),t.insertBefore(s,e),t.insertBefore(o,e))))}function pf(t,e,n,o){if(!o.buttonsStyling){ne([t,e,n],l.styled);return}E([t,e,n],l.styled),o.confirmButtonColor&&t.style.setProperty("--swal2-confirm-button-background-color",o.confirmButtonColor),o.denyButtonColor&&e.style.setProperty("--swal2-deny-button-background-color",o.denyButtonColor),o.cancelButtonColor&&n.style.setProperty("--swal2-cancel-button-background-color",o.cancelButtonColor),Fn(t),Fn(e),Fn(n)}function Fn(t){const e=window.getComputedStyle(t);if(e.getPropertyValue("--swal2-action-button-focus-box-shadow"))return;const n=e.backgroundColor.replace(/rgba?\((\d+), (\d+), (\d+).*/,"rgba($1, $2, $3, 0.5)");t.style.setProperty("--swal2-action-button-focus-box-shadow",e.getPropertyValue("--swal2-outline").replace(/ rgba\(.*/,` ${n}`))}function zn(t,e,n){const o=yo(e);Lt(t,n[`show${o}Button`],"inline-block"),Z(t,n[`${e}ButtonText`]||""),t.setAttribute("aria-label",n[`${e}ButtonAriaLabel`]||""),t.className=l[e],X(t,n,`${e}Button`)}const mf=(t,e)=>{const n=ko();n&&(Z(n,e.closeButtonHtml||""),X(n,e,"closeButton"),Lt(n,e.showCloseButton),n.setAttribute("aria-label",e.closeButtonAriaLabel||""))},gf=(t,e)=>{const n=F();n&&(wf(n,e.backdrop),bf(n,e.position),vf(n,e.grow),X(n,e,"container"))};function wf(t,e){typeof e=="string"?t.style.background=e:e||E([document.documentElement,document.body],l["no-backdrop"])}function bf(t,e){e&&(e in l?E(t,l[e]):(W('The "position" parameter is not valid, defaulting to "center"'),E(t,l.center)))}function vf(t,e){e&&E(t,l[`grow-${e}`])}var O={innerParams:new WeakMap,domCache:new WeakMap};const _f=["input","file","range","select","radio","checkbox","textarea"],Ef=(t,e)=>{const n=y();if(!n)return;const o=O.innerParams.get(t),s=!o||e.input!==o.input;_f.forEach(i=>{const r=ve(n,l[i]);r&&(Tf(i,e.inputAttributes),r.className=l[i],s&&R(r))}),e.input&&(s&&yf(e),Cf(e))},yf=t=>{if(!t.input)return;if(!L[t.input]){Fe(`Unexpected type of input! Expected ${Object.keys(L).join(" | ")}, got "${t.input}"`);return}const e=Gi(t.input);if(!e)return;const n=L[t.input](e,t);P(e),t.inputAutoFocus&&setTimeout(()=>{Yi(n)})},Af=t=>{for(let e=0;e<t.attributes.length;e++){const n=t.attributes[e].name;["id","type","value","style"].includes(n)||t.removeAttribute(n)}},Tf=(t,e)=>{const n=y();if(!n)return;const o=yn(n,t);if(o){Af(o);for(const s in e)o.setAttribute(s,e[s])}},Cf=t=>{if(!t.input)return;const e=Gi(t.input);e&&X(e,t,"input")},Do=(t,e)=>{!t.placeholder&&e.inputPlaceholder&&(t.placeholder=e.inputPlaceholder)},Nt=(t,e,n)=>{if(n.inputLabel){const o=document.createElement("label"),s=l["input-label"];o.setAttribute("for",t.id),o.className=s,typeof n.customClass=="object"&&E(o,n.customClass.inputLabel),o.innerText=n.inputLabel,e.insertAdjacentElement("beforebegin",o)}},Gi=t=>{const e=y();if(e)return ve(e,l[t]||l.input)},tn=(t,e)=>{["string","number"].includes(typeof e)?t.value=`${e}`:To(e)||W(`Unexpected type of inputValue! Expected "string", "number" or "Line truncated
${t.animation?'<div class="swal2-success-circular-line-left"></div>':""}
<span class="swal2-success-line-tip"></span> <span class="swal2-success-line-long"></span>
<div class="swal2-success-ring"></div>
${t.animation?'<div class="swal2-success-fix"></div>':""}
${t.animation?'<div class="swal2-success-circular-line-right"></div>':""}
`,$f=`
<span class="swal2-x-mark">
<span class="swal2-x-mark-line-left"></span>
<span class="swal2-x-mark-line-right"></span>
</span>
`,Ns=(t,e)=>{if(!e.icon&&!e.iconHtml)return;let n=t.innerHTML,o="";e.iconHtml?o=Ds(e.iconHtml):e.icon==="success"?(o=xf(e),n=n.replace(/ style=".*?"/g,"")):e.icon==="error"?o=$f:e.icon&&(o=Ds({question:"?",warning:"!",info:"i"}[e.icon])),n.trim()!==o.trim()&&Z(t,o)},Lf=(t,e)=>{if(e.iconColor){t.style.color=e.iconColor,t.style.borderColor=e.iconColor;for(const n of[".swal2-success-line-tip",".swal2-success-line-long",".swal2-x-mark-line-left",".swal2-x-mark-line-right"])$s(t,n,"background-color",e.iconColor);$s(t,".swal2-success-ring","border-color",e.iconColor)}},Ds=t=>`<div class="${l["icon-content"]}">${t}</div>`,Nf=(t,e)=>{const n=zi();if(n){if(!e.imageUrl){R(n);return}P(n,""),n.setAttribute("src",e.imageUrl),n.setAttribute("alt",e.imageAlt||""),Be(n,"width",e.imageWidth),Be(n,"height",e.imageHeight),n.className=l.image,X(n,e,"image")}};let Io=!1,Qi=0,Zi=0,Ji=0,er=0;const Df=t=>{t.addEventListener("mousedown",nn),document.body.addEventListener("mousemove",on),t.addEventListener("mouseup",sn),t.addEventListener("touchstart",nn),document.body.addEventListener("touchmove",on),t.addEventListener("touchend",sn)},If=t=>{t.removeEventListener("mousedown",nn),document.body.removeEventListener("mousemove",on),t.removeEventListener("mouseup",sn),t.removeEventListener("touchstart",nn),document.body.removeEventListener("touchmove",on),t.removeEventListener("touchend",sn)},nn=t=>{const e=y();if(!e)return;const n=ft();if(t.target===e||n&&n.contains(t.target)){Io=!0;const o=tr(t);Qi=o.clientX,Zi=o.clientY,Ji=parseInt(e.style.insetInlineStart)||0,er=parseInt(e.style.insetBlockStart)||0,E(e,"swal2-dragging")}},on=t=>{const e=y();if(e&&Io){let{clientX:n,clientY:o}=tr(t);const s=n-Qi;e.style.insetInlineStart=`${Ji+(h.isRTL?-s:s)}px`,e.style.insetBlockStart=`${er+(o-Zi)}px`}},sn=()=>{const t=y();Io=!1,ne(t,"swal2-dragging")},tr=t=>{let e=0,n=0;return t.type.startsWith("mouse")?(e=t.clientX,n=t.clientY):t.type.startsWith("touch")&&(e=t.touches[0].clientX,n=t.touches[0].clientY),{clientX:e,clientY:n}},Pf=(t,e)=>{const n=F(),o=y();if(!(!n||!o)){if(e.toast){Be(n,"width",e.width),o.style.width="100%";const s=pt();s&&o.insertBefore(s,ft())}else Be(o,"width",e.width);Be(o,"padding",e.padding),e.color&&(o.style.color=e.color),e.background&&(o.style.background=e.background),R(vn()),Mf(o,e),e.draggable&&!e.toast?(E(o,l.draggable),Df(o)):(ne(o,l.draggable),If(o))}},Mf=(t,e)=>{const n=e.showClass||{};t.className=`${l.popup} ${K(t)?n.popup:""}`,e.toast?(E([document.documentElement,document.body],l["toast-shown"]),E(t,l.toast)):E(t,l.modal),X(t,e,"popup"),typeof e.customClass=="string"&&E(t,e.customClass),e.icon&&E(t,l[`icon-${e.icon}`])},Bf=(t,e)=>{const n=Oo();if(!n)return;const{progressSteps:o,currentProgressStep:s}=e;if(!o||o.length===0||s===void 0){R(n);return}P(n),n.textContent="",s>=o.length&&W("Invalid currentProgressStep parameter, it should be less than progressSteps.length (currentProgressStep like JS arrays starts from 0)"),o.forEach((i,r)=>{const a=Rf(i);if(n.appendChild(a),r===s&&E(a,l["active-progress-step"]),r!==o.length-1){const c=Vf(e);n.appendChild(c)}})},Rf=t=>{const e=document.createElement("li");return E(e,l["progress-step"]),Z(e,t),e},Vf=t=>{const e=document.createElement("li");return E(e,l["progress-step-line"]),t.progressStepsDistance&&Be(e,"width",t.progressStepsDistance),e},Hf=(t,e)=>{const n=Fi();n&&($o(n),Lt(n,!!(e.title||e.titleText),"block"),e.title&&No(e.title,n),e.titleText&&(n.innerText=e.titleText),X(n,e,"title"))},nr=(t,e)=>{var n;Pf(t,e),gf(t,e),Bf(t,e),Sf(t,e),Nf(t,e),Hf(t,e),mf(t,e),Of(t,e),ff(t,e),kf(t,e);const o=y();typeof e.didRender=="function"&&o&&e.didRender(o),(n=h.eventEmitter)===null||n===void 0||n.emit("didRender",o)},jf=()=>K(y()),or=()=>{var t;return(t=de())===null||t===void 0?void 0:t.click()},Wf=()=>{var t;return(t=ze())===null||t===void 0?void 0:t.click()},Ff=()=>{var t;return(t=ht())===null||t===void 0?void 0:t.click()},mt=Object.freeze({cancel:"cancel",backdrop:"backdrop",close:"close",esc:"esc",timer:"timer"}),sr=t=>{if(t.keydownTarget&&t.keydownHandlerAdded&&t.keydownHandler){const e=t.keydownHandler;t.keydownTarget.removeEventListener("keydown",e,{capture:t.keydownListenerCapture}),t.keydownHandlerAdded=!1}},zf=(t,e,n)=>{if(sr(t),!e.toast){const o=i=>Yf(e,i,n);t.keydownHandler=o;const s=e.keydownListenerCapture?window:y();if(s){t.keydownTarget=s,t.keydownListenerCapture=e.keydownListenerCapture;const i=o;t.keydownTarget.addEventListener("keydown",i,{capture:t.keydownListenerCapture}),t.keydownHandlerAdded=!0}}},eo=(t,e)=>{var n;const o=So();if(o.length){t=t+e,t===-2&&(t=o.length-1),t===o.length?t=0:t===-1&&(t=o.length-1),o[t].focus();return}(n=y())===null||n===void 0||n.focus()},ir=["ArrowRight","ArrowDown"],Kf=["ArrowLeft","ArrowUp"],Yf=(t,e,n)=>{t&&(e.isComposing||e.keyCode===229||(t.stopKeydownPropagation&&e.stopPropagation(),e.key==="Enter"?Uf(e,t):e.key==="Tab"?qf(e):[...ir,...Kf].includes(e.key)?Gf(e.key):e.key==="Escape"&&Xf(e,t,n)))},Uf=(t,e)=>{if(!bn(e.allowEnterKey))reLine truncated
showLoaderOnConfirm should be used together with preConfirm, see usage example:
https://sweetalert2.github.io/#ajax-request`),bp(t),typeof t.title=="string"&&(t.title=t.title.split(`
`).join("<br />")),cf(t)}let ae;var Yt=new WeakMap;class N{constructor(...e){if(Vd(this,Yt,Promise.resolve({isConfirmed:!1,isDenied:!1,isDismissed:!0})),typeof window>"u")return;ae=this;const n=Object.freeze(this.constructor.argsToParams(e));this.params=n,this.isAwaitingPromise=!1,Hd(Yt,this,this._main(ae.params))}_main(e,n={}){if(Cr(Object.assign({},n,e)),h.currentInstance){const i=rt.swalPromiseResolve.get(h.currentInstance),{isAwaitingPromise:r}=h.currentInstance;h.currentInstance._destroy(),r||i({isDismissed:!0}),xo()&&rr()}h.currentInstance=ae;const o=Ep(e,n);vp(o),Object.freeze(o),h.timeout&&(h.timeout.stop(),delete h.timeout),clearTimeout(h.restoreFocusTimeout);const s=yp(ae);return nr(ae,o),O.innerParams.set(ae,o),_p(ae,s,o)}then(e){return Ss(Yt,this).then(e)}finally(e){return Ss(Yt,this).finally(e)}}const _p=(t,e,n)=>new Promise((o,s)=>{const i=r=>{t.close({isDismissed:!0,dismiss:r,isConfirmed:!1,isDenied:!1})};rt.swalPromiseResolve.set(t,o),rt.swalPromiseReject.set(t,s),e.confirmButton.onclick=()=>{yh(t)},e.denyButton.onclick=()=>{Ah(t)},e.cancelButton.onclick=()=>{Th(t,i)},e.closeButton.onclick=()=>{i(mt.close)},Mh(n,e,i),zf(h,n,i),hh(t,n),hp(n),Ap(h,n,i),Tp(e,n),setTimeout(()=>{e.container.scrollTop=0})}),Ep=(t,e)=>{const n=sp(t),o=Object.assign({},Ee,e,n,t);return o.showClass=Object.assign({},Ee.showClass,o.showClass),o.hideClass=Object.assign({},Ee.hideClass,o.hideClass),o.animation===!1&&(o.showClass={backdrop:"swal2-noanimation"},o.hideClass={}),o},yp=t=>{const e={popup:y(),container:F(),actions:$t(),confirmButton:de(),denyButton:ze(),cancelButton:ht(),loader:pt(),closeButton:ko(),validationMessage:vn(),progressSteps:Oo()};return O.domCache.set(t,e),e},Ap=(t,e,n)=>{const o=_n();R(o),e.timer&&(t.timeout=new op(()=>{n("timer"),delete t.timeout},e.timer),e.timerProgressBar&&o&&(P(o),X(o,e,"timerProgressBar"),setTimeout(()=>{t.timeout&&t.timeout.running&&Lo(e.timer)})))},Tp=(t,e)=>{if(!e.toast){if(!bn(e.allowEnterKey)){Wi("allowEnterKey"),kp();return}Cp(t)||Op(t,e)||eo(-1,1)}},Cp=t=>{const e=Array.from(t.popup.querySelectorAll("[autofocus]"));for(const n of e)if(n instanceof HTMLElement&&K(n))return n.focus(),!0;return!1},Op=(t,e)=>e.focusDeny&&K(t.denyButton)?(t.denyButton.focus(),!0):e.focusCancel&&K(t.cancelButton)?(t.cancelButton.focus(),!0):e.focusConfirm&&K(t.confirmButton)?(t.confirmButton.focus(),!0):!1,kp=()=>{document.activeElement instanceof HTMLElement&&typeof document.activeElement.blur=="function"&&document.activeElement.blur()};N.prototype.disableButtons=wr;N.prototype.enableButtons=gr;N.prototype.getInput=hr;N.prototype.disableInput=vr;N.prototype.enableInput=br;N.prototype.hideLoading=an;N.prototype.disableLoading=an;N.prototype.showValidationMessage=_r;N.prototype.resetValidationMessage=Er;N.prototype.close=_e;N.prototype.closePopup=_e;N.prototype.closeModal=_e;N.prototype.closeToast=_e;N.prototype.rejectPromise=cr;N.prototype.update=Or;N.prototype._destroy=kr;Object.assign(N,np);Object.keys(Ph).forEach(t=>{N[t]=function(...e){if(ae&&ae[t])return ae[t](...e)}});N.DismissReason=mt;N.version="11.26.17";const no=N;no.default=no;typeof document<"u"&&(function(t,e){var n=t.createElement("style");if(t.getElementsByTagName("head")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=e);else try{n.innerHTML=e}catch{n.innerText=e}})(document,':root{--swal2-outline: 0 0 0 3px rgba(100, 150, 200, 0.5);--swal2-container-padding: 0.625em;--swal2-backdrop: rgba(0, 0, 0, 0.4);--swal2-backdrop-transition: background-color 0.15s;--swal2-width: 32em;--swal2-padding: 0 0 1.25em;--swal2-border: none;--swal2-border-radius: 0.3125rem;--swal2-background: white;--swal2-color: #545454;--swal2-show-animation: swal2-show 0.3s;--swal2-hide-animation: swal2-hide 0.15s forwards;--swal2-icon-zoom: 1;--swal2-icon-animations: true;--swal2-title-padding: 0.8em 1em 0;--swal2-html-container-padding: 1em 1.6em 0.3em;--swal2-input-border: 1px solid #d9d9d9;--swal2-input-border-radius: 0.1875em;--swal2-input-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px transparent;--swal2-input-background: transparent;--swal2-input-transition: border-color 0.2s, box-shadow 0.2s;--swal2-input-hover-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px transparent;--swal2-input-focus-border: 1px solid #b4dbed;--swal2-input-focus-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px rgba(100, 150, 200, 0.5);--swal2-progress-step-background: #add8e6;--swal2-validation-message-background: #f0f0f0;--swal2-validation-message-color: #666;--swal2-footer-border-color: #eee;--swal2-footer-background: transparent;--swal2-footer-color: inherit;--swal2-timer-progress-bar-background: rgba(0, 0, 0, 0.3);--swal2-close-button-position: initial;--swal2-close-button-inset: auto;--swal2-close-button-font-size: 2.5em;--swal2-close-button-color: #ccc;--swal2-close-button-transition: color 0.2s, box-shadow 0.2s;--swal2-close-button-outline: initial;--swal2-close-button-box-shadow: inset 0 0 0 3px transparent; Line truncated
+3 -5
View File
@@ -3,13 +3,11 @@
<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>
<script type="module" crossorigin src="/assets/index-BsVv6gaD.js"></script>
<link rel="modulepreload" crossorigin href="/assets/vendor-charts-Bcjh2pZL.js">
<link rel="modulepreload" crossorigin href="/assets/vendor-ui-jlFFG6nm.js">
<link rel="stylesheet" crossorigin href="/assets/index-b8NXKHGm.css">
<script type="module" crossorigin src="/assets/index-BfAhXdi6.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-BZ2WYZTa.css">
</head>
<body>
-1
View File
@@ -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

+3
View File
@@ -3,6 +3,7 @@
# First start only: OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD in .env
# Optional: OVPMON_CORS_ORIGINS, OVPMON_HTTP_PORT (host port of the UI, default 80),
# OVPMON_VPN_PORT (host UDP port of OpenVPN, default 1194)
# Optional: OVPMON_CSP_CONNECT_EXTRA (origins the UI may call besides its own, e.g. https://api.example.com; empty by default)
# Install/update with the scripts in deploy/docker (see DOCS/Deployment/Containers/README.md)
#
# Variants A (this file) and B (docker-compose.yml) publish the same host ports and use fixed
@@ -48,6 +49,8 @@ services:
OVPMON_INITIAL_ADMIN_USER: ${OVPMON_INITIAL_ADMIN_USER:-}
OVPMON_INITIAL_ADMIN_PASSWORD: ${OVPMON_INITIAL_ADMIN_PASSWORD:-}
OVPMON_CORS_ORIGINS: ${OVPMON_CORS_ORIGINS:-}
# Extra connect-src origins of the CSP (API on another host), separated by spaces; validated at start
OVP_CSP_CONNECT_EXTRA: ${OVPMON_CSP_CONNECT_EXTRA:-}
healthcheck:
# UI through Nginx, profiler root (FastAPI) and TCP connect to the Flask API
test:
+6 -3
View File
@@ -3,6 +3,7 @@
# First start only: OVPMON_INITIAL_ADMIN_USER / OVPMON_INITIAL_ADMIN_PASSWORD in .env
# Optional: OVPMON_CORS_ORIGINS (comma-separated origins; off by default, UI is same-origin via Nginx)
# Optional: OVPMON_HTTP_PORT (host port of the UI, default 80), OVPMON_VPN_PORT (host UDP port of OpenVPN, default 1194)
# Optional: OVPMON_CSP_CONNECT_EXTRA (origins the UI may call besides its own, e.g. https://api.example.com; empty by default)
# Install/update with the scripts in deploy/docker (see DOCS/Deployment/Containers/README.md)
x-secret: &jwt-secret
@@ -14,7 +15,7 @@ services:
container_name: ovp-ui
restart: unless-stopped
ports:
- "${OVPMON_HTTP_PORT:-80}:80"
- "${OVPMON_HTTP_PORT:-80}:8080"
depends_on:
- app-api
- app-profiler
@@ -25,9 +26,11 @@ services:
OVP_API_PORT: 5001
OVP_PROFILER_HOST: ovp-profiler
OVP_PROFILER_PORT: 8000
# Extra connect-src origins of the CSP (API on another host), separated by spaces; empty = same origin only
OVP_CSP_CONNECT_EXTRA: ${OVPMON_CSP_CONNECT_EXTRA:-}
healthcheck:
# busybox wget exists in nginx:alpine
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/"]
# busybox wget exists in the nginx alpine image; nginx listens on 8080 inside (unprivileged, OVP_UI_PORT)
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/"]
interval: 30s
timeout: 5s
retries: 3