Docs restructure gatherer jwt hardening #2
No files matched your search
@@ -11,7 +11,12 @@ COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Ensure DB directory exists
|
||||
RUN mkdir -p /app/db
|
||||
RUN mkdir -p /app/db /app/backups
|
||||
|
||||
# Migrations of the monitoring database (standard library only), from the build context 'core'
|
||||
# (additional_contexts in docker-compose.yml). A restore migrates the package copy with them.
|
||||
COPY --from=core migrations.py migrate.py db.py /opt/core/
|
||||
ENV OVPMON_CORE_DIR=/opt/core
|
||||
|
||||
# Copy source code and entrypoint
|
||||
COPY . .
|
||||
|
||||
+11
-1
@@ -1,5 +1,6 @@
|
||||
import uvicorn
|
||||
from fastapi import FastAPI
|
||||
import logging
|
||||
import sys
|
||||
import os
|
||||
|
||||
@@ -9,7 +10,7 @@ sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from database import db_path
|
||||
import migrations
|
||||
from routers import system, server, profiles, server_process
|
||||
from routers import system, server, profiles, server_process, backup
|
||||
from utils.logging import setup_logging
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
@@ -20,6 +21,14 @@ setup_logging()
|
||||
# pending while OVPMON_AUTO_MIGRATE=0.
|
||||
migrations.startup_or_exit(db_path)
|
||||
|
||||
# Settings, destinations and history of backup and restore (own SQLite file, see services/backup/store.py).
|
||||
# A failure here must not stop the VPN management: the backup routes then report the error.
|
||||
try:
|
||||
from services.backup import store as backup_store
|
||||
backup_store.init()
|
||||
except Exception:
|
||||
logging.getLogger(__name__).exception("Backup store is not available")
|
||||
|
||||
app = FastAPI(
|
||||
title="OpenVPN Profiler API",
|
||||
description="REST API for managing OpenVPN profiles and configuration",
|
||||
@@ -39,6 +48,7 @@ app.include_router(system.router, prefix="/api", tags=["System"])
|
||||
app.include_router(server.router, prefix="/api", tags=["Server"])
|
||||
app.include_router(profiles.router, prefix="/api", tags=["Profiles"])
|
||||
app.include_router(server_process.router, prefix="/api", tags=["Process Control"])
|
||||
app.include_router(backup.router, prefix="/api", tags=["Backup"])
|
||||
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
|
||||
@@ -6,3 +6,6 @@ python-multipart
|
||||
jinja2
|
||||
pyjwt
|
||||
requests
|
||||
cryptography
|
||||
minio
|
||||
paramiko
|
||||
@@ -0,0 +1,218 @@
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from utils.auth import verify_token
|
||||
from services.backup import BackupError, Busy, Invalid, destinations, engine, package, store
|
||||
|
||||
router = APIRouter(dependencies=[Depends(verify_token)])
|
||||
|
||||
NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 _.-]{0,63}$")
|
||||
PASSPHRASE_MIN = 8
|
||||
|
||||
|
||||
class SettingsUpdate(BaseModel):
|
||||
passphrase: Optional[str] = Field(None, max_length=256) # set or change; never returned
|
||||
clear_passphrase: bool = False
|
||||
default_retention: Optional[int] = Field(None, ge=1, le=1000)
|
||||
server_name: Optional[str] = Field(None, max_length=63) # '' clears it (fallback names are used)
|
||||
|
||||
|
||||
class DestinationIn(BaseModel):
|
||||
name: str = Field(..., max_length=64)
|
||||
type: str = Field(..., max_length=20)
|
||||
enabled: bool = True
|
||||
retention_count: Optional[int] = Field(None, ge=1, le=1000)
|
||||
params: dict = {}
|
||||
secrets: dict = {} # absent, empty or masked values keep the stored secret
|
||||
|
||||
|
||||
class TrustIn(BaseModel):
|
||||
fingerprint: str = Field(..., max_length=80) # the one shown by Test
|
||||
|
||||
|
||||
class RunIn(BaseModel):
|
||||
destination_ids: Optional[list[int]] = None
|
||||
|
||||
|
||||
class RestoreIn(BaseModel):
|
||||
destination_id: int
|
||||
package: str = Field(..., max_length=200)
|
||||
passphrase: Optional[str] = Field(None, max_length=256)
|
||||
|
||||
|
||||
def _fail(e: Exception):
|
||||
"""BackupError family -> HTTP error. Messages never contain secrets."""
|
||||
if isinstance(e, Busy):
|
||||
raise HTTPException(status_code=409, detail=str(e))
|
||||
if isinstance(e, destinations.DestinationError):
|
||||
raise HTTPException(status_code=502, detail=str(e))
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
def _types_info():
|
||||
return [{"id": t, "label": cls.label, "remote": t in destinations.REMOTE_TYPES, "fields": cls.FIELDS,
|
||||
"pins_host_key": bool(cls.PIN_PARAMS)}
|
||||
for t, cls in destinations.DESTINATION_TYPES.items()]
|
||||
|
||||
|
||||
@router.get("/backup/settings")
|
||||
def get_settings():
|
||||
effective, source = engine.effective_server_name()
|
||||
return {
|
||||
"encryption_enabled": store.has_passphrase(),
|
||||
"default_retention": store.default_retention(),
|
||||
"server_name": store.get_server_name(),
|
||||
"effective_server_name": effective,
|
||||
"server_name_source": source,
|
||||
"local_root": destinations.local_root(),
|
||||
"types": _types_info(),
|
||||
}
|
||||
|
||||
|
||||
@router.put("/backup/settings")
|
||||
def update_settings(body: SettingsUpdate):
|
||||
if engine.is_running():
|
||||
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||
if body.passphrase is not None and body.clear_passphrase:
|
||||
raise HTTPException(status_code=400, detail="Give a passphrase or clear it, not both")
|
||||
server_name = (body.server_name or "").strip()
|
||||
if server_name and not package.SERVER_NAME_RE.match(server_name):
|
||||
raise HTTPException(status_code=400, detail="Server name: 1-63 letters, digits, '.' or '-', "
|
||||
"starting with a letter or digit")
|
||||
if body.passphrase is not None:
|
||||
if len(body.passphrase) < PASSPHRASE_MIN:
|
||||
raise HTTPException(status_code=400, detail=f"Passphrase must have at least {PASSPHRASE_MIN} characters")
|
||||
store.set_passphrase(body.passphrase)
|
||||
if body.clear_passphrase:
|
||||
remote = [d["name"] for d in store.list_destinations()
|
||||
if d["enabled"] and d["type"] in destinations.REMOTE_TYPES]
|
||||
if remote:
|
||||
raise HTTPException(status_code=400, detail="Remote destinations need a passphrase: disable or "
|
||||
f"delete them first ({', '.join(remote)})")
|
||||
store.set_passphrase(None)
|
||||
if body.default_retention is not None:
|
||||
store.set_default_retention(body.default_retention)
|
||||
if body.server_name is not None:
|
||||
store.set_server_name(server_name)
|
||||
return get_settings()
|
||||
|
||||
|
||||
@router.get("/backup/destinations")
|
||||
def list_destinations():
|
||||
return store.list_destinations()
|
||||
|
||||
|
||||
def _prepare(body: DestinationIn, previous: Optional[dict]):
|
||||
cls = destinations.DESTINATION_TYPES.get(body.type)
|
||||
if cls is None:
|
||||
raise HTTPException(status_code=400, detail=f"Unsupported destination type: {body.type}")
|
||||
name = body.name.strip()
|
||||
if not NAME_RE.match(name):
|
||||
raise HTTPException(status_code=400, detail="Name: 1-64 letters, digits, spaces, '.', '_' or '-'")
|
||||
same_type = bool(previous and previous["type"] == body.type)
|
||||
# Secrets of another type never carry over
|
||||
keep = previous["secrets"] if same_type else {}
|
||||
given = {k: v for k, v in body.secrets.items() if isinstance(v, str) and v and v != store.MASK}
|
||||
# A pinned host key comes only from the trust call, never from the client
|
||||
client_params = {k: v for k, v in body.params.items() if k not in cls.PIN_PARAMS}
|
||||
try:
|
||||
params, secrets = cls.validate(client_params, given, keep)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
if same_type and cls.PIN_PARAMS:
|
||||
old = previous["params"]
|
||||
if all(old.get(k) == params.get(k) for k in cls.PIN_DEPENDS): # same server: the pin stays
|
||||
params.update({k: old[k] for k in cls.PIN_PARAMS if old.get(k)})
|
||||
retention = body.retention_count or (previous["retention_count"] if previous else store.default_retention())
|
||||
return name, params, secrets, retention
|
||||
|
||||
|
||||
@router.post("/backup/destinations", status_code=201)
|
||||
def create_destination(body: DestinationIn):
|
||||
name, params, secrets, retention = _prepare(body, None)
|
||||
try:
|
||||
dest_id = store.save_destination(None, name, body.type, body.enabled, retention, params, secrets)
|
||||
except BackupError as e:
|
||||
raise HTTPException(status_code=409, detail=str(e))
|
||||
return store.get_destination(dest_id)
|
||||
|
||||
|
||||
@router.put("/backup/destinations/{dest_id}")
|
||||
def update_destination(dest_id: int, body: DestinationIn):
|
||||
if engine.is_running():
|
||||
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||
previous = store.get_destination(dest_id, with_secrets=True)
|
||||
if not previous:
|
||||
raise HTTPException(status_code=404, detail="Destination not found")
|
||||
name, params, secrets, retention = _prepare(body, previous)
|
||||
try:
|
||||
store.save_destination(dest_id, name, body.type, body.enabled, retention, params, secrets)
|
||||
except BackupError as e:
|
||||
raise HTTPException(status_code=409, detail=str(e))
|
||||
return store.get_destination(dest_id)
|
||||
|
||||
|
||||
@router.delete("/backup/destinations/{dest_id}")
|
||||
def delete_destination(dest_id: int):
|
||||
if engine.is_running():
|
||||
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||
if not store.delete_destination(dest_id):
|
||||
raise HTTPException(status_code=404, detail="Destination not found")
|
||||
return {"message": "Destination deleted"}
|
||||
|
||||
|
||||
@router.post("/backup/destinations/{dest_id}/test")
|
||||
def test_destination(dest_id: int):
|
||||
try:
|
||||
return engine.test_destination(dest_id)
|
||||
except BackupError as e:
|
||||
_fail(e)
|
||||
|
||||
|
||||
@router.post("/backup/destinations/{dest_id}/trust-host-key")
|
||||
def trust_host_key(dest_id: int, body: TrustIn):
|
||||
if engine.is_running():
|
||||
raise HTTPException(status_code=409, detail="A backup or restore is running")
|
||||
try:
|
||||
return engine.trust_host_key(dest_id, body.fingerprint.strip())
|
||||
except BackupError as e:
|
||||
_fail(e)
|
||||
|
||||
|
||||
@router.get("/backup/destinations/{dest_id}/packages")
|
||||
def list_packages(dest_id: int):
|
||||
try:
|
||||
return {"packages": engine.list_packages(dest_id)}
|
||||
except BackupError as e:
|
||||
_fail(e)
|
||||
|
||||
|
||||
@router.post("/backup/run", status_code=202)
|
||||
def run_backup(body: RunIn = RunIn()):
|
||||
try:
|
||||
engine.start_backup(body.destination_ids)
|
||||
except BackupError as e:
|
||||
_fail(e)
|
||||
return {"state": "running"}
|
||||
|
||||
|
||||
@router.post("/backup/restore", status_code=202)
|
||||
def run_restore(body: RestoreIn):
|
||||
try:
|
||||
engine.start_restore(body.destination_id, body.package, body.passphrase)
|
||||
except BackupError as e:
|
||||
_fail(e)
|
||||
return {"state": "running"}
|
||||
|
||||
|
||||
@router.get("/backup/status")
|
||||
def get_status():
|
||||
return engine.status()
|
||||
|
||||
|
||||
@router.get("/backup/history")
|
||||
def get_history(limit: int = Query(20, ge=1, le=100)):
|
||||
return store.history_list(limit)
|
||||
@@ -4,6 +4,7 @@ from fastapi.responses import FileResponse
|
||||
from sqlalchemy.orm import Session
|
||||
from database import get_db
|
||||
from utils.auth import verify_token
|
||||
from utils.guards import forbid_during_restore
|
||||
from models import UserProfile
|
||||
from schemas import UserProfile as UserProfileSchema, UserProfileCreate, UserProfileNoteUpdate
|
||||
from services import pki, generator
|
||||
@@ -69,7 +70,7 @@ def list_profiles(db: Session = Depends(get_db)):
|
||||
|
||||
return updated_profiles
|
||||
|
||||
@router.post("/profiles", response_model=UserProfileSchema)
|
||||
@router.post("/profiles", response_model=UserProfileSchema, dependencies=[Depends(forbid_during_restore)])
|
||||
def create_profile(
|
||||
profile_in: UserProfileCreate,
|
||||
db: Session = Depends(get_db)
|
||||
@@ -123,7 +124,7 @@ def create_profile(
|
||||
db.refresh(new_profile)
|
||||
return new_profile
|
||||
|
||||
@router.put("/profiles/{profile_id}/note", response_model=UserProfileSchema)
|
||||
@router.put("/profiles/{profile_id}/note", response_model=UserProfileSchema, dependencies=[Depends(forbid_during_restore)])
|
||||
def update_profile_note(profile_id: int, body: UserProfileNoteUpdate, db: Session = Depends(get_db)):
|
||||
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
|
||||
if not profile:
|
||||
@@ -134,7 +135,7 @@ def update_profile_note(profile_id: int, body: UserProfileNoteUpdate, db: Sessio
|
||||
db.refresh(profile)
|
||||
return profile
|
||||
|
||||
@router.delete("/profiles/{profile_id}")
|
||||
@router.delete("/profiles/{profile_id}", dependencies=[Depends(forbid_during_restore)])
|
||||
def revoke_profile(profile_id: int, db: Session = Depends(get_db)):
|
||||
profile = db.query(UserProfile).filter(UserProfile.id == profile_id).first()
|
||||
if not profile:
|
||||
|
||||
@@ -4,13 +4,14 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from database import get_db
|
||||
from utils.auth import verify_token
|
||||
from utils.guards import forbid_during_restore
|
||||
from services import generator, process, config, pki
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(dependencies=[Depends(verify_token)])
|
||||
|
||||
@router.post("/server/configure")
|
||||
@router.post("/server/configure", dependencies=[Depends(forbid_during_restore)])
|
||||
def configure_server(db: Session = Depends(get_db)):
|
||||
try:
|
||||
pki.require_server_ready(db)
|
||||
|
||||
@@ -4,6 +4,7 @@ from services import process, pki
|
||||
from database import get_db
|
||||
from sqlalchemy.orm import Session
|
||||
from utils.auth import verify_token
|
||||
from utils.guards import forbid_during_restore
|
||||
from typing import Optional
|
||||
from fastapi import Depends
|
||||
|
||||
@@ -22,7 +23,7 @@ class ProcessStats(BaseModel):
|
||||
memory_mb: float
|
||||
uptime: Optional[str] = None
|
||||
|
||||
@router.post("/server/process/{action}", response_model=ProcessActionResponse)
|
||||
@router.post("/server/process/{action}", response_model=ProcessActionResponse, dependencies=[Depends(forbid_during_restore)])
|
||||
def manage_process(action: str, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Control the OpenVPN server process.
|
||||
|
||||
@@ -2,6 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from database import get_db
|
||||
from utils.auth import verify_token
|
||||
from utils.guards import forbid_during_restore
|
||||
from schemas import (
|
||||
ConfigResponse, SystemSettings, PKISetting,
|
||||
SystemSettingsUpdate, PKISettingUpdate
|
||||
@@ -22,14 +23,14 @@ def get_config(
|
||||
response.pki = config.get_pki_settings(db)
|
||||
return response
|
||||
|
||||
@router.put("/config/server", response_model=SystemSettings)
|
||||
@router.put("/config/server", response_model=SystemSettings, dependencies=[Depends(forbid_during_restore)])
|
||||
def update_server_config(
|
||||
settings: SystemSettingsUpdate,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
return config.update_system_settings(db, settings)
|
||||
|
||||
@router.put("/config/pki", response_model=PKISetting)
|
||||
@router.put("/config/pki", response_model=PKISetting, dependencies=[Depends(forbid_during_restore)])
|
||||
def update_pki_config(
|
||||
settings: PKISettingUpdate,
|
||||
db: Session = Depends(get_db)
|
||||
@@ -48,7 +49,7 @@ def init_system_pki(db: Session = Depends(get_db)):
|
||||
def get_init_status(db: Session = Depends(get_db)):
|
||||
return pki.init_status(db)
|
||||
|
||||
@router.delete("/system/pki")
|
||||
@router.delete("/system/pki", dependencies=[Depends(forbid_during_restore)])
|
||||
def clear_system_pki(db: Session = Depends(get_db)):
|
||||
if pki.is_init_running():
|
||||
raise HTTPException(status_code=409, detail="PKI initialization is running")
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Backup and restore of the application data (databases, PKI, client profiles).
|
||||
|
||||
Modules:
|
||||
package.py package format (tar.gz + manifest), snapshots, safe extraction
|
||||
crypto.py optional package encryption (AES-256-GCM, scrypt)
|
||||
destinations.py where packages go: common interface, local folder and S3 (minio)
|
||||
store.py settings, destinations and history in a separate SQLite file
|
||||
engine.py backup job and restore engine (one background job at a time)
|
||||
"""
|
||||
|
||||
|
||||
class BackupError(Exception):
|
||||
"""A backup or restore step failed. The message is safe to show to the user (no secrets)."""
|
||||
|
||||
|
||||
class Invalid(BackupError):
|
||||
"""The request cannot be accepted as it is (API: 400)."""
|
||||
|
||||
|
||||
class Busy(BackupError):
|
||||
"""Another backup or restore job is running (API: 409)."""
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Package encryption: AES-256-GCM in chunks, key from the passphrase with scrypt.
|
||||
|
||||
File layout:
|
||||
magic "OVPBAKE1" | log2(N) 1 byte | r 1 byte | p 1 byte | salt 16 | nonce prefix 8 (header, 35 bytes)
|
||||
then chunks of CHUNK bytes of plaintext, each stored as ciphertext + 16 byte tag.
|
||||
Chunk i uses the nonce prefix || i (4 bytes, big endian). The header and a "final chunk" flag
|
||||
are authenticated data of every chunk, so a truncated, reordered or modified file is rejected.
|
||||
"""
|
||||
import os
|
||||
import struct
|
||||
|
||||
from cryptography.exceptions import InvalidTag
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
|
||||
|
||||
from . import BackupError
|
||||
|
||||
MAGIC = b"OVPBAKE1"
|
||||
HEADER_LEN = len(MAGIC) + 3 + 16 + 8
|
||||
CHUNK = 1024 * 1024
|
||||
TAG = 16
|
||||
SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P = 15, 8, 1 # about 32 MiB of memory
|
||||
# Bounds for the parameters read from a file: a crafted header must not exhaust memory or CPU
|
||||
MAX_LOG_N, MAX_R, MAX_P = 20, 16, 4
|
||||
|
||||
|
||||
class WrongPassphrase(BackupError):
|
||||
"""Wrong passphrase, or the file is damaged (AES-GCM cannot tell the two apart)."""
|
||||
|
||||
|
||||
def is_encrypted(path: str) -> bool:
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
return f.read(len(MAGIC)) == MAGIC
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _derive(passphrase: str, salt: bytes, log_n: int, r: int, p: int) -> bytes:
|
||||
return Scrypt(salt=salt, length=32, n=2 ** log_n, r=r, p=p).derive(passphrase.encode("utf-8"))
|
||||
|
||||
|
||||
def _nonce(prefix: bytes, index: int) -> bytes:
|
||||
return prefix + struct.pack(">I", index)
|
||||
|
||||
|
||||
def _aad(header: bytes, final: bool) -> bytes:
|
||||
return header + (b"\x01" if final else b"\x00")
|
||||
|
||||
|
||||
def encrypt_file(src: str, dst: str, passphrase: str) -> None:
|
||||
if not passphrase:
|
||||
raise BackupError("Passphrase is empty")
|
||||
salt, prefix = os.urandom(16), os.urandom(8)
|
||||
header = MAGIC + bytes([SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P]) + salt + prefix
|
||||
aes = AESGCM(_derive(passphrase, salt, SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P))
|
||||
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with open(src, "rb") as fin, os.fdopen(fd, "wb") as fout:
|
||||
fout.write(header)
|
||||
index = 0
|
||||
block = fin.read(CHUNK)
|
||||
while True:
|
||||
nxt = fin.read(CHUNK)
|
||||
final = not nxt
|
||||
fout.write(aes.encrypt(_nonce(prefix, index), block, _aad(header, final)))
|
||||
if final:
|
||||
break
|
||||
block, index = nxt, index + 1
|
||||
|
||||
|
||||
def decrypt_file(src: str, dst: str, passphrase: str) -> None:
|
||||
if not passphrase:
|
||||
raise WrongPassphrase("Passphrase is required for an encrypted package")
|
||||
with open(src, "rb") as fin:
|
||||
header = fin.read(HEADER_LEN)
|
||||
if len(header) != HEADER_LEN or not header.startswith(MAGIC):
|
||||
raise BackupError("Not an encrypted package (bad header)")
|
||||
log_n, r, p = header[8], header[9], header[10]
|
||||
if not (1 <= log_n <= MAX_LOG_N and 1 <= r <= MAX_R and 1 <= p <= MAX_P):
|
||||
raise BackupError("Encrypted package has unsupported key derivation parameters")
|
||||
salt, prefix = header[11:27], header[27:35]
|
||||
aes = AESGCM(_derive(passphrase, salt, log_n, r, p))
|
||||
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "wb") as fout:
|
||||
index = 0
|
||||
block = fin.read(CHUNK + TAG)
|
||||
if not block:
|
||||
raise BackupError("Encrypted package is truncated")
|
||||
while True:
|
||||
nxt = fin.read(CHUNK + TAG)
|
||||
final = not nxt
|
||||
try:
|
||||
fout.write(aes.decrypt(_nonce(prefix, index), block, _aad(header, final)))
|
||||
except InvalidTag:
|
||||
raise WrongPassphrase("Wrong passphrase, or the package is damaged") from None
|
||||
if final:
|
||||
break
|
||||
block, index = nxt, index + 1
|
||||
@@ -0,0 +1,876 @@
|
||||
"""Backup destinations. Every type implements the same interface:
|
||||
|
||||
test() check the connection and the right to write and delete; returns a message
|
||||
put(local_path, name) store a file under name
|
||||
list() [{"name", "size", "mtime"}] of the files in the destination folder
|
||||
get(name, local_path) download to a local file
|
||||
delete(name) remove a file
|
||||
|
||||
Implemented: "local", "s3", "sftp" and "ftp". To add a type (smb): write a Destination subclass
|
||||
with FIELDS, validate() and the five methods, and add it to DESTINATION_TYPES. The API accepts
|
||||
exactly the types of that registry.
|
||||
"""
|
||||
import hmac
|
||||
import hashlib
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import ssl
|
||||
import stat
|
||||
import uuid
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from . import BackupError
|
||||
from .package import PACKAGE_RE
|
||||
|
||||
DEFAULT_LOCAL_ROOT = "/var/lib/ovpmon/backups"
|
||||
SAFE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
||||
FOLDER_SEGMENT_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
|
||||
HOST_RE = re.compile(r"^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$")
|
||||
BUCKET_RE = re.compile(r"^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$")
|
||||
REGION_RE = re.compile(r"^[A-Za-z0-9-]{1,40}$")
|
||||
|
||||
|
||||
class DestinationError(BackupError):
|
||||
"""The destination refused or could not be reached. The message never contains secrets."""
|
||||
|
||||
|
||||
class NeedsTrust(DestinationError):
|
||||
"""The SSH host key of the server is not pinned yet (or changed). Carries what the server showed."""
|
||||
|
||||
def __init__(self, message: str, fingerprint: str, key_type: str, changed: bool = False):
|
||||
super().__init__(message)
|
||||
self.fingerprint, self.key_type, self.changed = fingerprint, key_type, changed
|
||||
|
||||
|
||||
def local_root() -> str:
|
||||
return os.environ.get("OVPMON_BACKUP_LOCAL_ROOT", "").strip() or DEFAULT_LOCAL_ROOT
|
||||
|
||||
|
||||
def _check_name(name: str) -> str:
|
||||
if not isinstance(name, str) or not SAFE_NAME_RE.match(name) or ".." in name:
|
||||
raise DestinationError("Invalid file name")
|
||||
return name
|
||||
|
||||
|
||||
def _short(e: Exception) -> str:
|
||||
return f"{type(e).__name__}: {str(e)[:300]}"
|
||||
|
||||
|
||||
class Destination:
|
||||
type = ""
|
||||
label = ""
|
||||
# Field description for the UI: name, label, kind (text|number|bool|secret|secret_multiline),
|
||||
# required, default, hint; optional warning + warn_if (shown while the value equals warn_if)
|
||||
FIELDS: list = []
|
||||
# Parameters set by pinning a host key (never accepted from the client, kept while the parameters
|
||||
# of PIN_DEPENDS stay the same); empty for types without pinning
|
||||
PIN_PARAMS: tuple = ()
|
||||
PIN_DEPENDS: tuple = ()
|
||||
|
||||
def __init__(self, params: dict, secrets: dict):
|
||||
self.params = params
|
||||
self.secrets = secrets
|
||||
|
||||
@classmethod
|
||||
def validate(cls, params: dict, secrets: dict, previous_secrets: Optional[dict] = None):
|
||||
"""Return (clean_params, clean_secrets) or raise ValueError with a message for the user."""
|
||||
raise NotImplementedError
|
||||
|
||||
def test(self) -> str:
|
||||
raise NotImplementedError
|
||||
|
||||
def put(self, local_path: str, name: str) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def list(self) -> list:
|
||||
raise NotImplementedError
|
||||
|
||||
def get(self, name: str, local_path: str) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def delete(self, name: str) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def fetch_host_key(self):
|
||||
"""(fingerprint, key type) the server shows now; no credentials are sent. Pinning types only."""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def _unknown_keys(given: dict, allowed: set, what: str):
|
||||
extra = sorted(set(given) - allowed)
|
||||
if extra:
|
||||
raise ValueError(f"Unknown {what}: {', '.join(extra)}")
|
||||
|
||||
|
||||
# --- local folder --------------------------------------------------------------------------
|
||||
|
||||
class LocalDestination(Destination):
|
||||
"""A sub folder inside the root OVPMON_BACKUP_LOCAL_ROOT. Paths outside the root and
|
||||
symbolic links are rejected."""
|
||||
type = "local"
|
||||
label = "Local folder"
|
||||
FIELDS = [
|
||||
{"name": "folder", "label": "Folder (inside the backup root)", "kind": "text", "required": True,
|
||||
"default": "default", "hint": "Sub folder of the server's backup root, for example 'daily'"},
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def validate(cls, params, secrets, previous_secrets=None):
|
||||
_unknown_keys(params, {"folder"}, "parameters")
|
||||
if secrets:
|
||||
raise ValueError("A local destination has no secrets")
|
||||
folder = str(params.get("folder", "")).strip().strip("/")
|
||||
if not folder:
|
||||
raise ValueError("Folder is required")
|
||||
parts = folder.split("/")
|
||||
if len(parts) > 4 or not all(FOLDER_SEGMENT_RE.match(p) and ".." not in p for p in parts):
|
||||
raise ValueError("Folder must be a relative path of letters, digits, '.', '_' and '-' "
|
||||
"(no '..', no leading dot, at most 4 levels)")
|
||||
return {"folder": "/".join(parts)}, {}
|
||||
|
||||
def _root(self) -> str:
|
||||
root = local_root()
|
||||
try:
|
||||
os.makedirs(root, mode=0o700, exist_ok=True)
|
||||
except OSError as e:
|
||||
raise DestinationError(f"Backup root {root} is not usable: {e.strerror or e}") from e
|
||||
return os.path.realpath(root)
|
||||
|
||||
def _dir(self, create: bool) -> str:
|
||||
root = self._root()
|
||||
current = root
|
||||
for part in self.params["folder"].split("/"):
|
||||
current = os.path.join(current, part)
|
||||
try:
|
||||
st = os.lstat(current)
|
||||
except FileNotFoundError:
|
||||
if not create:
|
||||
raise DestinationError("Folder does not exist yet") from None
|
||||
try:
|
||||
os.mkdir(current, 0o700)
|
||||
except OSError as e:
|
||||
raise DestinationError(f"Cannot create the folder: {e.strerror or e}") from e
|
||||
continue
|
||||
if stat.S_ISLNK(st.st_mode) or not stat.S_ISDIR(st.st_mode):
|
||||
raise DestinationError("Folder is a symbolic link or not a directory: refused")
|
||||
real = os.path.realpath(current)
|
||||
if real != root and not real.startswith(root + os.sep):
|
||||
raise DestinationError("Folder is outside the backup root: refused")
|
||||
return real
|
||||
|
||||
def test(self) -> str:
|
||||
directory = self._dir(create=True)
|
||||
probe = os.path.join(directory, f".ovpmon-test-{uuid.uuid4().hex[:8]}")
|
||||
try:
|
||||
with open(probe, "wb") as f:
|
||||
f.write(b"ok")
|
||||
os.remove(probe)
|
||||
except OSError as e:
|
||||
raise DestinationError(f"Cannot write to the folder: {e.strerror or e}") from e
|
||||
free = shutil.disk_usage(directory).free // (1024 * 1024)
|
||||
return f"Folder is writable ({free} MB free)"
|
||||
|
||||
def put(self, local_path, name):
|
||||
_check_name(name)
|
||||
directory = self._dir(create=True)
|
||||
final = os.path.join(directory, name)
|
||||
tmp = os.path.join(directory, f".{name}.part")
|
||||
try:
|
||||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "wb") as out, open(local_path, "rb") as src:
|
||||
shutil.copyfileobj(src, out, 1024 * 1024)
|
||||
os.replace(tmp, final)
|
||||
except OSError as e:
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise DestinationError(f"Cannot write the package: {e.strerror or e}") from e
|
||||
|
||||
def list(self):
|
||||
try:
|
||||
directory = self._dir(create=False)
|
||||
except DestinationError as e:
|
||||
if "does not exist" in str(e):
|
||||
return []
|
||||
raise
|
||||
out = []
|
||||
with os.scandir(directory) as it:
|
||||
for entry in it:
|
||||
try:
|
||||
st = entry.stat(follow_symlinks=False)
|
||||
except OSError:
|
||||
continue
|
||||
if stat.S_ISREG(st.st_mode) and not entry.name.startswith("."):
|
||||
out.append({"name": entry.name, "size": st.st_size, "mtime": st.st_mtime})
|
||||
return out
|
||||
|
||||
def get(self, name, local_path):
|
||||
_check_name(name)
|
||||
path = os.path.join(self._dir(create=False), name)
|
||||
try:
|
||||
st = os.lstat(path)
|
||||
if not stat.S_ISREG(st.st_mode):
|
||||
raise DestinationError("Not a regular file: refused")
|
||||
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "wb") as out, open(path, "rb") as src:
|
||||
shutil.copyfileobj(src, out, 1024 * 1024)
|
||||
except OSError as e:
|
||||
raise DestinationError(f"Cannot read the package: {e.strerror or e}") from e
|
||||
|
||||
def delete(self, name):
|
||||
_check_name(name)
|
||||
path = os.path.join(self._dir(create=False), name)
|
||||
try:
|
||||
if stat.S_ISREG(os.lstat(path).st_mode):
|
||||
os.remove(path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError as e:
|
||||
raise DestinationError(f"Cannot delete the package: {e.strerror or e}") from e
|
||||
|
||||
|
||||
# --- S3 (minio client) ---------------------------------------------------------------------
|
||||
|
||||
class S3Destination(Destination):
|
||||
"""AWS S3 or a compatible store, through the minio Python SDK."""
|
||||
type = "s3"
|
||||
label = "S3 bucket"
|
||||
FIELDS = [
|
||||
{"name": "endpoint", "label": "Endpoint (host[:port])", "kind": "text", "required": True,
|
||||
"default": "s3.amazonaws.com", "hint": "Without http:// or https://"},
|
||||
{"name": "secure", "label": "Use TLS (https)", "kind": "bool", "required": False, "default": True},
|
||||
{"name": "region", "label": "Region (optional)", "kind": "text", "required": False, "default": ""},
|
||||
{"name": "bucket", "label": "Bucket", "kind": "text", "required": True, "default": ""},
|
||||
{"name": "prefix", "label": "Prefix (optional)", "kind": "text", "required": False, "default": "",
|
||||
"hint": "Folder inside the bucket, for example 'ovpmon/'"},
|
||||
{"name": "access_key", "label": "Access key", "kind": "secret", "required": True},
|
||||
{"name": "secret_key", "label": "Secret key", "kind": "secret", "required": True},
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def validate(cls, params, secrets, previous_secrets=None):
|
||||
_unknown_keys(params, {"endpoint", "secure", "region", "bucket", "prefix"}, "parameters")
|
||||
_unknown_keys(secrets, {"access_key", "secret_key"}, "secrets")
|
||||
endpoint = str(params.get("endpoint", "")).strip()
|
||||
host, _, port = endpoint.partition(":")
|
||||
if not endpoint or "/" in endpoint or not HOST_RE.match(host) or (port and not (port.isdigit() and 0 < int(port) < 65536)):
|
||||
raise ValueError("Endpoint must be host[:port] without http:// or a path")
|
||||
bucket = str(params.get("bucket", "")).strip()
|
||||
if not BUCKET_RE.match(bucket) or ".." in bucket:
|
||||
raise ValueError("Bucket name is invalid (3-63 lowercase letters, digits, '.' and '-')")
|
||||
region = str(params.get("region", "") or "").strip()
|
||||
if region and not REGION_RE.match(region):
|
||||
raise ValueError("Region is invalid")
|
||||
prefix = str(params.get("prefix", "") or "").strip().strip("/")
|
||||
if prefix:
|
||||
parts = prefix.split("/")
|
||||
if len(prefix) > 200 or not all(re.match(r"^[A-Za-z0-9][A-Za-z0-9._ -]{0,63}$", p) for p in parts) or ".." in prefix:
|
||||
raise ValueError("Prefix is invalid: use folders of letters, digits, '.', '_', '-' and spaces")
|
||||
prefix += "/"
|
||||
clean_secrets = {}
|
||||
previous = previous_secrets or {}
|
||||
for key in ("access_key", "secret_key"):
|
||||
value = str(secrets.get(key) or "").strip() or previous.get(key, "")
|
||||
if not value:
|
||||
raise ValueError(f"{'Access key' if key == 'access_key' else 'Secret key'} is required")
|
||||
if len(value) > 512:
|
||||
raise ValueError("Key is too long")
|
||||
clean_secrets[key] = value
|
||||
clean = {"endpoint": endpoint, "secure": bool(params.get("secure", True)),
|
||||
"region": region, "bucket": bucket, "prefix": prefix}
|
||||
return clean, clean_secrets
|
||||
|
||||
def _client(self):
|
||||
try:
|
||||
import urllib3
|
||||
from minio import Minio
|
||||
except ImportError as e: # the package is in requirements.txt; this is a broken installation
|
||||
raise DestinationError("The 'minio' library is not installed") from e
|
||||
http = urllib3.PoolManager(timeout=urllib3.Timeout(connect=10, read=120),
|
||||
retries=urllib3.Retry(total=2, backoff_factor=0.5))
|
||||
return Minio(self.params["endpoint"], access_key=self.secrets["access_key"],
|
||||
secret_key=self.secrets["secret_key"], secure=self.params["secure"],
|
||||
region=self.params["region"] or None, http_client=http)
|
||||
|
||||
def _call(self, fn):
|
||||
from minio.error import S3Error
|
||||
try:
|
||||
return fn()
|
||||
except DestinationError:
|
||||
raise
|
||||
except S3Error as e:
|
||||
raise DestinationError(f"S3 error {e.code}: {str(e.message)[:200]}") from e
|
||||
except Exception as e:
|
||||
raise DestinationError(_short(e)) from e
|
||||
|
||||
def _key(self, name: str) -> str:
|
||||
return self.params["prefix"] + _check_name(name)
|
||||
|
||||
def test(self) -> str:
|
||||
client = self._client()
|
||||
bucket = self.params["bucket"]
|
||||
|
||||
def probe():
|
||||
if not client.bucket_exists(bucket):
|
||||
raise DestinationError(f"Bucket '{bucket}' does not exist or is not visible to this key")
|
||||
key = self.params["prefix"] + f".ovpmon-test-{uuid.uuid4().hex[:8]}"
|
||||
import io
|
||||
client.put_object(bucket, key, io.BytesIO(b"ok"), 2)
|
||||
try:
|
||||
client.remove_object(bucket, key)
|
||||
except Exception:
|
||||
return "Bucket is writable, but deleting objects is not allowed (rotation will not work)"
|
||||
return "Bucket is reachable, write and delete work"
|
||||
return self._call(probe)
|
||||
|
||||
def put(self, local_path, name):
|
||||
client = self._client()
|
||||
self._call(lambda: client.fput_object(self.params["bucket"], self._key(name), local_path,
|
||||
content_type="application/octet-stream"))
|
||||
|
||||
def list(self):
|
||||
client = self._client()
|
||||
prefix = self.params["prefix"]
|
||||
|
||||
def run():
|
||||
out = []
|
||||
for obj in client.list_objects(self.params["bucket"], prefix=prefix or None, recursive=False):
|
||||
if obj.is_dir or not obj.object_name.startswith(prefix):
|
||||
continue
|
||||
name = obj.object_name[len(prefix):]
|
||||
if "/" in name or not name:
|
||||
continue
|
||||
mtime = obj.last_modified.timestamp() if obj.last_modified else None
|
||||
out.append({"name": name, "size": obj.size or 0, "mtime": mtime})
|
||||
return out
|
||||
return self._call(run)
|
||||
|
||||
def get(self, name, local_path):
|
||||
client = self._client()
|
||||
|
||||
def run():
|
||||
resp = client.get_object(self.params["bucket"], self._key(name))
|
||||
try:
|
||||
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "wb") as out:
|
||||
shutil.copyfileobj(resp, out, 1024 * 1024)
|
||||
finally:
|
||||
resp.close()
|
||||
resp.release_conn()
|
||||
self._call(run)
|
||||
|
||||
def delete(self, name):
|
||||
client = self._client()
|
||||
self._call(lambda: client.remove_object(self.params["bucket"], self._key(name)))
|
||||
|
||||
|
||||
# --- shared by SFTP and FTP ----------------------------------------------------------------
|
||||
|
||||
CONNECT_TIMEOUT = 15 # seconds: connection, banner, login
|
||||
TRANSFER_TIMEOUT = 120 # seconds without data on an open transfer
|
||||
USER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._@-]{0,127}$")
|
||||
FINGERPRINT_RE = re.compile(r"^SHA256:[A-Za-z0-9+/]{43}$")
|
||||
|
||||
|
||||
def _check_host_port(params: dict, default_port: int):
|
||||
host = str(params.get("host", "")).strip()
|
||||
if not host or not HOST_RE.match(host):
|
||||
raise ValueError("Host must be a host name or an IPv4 address")
|
||||
try:
|
||||
port = int(params.get("port") or default_port)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("Port must be a number") from None
|
||||
if not 0 < port < 65536:
|
||||
raise ValueError("Port must be between 1 and 65535")
|
||||
return host, port
|
||||
|
||||
|
||||
def _check_username(params: dict) -> str:
|
||||
user = str(params.get("username", "")).strip()
|
||||
if not USER_RE.match(user):
|
||||
raise ValueError("User name is required (letters, digits, '.', '_', '-', '@')")
|
||||
return user
|
||||
|
||||
|
||||
def _check_directory(params: dict) -> str:
|
||||
"""Remote directory: the same rule as the local folder (relative, no '..', at most 4 levels)."""
|
||||
directory = str(params.get("directory", "")).strip().rstrip("/")
|
||||
if not directory:
|
||||
raise ValueError("Directory is required")
|
||||
if directory.startswith("/"):
|
||||
raise ValueError("Directory must be relative to the login directory of the user (no leading '/')")
|
||||
parts = directory.split("/")
|
||||
if len(parts) > 4 or not all(FOLDER_SEGMENT_RE.match(p) and ".." not in p for p in parts):
|
||||
raise ValueError("Directory must be a relative path of letters, digits, '.', '_' and '-' "
|
||||
"(no '..', no leading dot, at most 4 levels)")
|
||||
return "/".join(parts)
|
||||
|
||||
|
||||
def _secret_value(secrets: dict, key: str, label: str, limit: int = 512) -> str:
|
||||
value = str(secrets.get(key) or "").strip()
|
||||
if len(value) > limit:
|
||||
raise ValueError(f"{label} is too long")
|
||||
return value
|
||||
|
||||
|
||||
def _ssh_fingerprint(key) -> str:
|
||||
return "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
# --- SFTP (paramiko) -----------------------------------------------------------------------
|
||||
|
||||
def _paramiko():
|
||||
try:
|
||||
import paramiko
|
||||
except ImportError as e: # the package is in requirements.txt; this is a broken installation
|
||||
raise DestinationError("The 'paramiko' library is not installed") from e
|
||||
return paramiko
|
||||
|
||||
|
||||
def _load_private_key(text: str, passphrase: str):
|
||||
"""paramiko key object of a PEM / OpenSSH private key text. ValueError without any key material."""
|
||||
paramiko = _paramiko()
|
||||
for cls in (paramiko.Ed25519Key, paramiko.ECDSAKey, paramiko.RSAKey):
|
||||
try:
|
||||
return cls.from_private_key(io.StringIO(text), password=passphrase or None)
|
||||
except Exception:
|
||||
continue # not this key type, or a wrong passphrase: the message below covers both
|
||||
raise ValueError("The private key cannot be read: check the key text and its passphrase "
|
||||
"(supported: RSA, ECDSA, Ed25519; OpenSSH or PEM)")
|
||||
|
||||
|
||||
class SFTPDestination(Destination):
|
||||
"""SFTP server. The SSH host key is pinned by its SHA-256 fingerprint: the first Test shows it,
|
||||
the administrator confirms it ('Trust'), after that every connection must present exactly that
|
||||
key. Nothing is copied, listed, read or deleted while the key is not pinned."""
|
||||
type = "sftp"
|
||||
label = "SFTP server"
|
||||
PIN_PARAMS = ("host_key", "host_key_type")
|
||||
PIN_DEPENDS = ("host", "port")
|
||||
FIELDS = [
|
||||
{"name": "host", "label": "Host", "kind": "text", "required": True, "default": "",
|
||||
"hint": "Host name or IPv4 address"},
|
||||
{"name": "port", "label": "Port", "kind": "number", "required": True, "default": 22},
|
||||
{"name": "username", "label": "User name", "kind": "text", "required": True, "default": ""},
|
||||
{"name": "directory", "label": "Directory", "kind": "text", "required": True, "default": "ovpmon-backups",
|
||||
"hint": "Relative to the login directory of the user; created if missing"},
|
||||
{"name": "password", "label": "Password", "kind": "secret", "required": False,
|
||||
"hint": "Password or private key: give one of them"},
|
||||
{"name": "private_key", "label": "Private key (PEM / OpenSSH text)", "kind": "secret_multiline",
|
||||
"required": False},
|
||||
{"name": "key_passphrase", "label": "Private key passphrase (if the key is encrypted)", "kind": "secret",
|
||||
"required": False},
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def validate(cls, params, secrets, previous_secrets=None):
|
||||
_unknown_keys(params, {"host", "port", "username", "directory"}, "parameters")
|
||||
_unknown_keys(secrets, {"password", "private_key", "key_passphrase"}, "secrets")
|
||||
host, port = _check_host_port(params, 22)
|
||||
clean = {"host": host, "port": port, "username": _check_username(params),
|
||||
"directory": _check_directory(params)}
|
||||
previous = previous_secrets or {}
|
||||
password = _secret_value(secrets, "password", "Password")
|
||||
key = _secret_value(secrets, "private_key", "Private key", 16384).replace("\r\n", "\n")
|
||||
phrase = _secret_value(secrets, "key_passphrase", "Key passphrase")
|
||||
if password and key:
|
||||
raise ValueError("Give a password or a private key, not both")
|
||||
if not password and not key:
|
||||
# nothing new: keep what is stored (a new passphrase goes with the stored key)
|
||||
password, key = previous.get("password", ""), previous.get("private_key", "")
|
||||
phrase = phrase or previous.get("key_passphrase", "")
|
||||
if not password and not key:
|
||||
raise ValueError("A password or a private key is required")
|
||||
if key:
|
||||
if "PRIVATE KEY" not in key:
|
||||
raise ValueError("The private key must be the text of the key file (-----BEGIN ... PRIVATE KEY-----)")
|
||||
_load_private_key(key + "\n", phrase)
|
||||
clean_secrets = {"private_key": key.strip() + "\n"}
|
||||
if phrase:
|
||||
clean_secrets["key_passphrase"] = phrase
|
||||
else:
|
||||
clean_secrets = {"password": password}
|
||||
return clean, clean_secrets
|
||||
|
||||
# -- connection --
|
||||
|
||||
@staticmethod
|
||||
def _policy(pinned: Optional[str], seen: dict):
|
||||
"""Host key policy: records what the server shows and accepts ONLY the pinned fingerprint.
|
||||
Unknown keys are rejected (never added automatically)."""
|
||||
paramiko = _paramiko()
|
||||
|
||||
class PinnedPolicy(paramiko.MissingHostKeyPolicy):
|
||||
def missing_host_key(self, client, hostname, key):
|
||||
seen["fingerprint"], seen["key_type"] = _ssh_fingerprint(key), key.get_name()
|
||||
if not pinned or not hmac.compare_digest(seen["fingerprint"], pinned):
|
||||
raise paramiko.SSHException("host key is not trusted")
|
||||
return PinnedPolicy()
|
||||
|
||||
def _connect(self, allow_trust: bool = False):
|
||||
"""Open the SSH connection and return the client. allow_trust: for Test and the pinning
|
||||
call; a key that is unknown or changed then raises NeedsTrust with the fingerprint."""
|
||||
paramiko = _paramiko()
|
||||
pinned = self.params.get("host_key") or None
|
||||
if not pinned and not allow_trust:
|
||||
raise DestinationError("The host key of the server is not trusted yet: run Test and confirm the fingerprint")
|
||||
pkey = None
|
||||
if self.secrets.get("private_key"):
|
||||
try:
|
||||
pkey = _load_private_key(self.secrets["private_key"], self.secrets.get("key_passphrase", ""))
|
||||
except ValueError as e:
|
||||
raise DestinationError(str(e)) from None
|
||||
seen: dict = {}
|
||||
client = paramiko.SSHClient() # no known_hosts is loaded: every key goes to the policy
|
||||
client.set_missing_host_key_policy(self._policy(pinned, seen))
|
||||
try:
|
||||
client.connect(self.params["host"], port=self.params["port"], username=self.params["username"],
|
||||
password=self.secrets.get("password") or None, pkey=pkey,
|
||||
timeout=CONNECT_TIMEOUT, banner_timeout=CONNECT_TIMEOUT, auth_timeout=CONNECT_TIMEOUT,
|
||||
allow_agent=False, look_for_keys=False)
|
||||
except Exception as e:
|
||||
client.close()
|
||||
fp = seen.get("fingerprint")
|
||||
if fp and fp != pinned:
|
||||
if allow_trust:
|
||||
raise NeedsTrust(
|
||||
("The host key changed: it differs from the trusted one" if pinned
|
||||
else "The host key of the server is not trusted yet"),
|
||||
fp, seen.get("key_type", ""), changed=bool(pinned)) from None
|
||||
raise DestinationError("The host key of the server changed: connection refused. "
|
||||
"Run Test to see the new fingerprint and trust it if the change is expected") from None
|
||||
raise DestinationError(self._explain(e)) from None
|
||||
return client
|
||||
|
||||
@staticmethod
|
||||
def _explain(e: Exception) -> str:
|
||||
paramiko = _paramiko()
|
||||
if isinstance(e, paramiko.AuthenticationException):
|
||||
return "Authentication failed: check the user name and the password or key"
|
||||
if isinstance(e, (socket.timeout, TimeoutError)):
|
||||
return "Connection timed out"
|
||||
if isinstance(e, socket.gaierror):
|
||||
return "Host name cannot be resolved"
|
||||
if isinstance(e, ConnectionRefusedError):
|
||||
return "Connection refused"
|
||||
if isinstance(e, paramiko.SSHException):
|
||||
return f"SSH error: {str(e)[:200]}"
|
||||
if isinstance(e, OSError):
|
||||
return f"Network error: {e.strerror or type(e).__name__}"
|
||||
return _short(e)
|
||||
|
||||
@contextmanager
|
||||
def _session(self, allow_trust: bool = False):
|
||||
client = self._connect(allow_trust)
|
||||
try:
|
||||
sftp = client.open_sftp()
|
||||
sftp.get_channel().settimeout(TRANSFER_TIMEOUT)
|
||||
yield sftp
|
||||
except DestinationError:
|
||||
raise
|
||||
except FileNotFoundError:
|
||||
raise DestinationError("File or directory not found on the server") from None
|
||||
except Exception as e:
|
||||
raise DestinationError(self._explain(e)) from None
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
def fetch_host_key(self):
|
||||
try:
|
||||
self._connect(allow_trust=True).close()
|
||||
except NeedsTrust as n:
|
||||
return n.fingerprint, n.key_type
|
||||
return self.params.get("host_key", ""), self.params.get("host_key_type", "")
|
||||
|
||||
# -- operations --
|
||||
|
||||
def _dir(self, sftp, create: bool) -> str:
|
||||
"""Change into the directory (creating the levels when asked). Returns the path."""
|
||||
path = ""
|
||||
for part in self.params["directory"].split("/"):
|
||||
path = f"{path}/{part}" if path else part
|
||||
try:
|
||||
if not stat.S_ISDIR(sftp.stat(path).st_mode):
|
||||
raise DestinationError(f"'{path}' on the server is not a directory")
|
||||
except FileNotFoundError:
|
||||
if not create:
|
||||
raise DestinationError("Directory does not exist yet") from None
|
||||
sftp.mkdir(path, 0o700)
|
||||
return path
|
||||
|
||||
def test(self) -> str:
|
||||
with self._session(allow_trust=True) as sftp:
|
||||
directory = self._dir(sftp, create=True)
|
||||
probe = f"{directory}/.ovpmon-test-{uuid.uuid4().hex[:8]}"
|
||||
sftp.putfo(io.BytesIO(b"ok"), probe)
|
||||
try:
|
||||
sftp.remove(probe)
|
||||
except Exception:
|
||||
return "Server is writable, but deleting files is not allowed (rotation will not work)"
|
||||
return "SFTP server is reachable, host key matches, write and delete work"
|
||||
|
||||
def put(self, local_path, name):
|
||||
_check_name(name)
|
||||
with self._session() as sftp:
|
||||
directory = self._dir(sftp, create=True)
|
||||
final, tmp = f"{directory}/{name}", f"{directory}/.{name}.part"
|
||||
try:
|
||||
sftp.put(local_path, tmp, confirm=True)
|
||||
try:
|
||||
sftp.posix_rename(tmp, final)
|
||||
except OSError: # the server has no posix-rename extension
|
||||
sftp.rename(tmp, final)
|
||||
except Exception:
|
||||
try:
|
||||
sftp.remove(tmp)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
def list(self):
|
||||
with self._session() as sftp:
|
||||
try:
|
||||
directory = self._dir(sftp, create=False)
|
||||
except DestinationError as e:
|
||||
if "does not exist" in str(e):
|
||||
return []
|
||||
raise
|
||||
return [{"name": a.filename, "size": a.st_size or 0, "mtime": a.st_mtime}
|
||||
for a in sftp.listdir_attr(directory)
|
||||
if stat.S_ISREG(a.st_mode or 0) and PACKAGE_RE.match(a.filename)]
|
||||
|
||||
def get(self, name, local_path):
|
||||
_check_name(name)
|
||||
with self._session() as sftp:
|
||||
remote = f"{self._dir(sftp, create=False)}/{name}"
|
||||
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "wb") as out:
|
||||
sftp.getfo(remote, out)
|
||||
|
||||
def delete(self, name):
|
||||
_check_name(name)
|
||||
with self._session() as sftp:
|
||||
try:
|
||||
sftp.remove(f"{self._dir(sftp, create=False)}/{name}")
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
# --- FTP / FTPS (ftplib) -------------------------------------------------------------------
|
||||
|
||||
class FTPDestination(Destination):
|
||||
"""FTP server; explicit FTPS (AUTH TLS) with certificate verification by default. Plain FTP and a
|
||||
disabled certificate check are allowed explicitly (the UI warns)."""
|
||||
type = "ftp"
|
||||
label = "FTP / FTPS server"
|
||||
FIELDS = [
|
||||
{"name": "host", "label": "Host", "kind": "text", "required": True, "default": "",
|
||||
"hint": "Host name or IPv4 address"},
|
||||
{"name": "port", "label": "Port", "kind": "number", "required": True, "default": 21},
|
||||
{"name": "username", "label": "User name", "kind": "text", "required": True, "default": ""},
|
||||
{"name": "directory", "label": "Directory", "kind": "text", "required": True, "default": "ovpmon-backups",
|
||||
"hint": "Relative to the login directory of the user; created if missing"},
|
||||
{"name": "tls", "label": "Use TLS (explicit FTPS)", "kind": "bool", "required": False, "default": True,
|
||||
"warning": "Without TLS the password and the packages travel in clear text. Use only inside a trusted network.",
|
||||
"warn_if": False},
|
||||
{"name": "verify_cert", "label": "Verify the server certificate", "kind": "bool", "required": False,
|
||||
"default": True,
|
||||
"warning": "Certificate verification is off: the server cannot be told from an impostor. Use only for a self-signed certificate in a trusted network.",
|
||||
"warn_if": False},
|
||||
{"name": "passive", "label": "Passive mode", "kind": "bool", "required": False, "default": True},
|
||||
{"name": "password", "label": "Password", "kind": "secret", "required": True},
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def validate(cls, params, secrets, previous_secrets=None):
|
||||
_unknown_keys(params, {"host", "port", "username", "directory", "tls", "verify_cert", "passive"}, "parameters")
|
||||
_unknown_keys(secrets, {"password"}, "secrets")
|
||||
host, port = _check_host_port(params, 21)
|
||||
clean = {"host": host, "port": port, "username": _check_username(params),
|
||||
"directory": _check_directory(params),
|
||||
"tls": bool(params.get("tls", True)), "verify_cert": bool(params.get("verify_cert", True)),
|
||||
"passive": bool(params.get("passive", True))}
|
||||
password = _secret_value(secrets, "password", "Password") or (previous_secrets or {}).get("password", "")
|
||||
if not password:
|
||||
raise ValueError("Password is required")
|
||||
return clean, {"password": password}
|
||||
|
||||
@contextmanager
|
||||
def _session(self, create_dir: bool = False):
|
||||
import ftplib
|
||||
p = self.params
|
||||
try:
|
||||
if p["tls"]:
|
||||
ctx = ssl.create_default_context()
|
||||
if not p["verify_cert"]:
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
ftp = ftplib.FTP_TLS(context=ctx, timeout=TRANSFER_TIMEOUT)
|
||||
else:
|
||||
ftp = ftplib.FTP(timeout=TRANSFER_TIMEOUT)
|
||||
except Exception as e:
|
||||
raise DestinationError(_short(e)) from None
|
||||
try:
|
||||
try:
|
||||
ftp.connect(p["host"], p["port"], timeout=CONNECT_TIMEOUT)
|
||||
ftp.login(p["username"], self.secrets["password"])
|
||||
ftp.timeout = TRANSFER_TIMEOUT # transfers (data connections) wait longer than the login
|
||||
ftp.sock.settimeout(TRANSFER_TIMEOUT)
|
||||
if p["tls"]:
|
||||
ftp.prot_p() # TLS for the data connection too
|
||||
ftp.set_pasv(p["passive"])
|
||||
self._cd(ftp, create_dir)
|
||||
yield ftp
|
||||
except DestinationError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise DestinationError(self._explain(e)) from None
|
||||
finally:
|
||||
try:
|
||||
ftp.quit()
|
||||
except Exception:
|
||||
ftp.close()
|
||||
|
||||
@staticmethod
|
||||
def _explain(e: Exception) -> str:
|
||||
import ftplib
|
||||
if isinstance(e, ssl.SSLCertVerificationError):
|
||||
return f"TLS certificate check failed: {(e.verify_message or 'invalid certificate')[:150]}. " \
|
||||
"For a self-signed certificate turn the verification off in the destination"
|
||||
if isinstance(e, ssl.SSLError):
|
||||
return f"TLS error: {(e.reason or type(e).__name__)}"
|
||||
if isinstance(e, ftplib.error_perm):
|
||||
text = str(e)[:200]
|
||||
return "Login failed: check the user name and the password" if text.startswith("530") else f"Server refused: {text}"
|
||||
if isinstance(e, ftplib.Error):
|
||||
return f"FTP error: {str(e)[:200]}"
|
||||
if isinstance(e, (socket.timeout, TimeoutError)):
|
||||
return "Connection timed out"
|
||||
if isinstance(e, socket.gaierror):
|
||||
return "Host name cannot be resolved"
|
||||
if isinstance(e, ConnectionRefusedError):
|
||||
return "Connection refused"
|
||||
if isinstance(e, EOFError):
|
||||
return "The server closed the connection"
|
||||
if isinstance(e, OSError):
|
||||
return f"Network error: {e.strerror or type(e).__name__}"
|
||||
return _short(e)
|
||||
|
||||
def _cd(self, ftp, create: bool) -> None:
|
||||
import ftplib
|
||||
for part in self.params["directory"].split("/"):
|
||||
try:
|
||||
ftp.cwd(part)
|
||||
except ftplib.error_perm:
|
||||
if not create:
|
||||
raise DestinationError("Directory does not exist yet") from None
|
||||
ftp.mkd(part)
|
||||
ftp.cwd(part)
|
||||
|
||||
def test(self) -> str:
|
||||
with self._session(create_dir=True) as ftp:
|
||||
probe = f".ovpmon-test-{uuid.uuid4().hex[:8]}"
|
||||
ftp.storbinary(f"STOR {probe}", io.BytesIO(b"ok"))
|
||||
try:
|
||||
ftp.delete(probe)
|
||||
except Exception:
|
||||
return "Server is writable, but deleting files is not allowed (rotation will not work)"
|
||||
mode = "TLS" if self.params["tls"] else "NO TLS (clear text)"
|
||||
return f"FTP server is reachable ({mode}), write and delete work"
|
||||
|
||||
def put(self, local_path, name):
|
||||
_check_name(name)
|
||||
tmp = f".{name}.part"
|
||||
with self._session(create_dir=True) as ftp:
|
||||
try:
|
||||
with open(local_path, "rb") as src:
|
||||
ftp.storbinary(f"STOR {tmp}", src, blocksize=1024 * 1024)
|
||||
ftp.rename(tmp, name)
|
||||
except Exception:
|
||||
try:
|
||||
ftp.delete(tmp)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
def list(self):
|
||||
try:
|
||||
with self._session() as ftp:
|
||||
return self._packages(ftp)
|
||||
except DestinationError as e:
|
||||
if "does not exist" in str(e):
|
||||
return []
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def _packages(ftp):
|
||||
import ftplib
|
||||
out = []
|
||||
try:
|
||||
for name, facts in ftp.mlsd(facts=["type", "size", "modify"]):
|
||||
if facts.get("type") == "file" and PACKAGE_RE.match(name):
|
||||
out.append({"name": name, "size": int(facts.get("size") or 0),
|
||||
"mtime": FTPDestination._mtime(facts.get("modify"))})
|
||||
return out
|
||||
except ftplib.error_perm:
|
||||
out = [] # no MLSD on this server: names first, then size and time of our packages
|
||||
ftp.voidcmd("TYPE I")
|
||||
for entry in ftp.nlst():
|
||||
name = entry.rsplit("/", 1)[-1]
|
||||
if not PACKAGE_RE.match(name):
|
||||
continue
|
||||
try:
|
||||
size = ftp.size(name) or 0
|
||||
except ftplib.Error:
|
||||
size = 0
|
||||
try:
|
||||
mtime = FTPDestination._mtime(ftp.voidcmd(f"MDTM {name}").split()[-1])
|
||||
except ftplib.Error:
|
||||
mtime = None
|
||||
out.append({"name": name, "size": size, "mtime": mtime})
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _mtime(modify):
|
||||
try:
|
||||
return datetime.strptime(modify[:14], "%Y%m%d%H%M%S").replace(tzinfo=timezone.utc).timestamp()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
def get(self, name, local_path):
|
||||
_check_name(name)
|
||||
with self._session() as ftp:
|
||||
ftp.voidcmd("TYPE I")
|
||||
fd = os.open(local_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "wb") as out:
|
||||
ftp.retrbinary(f"RETR {name}", out.write, blocksize=1024 * 1024)
|
||||
|
||||
def delete(self, name):
|
||||
_check_name(name)
|
||||
with self._session() as ftp:
|
||||
ftp.delete(name)
|
||||
|
||||
|
||||
# Registry: the API accepts exactly these types. smb comes in a later pass.
|
||||
DESTINATION_TYPES = {
|
||||
LocalDestination.type: LocalDestination,
|
||||
S3Destination.type: S3Destination,
|
||||
SFTPDestination.type: SFTPDestination,
|
||||
FTPDestination.type: FTPDestination,
|
||||
}
|
||||
|
||||
REMOTE_TYPES = {t for t in DESTINATION_TYPES if t != "local"} # these need an encryption passphrase
|
||||
|
||||
|
||||
def build_destination(dtype: str, params: dict, secrets: dict) -> Destination:
|
||||
cls = DESTINATION_TYPES.get(dtype)
|
||||
if cls is None:
|
||||
raise BackupError(f"Unsupported destination type: {dtype}")
|
||||
return cls(params, secrets)
|
||||
@@ -0,0 +1,657 @@
|
||||
"""Backup job and restore engine.
|
||||
|
||||
One background job at a time for the whole service (a backup or a restore), like the async PKI
|
||||
initialization: the state lives in memory of the single Profiler process, results go to the history
|
||||
in ovpmon_backup.db.
|
||||
"""
|
||||
import copy
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
import migrations
|
||||
from database import SessionLocal, engine as sa_engine
|
||||
|
||||
from . import BackupError, Busy, Invalid, crypto, destinations, package, store
|
||||
from services import pki, process
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PRE_RESTORE_FOLDER = "pre-restore"
|
||||
PRE_RESTORE_KEEP = 5
|
||||
|
||||
_lock = threading.Lock()
|
||||
_job = {"kind": None, "state": "idle", "stages": [], "results": [], "warnings": [],
|
||||
"started_at": None, "finished_at": None, "message": None, "relogin": False}
|
||||
|
||||
|
||||
# --- paths ---------------------------------------------------------------------------------
|
||||
|
||||
def profiler_db_path() -> str:
|
||||
from database import db_path
|
||||
return os.path.abspath(db_path)
|
||||
|
||||
|
||||
def monitor_db_path() -> str:
|
||||
env = os.environ.get("OVPMON_OPENVPN_MONITOR_DB_PATH", "").strip()
|
||||
return os.path.abspath(env) if env else os.path.join(os.path.dirname(profiler_db_path()), "openvpn_monitor.db")
|
||||
|
||||
|
||||
def pki_dir() -> str:
|
||||
return pki.PKI_DIR
|
||||
|
||||
|
||||
def client_dir() -> str:
|
||||
return os.path.join(os.getcwd(), "client-config")
|
||||
|
||||
|
||||
def runtime() -> str:
|
||||
return "container" if process.is_container() else "host"
|
||||
|
||||
|
||||
def _work_dir() -> str:
|
||||
"""Temporary directory for a job: next to the local backups (they have room by definition),
|
||||
else the system temporary directory."""
|
||||
base = os.environ.get("OVPMON_BACKUP_WORK_DIR", "").strip() or os.path.join(destinations.local_root(), ".work")
|
||||
try:
|
||||
os.makedirs(base, mode=0o700, exist_ok=True)
|
||||
except OSError:
|
||||
base = None
|
||||
return tempfile.mkdtemp(prefix="job-", dir=base)
|
||||
|
||||
|
||||
# --- job state -----------------------------------------------------------------------------
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def status() -> dict:
|
||||
with _lock:
|
||||
return copy.deepcopy(_job)
|
||||
|
||||
|
||||
def is_running() -> bool:
|
||||
with _lock:
|
||||
return _job["state"] == "running"
|
||||
|
||||
|
||||
def _claim(kind: str, stages: list, results: list) -> None:
|
||||
with _lock:
|
||||
if _job["state"] == "running":
|
||||
raise Busy(f"A {_job['kind']} is already running")
|
||||
_job.update(kind=kind, state="running", stages=[{"name": n, "state": "pending"} for n in stages],
|
||||
results=results, warnings=[], started_at=_now(), finished_at=None, message=None,
|
||||
relogin=False)
|
||||
|
||||
|
||||
def _stage(name: str, state: str = "running") -> None:
|
||||
with _lock:
|
||||
for s in _job["stages"]:
|
||||
if s["name"] == name:
|
||||
s["state"] = state
|
||||
elif s["state"] == "running" and state == "running":
|
||||
s["state"] = "done"
|
||||
|
||||
|
||||
def _warn(text: str) -> None:
|
||||
logger.warning(f"[BACKUP] {text}")
|
||||
with _lock:
|
||||
_job["warnings"].append(text)
|
||||
|
||||
|
||||
def _finish(state: str, message: str, relogin: bool = False) -> None:
|
||||
with _lock:
|
||||
for s in _job["stages"]:
|
||||
if s["state"] == "running":
|
||||
s["state"] = "done" if state in ("done", "partial") else "error"
|
||||
_job.update(state=state, message=message, finished_at=_now(), relogin=relogin)
|
||||
|
||||
|
||||
def _result(index: int, **fields) -> None:
|
||||
with _lock:
|
||||
_job["results"][index].update(fields)
|
||||
|
||||
|
||||
# --- destinations --------------------------------------------------------------------------
|
||||
|
||||
def build_dest(rec: dict) -> destinations.Destination:
|
||||
if not rec.get("secrets_ok", True):
|
||||
raise BackupError("Stored secrets of this destination cannot be decrypted "
|
||||
"(the JWT secret changed). Edit the destination and enter them again.")
|
||||
return destinations.build_destination(rec["type"], rec["params"], rec["secrets"])
|
||||
|
||||
|
||||
def test_destination(dest_id: int) -> dict:
|
||||
rec = store.get_destination(dest_id, with_secrets=True)
|
||||
if not rec:
|
||||
raise Invalid("Destination not found")
|
||||
try:
|
||||
message = build_dest(rec).test()
|
||||
except destinations.NeedsTrust as e:
|
||||
# SFTP: the host key is not pinned (or changed): show it, the administrator decides
|
||||
store.set_last_result(dest_id, False, str(e))
|
||||
return {"ok": False, "message": str(e), "needs_trust": True, "fingerprint": e.fingerprint,
|
||||
"key_type": e.key_type, "key_changed": e.changed}
|
||||
except BackupError as e:
|
||||
store.set_last_result(dest_id, False, str(e))
|
||||
return {"ok": False, "message": str(e)}
|
||||
except Exception as e: # a driver error that is not mapped: report it, never crash the API
|
||||
logger.exception("Destination test failed")
|
||||
message = f"{type(e).__name__}: {str(e)[:200]}"
|
||||
store.set_last_result(dest_id, False, message)
|
||||
return {"ok": False, "message": message}
|
||||
store.set_last_result(dest_id, True, message)
|
||||
return {"ok": True, "message": message}
|
||||
|
||||
|
||||
def effective_server_name() -> tuple:
|
||||
"""(name, source): the server name of the settings, else the public address from the VPN
|
||||
settings, else the host name. The name goes into the package names."""
|
||||
name = store.get_server_name()
|
||||
if name and package.SERVER_NAME_RE.match(name):
|
||||
return name, "setting"
|
||||
try:
|
||||
conn = sqlite3.connect(f"file:{profiler_db_path()}?mode=ro", uri=True, timeout=5)
|
||||
try:
|
||||
row = conn.execute("SELECT public_ip FROM system_settings LIMIT 1").fetchone()
|
||||
finally:
|
||||
conn.close()
|
||||
name = package.sanitize_name(row[0]) if row and row[0] else ""
|
||||
if name:
|
||||
return name, "public_ip"
|
||||
except sqlite3.Error:
|
||||
pass # no settings yet (or the column is absent): fall through
|
||||
return package.host_name(), "hostname"
|
||||
|
||||
|
||||
def trust_host_key(dest_id: int, fingerprint: str) -> dict:
|
||||
"""Pin the host key the server shows now, if it is the one the administrator saw (`fingerprint`)."""
|
||||
rec = store.get_destination(dest_id, with_secrets=True)
|
||||
if not rec:
|
||||
raise Invalid("Destination not found")
|
||||
cls = destinations.DESTINATION_TYPES.get(rec["type"])
|
||||
if not cls or not cls.PIN_PARAMS:
|
||||
raise Invalid("This destination type has no host key")
|
||||
if not destinations.FINGERPRINT_RE.match(fingerprint or ""):
|
||||
raise Invalid("Invalid fingerprint")
|
||||
shown, key_type = build_dest(rec).fetch_host_key()
|
||||
if shown != fingerprint:
|
||||
raise Invalid("The server now shows a different host key than the one you saw: run Test again")
|
||||
params = dict(rec["params"], host_key=shown, host_key_type=key_type)
|
||||
store.save_destination(rec["id"], rec["name"], rec["type"], rec["enabled"], rec["retention_count"],
|
||||
params, rec["secrets"])
|
||||
store.set_last_result(rec["id"], True, f"Host key {shown} trusted")
|
||||
return store.get_destination(rec["id"])
|
||||
|
||||
|
||||
def list_packages(dest_id: int) -> list:
|
||||
"""Packages of our name pattern in the destination, newest first."""
|
||||
rec = store.get_destination(dest_id, with_secrets=True)
|
||||
if not rec:
|
||||
raise Invalid("Destination not found")
|
||||
items = []
|
||||
for obj in build_dest(rec).list():
|
||||
meta = package.parse_package_name(obj["name"])
|
||||
if meta:
|
||||
items.append({"name": obj["name"], "server_name": meta["host"], "created_at": meta["created_at"],
|
||||
"encrypted": meta["encrypted"], "size": obj["size"],
|
||||
"_key": (meta["stamp"], meta["seq"], obj["name"])})
|
||||
items.sort(key=lambda i: i["_key"], reverse=True)
|
||||
for i in items:
|
||||
del i["_key"]
|
||||
return items
|
||||
|
||||
|
||||
def put_unique(dest: destinations.Destination, path: str, base_name: str) -> str:
|
||||
"""Store the package under base_name, or under -2, -3 ... when the destination already has a
|
||||
package of that second. Returns the name used."""
|
||||
meta = package.parse_package_name(base_name)
|
||||
name = package.unique_package_name(meta["host"], meta["stamp"], meta["encrypted"],
|
||||
(o["name"] for o in dest.list()))
|
||||
dest.put(path, name)
|
||||
return name
|
||||
|
||||
|
||||
def rotate(dest: destinations.Destination, keep: int, keep_name: str, server_name: str) -> int:
|
||||
"""Delete the oldest packages of this server name beyond `keep` (never keep_name). Packages
|
||||
with another name in the same folder (other servers, or made under an earlier name or by host
|
||||
name) are not ours to delete. Returns the number removed."""
|
||||
mine = []
|
||||
for obj in dest.list():
|
||||
meta = package.parse_package_name(obj["name"])
|
||||
if meta and meta["host"] == server_name:
|
||||
mine.append(((meta["stamp"], meta["seq"]), obj["name"]))
|
||||
mine.sort(reverse=True)
|
||||
removed = 0
|
||||
for _key, name in mine[max(keep, 1):]:
|
||||
if name != keep_name:
|
||||
dest.delete(name)
|
||||
removed += 1
|
||||
return removed
|
||||
|
||||
|
||||
# --- package creation ----------------------------------------------------------------------
|
||||
|
||||
def create_package(work: str, passphrase: Optional[str]):
|
||||
"""Build (and encrypt, if a passphrase is given) a package in `work`. Returns (path, name, manifest);
|
||||
name is the plain name, a destination may add -2, -3 when that second is taken (put_unique)."""
|
||||
stamp = package.utc_stamp()
|
||||
server_name, _source = effective_server_name()
|
||||
plain = os.path.join(work, "package.tar.gz")
|
||||
manifest = package.build_package(plain, work, profiler_db_path(), monitor_db_path(),
|
||||
pki_dir(), client_dir(), runtime(), server_name)
|
||||
path = plain
|
||||
if passphrase:
|
||||
path = os.path.join(work, "package.enc")
|
||||
crypto.encrypt_file(plain, path, passphrase)
|
||||
os.remove(plain)
|
||||
return path, package.package_name(server_name, stamp, bool(passphrase)), manifest
|
||||
|
||||
|
||||
# --- backup job ----------------------------------------------------------------------------
|
||||
|
||||
def start_backup(destination_ids: Optional[list] = None) -> None:
|
||||
all_dests = store.list_destinations(with_secrets=True)
|
||||
if destination_ids is None:
|
||||
selected = [d for d in all_dests if d["enabled"]]
|
||||
else:
|
||||
by_id = {d["id"]: d for d in all_dests}
|
||||
selected = []
|
||||
for i in dict.fromkeys(destination_ids):
|
||||
if i not in by_id:
|
||||
raise Invalid(f"Destination {i} not found")
|
||||
if not by_id[i]["enabled"]:
|
||||
raise Invalid(f"Destination '{by_id[i]['name']}' is disabled")
|
||||
selected.append(by_id[i])
|
||||
if not selected:
|
||||
raise Invalid("No destinations selected: add and enable a destination first")
|
||||
if any(d["type"] in destinations.REMOTE_TYPES for d in selected) and not store.has_passphrase():
|
||||
raise Invalid("A passphrase is required for remote destinations: set the encryption passphrase first")
|
||||
passphrase = store.get_passphrase()
|
||||
stages = ["package"] + (["encrypt"] if passphrase else []) + ["upload"]
|
||||
results = [{"destination_id": d["id"], "name": d["name"], "type": d["type"], "state": "pending",
|
||||
"message": None, "package": None} for d in selected]
|
||||
_claim("backup", stages, results)
|
||||
hist_id = store.history_start("backup")
|
||||
threading.Thread(target=_backup_worker, args=(selected, passphrase, hist_id), daemon=True).start()
|
||||
|
||||
|
||||
def _backup_worker(selected: list, passphrase: Optional[str], hist_id: int) -> None:
|
||||
work = None
|
||||
try:
|
||||
work = _work_dir()
|
||||
_stage("package")
|
||||
# create_package encrypts too: show the second stage once the tar is written
|
||||
path, name, manifest = create_package(work, passphrase)
|
||||
if passphrase:
|
||||
_stage("encrypt", "done")
|
||||
_stage("upload")
|
||||
size = os.path.getsize(path)
|
||||
server_name = manifest["server_name"]
|
||||
for i, rec in enumerate(selected):
|
||||
_result(i, state="running")
|
||||
try:
|
||||
dest = build_dest(rec)
|
||||
stored = put_unique(dest, path, name)
|
||||
note = f"{stored} ({size // 1024} KB)"
|
||||
try:
|
||||
removed = rotate(dest, rec["retention_count"], stored, server_name)
|
||||
if removed:
|
||||
note += f", {removed} old removed"
|
||||
except Exception as e:
|
||||
logger.warning(f"[BACKUP] rotation failed for '{rec['name']}': {type(e).__name__}")
|
||||
note += f", rotation failed: {str(e)[:150]}"
|
||||
_result(i, state="ok", message=note, package=stored)
|
||||
store.set_last_result(rec["id"], True, note)
|
||||
except Exception as e:
|
||||
msg = str(e)[:300] if isinstance(e, BackupError) else f"{type(e).__name__}: {str(e)[:200]}"
|
||||
logger.error(f"[BACKUP] destination '{rec['name']}' failed: {msg}")
|
||||
_result(i, state="error", message=msg)
|
||||
store.set_last_result(rec["id"], False, msg)
|
||||
with _lock:
|
||||
results = copy.deepcopy(_job["results"])
|
||||
ok = sum(1 for r in results if r["state"] == "ok")
|
||||
if ok == len(results):
|
||||
state, message = "done", f"Backup stored in {ok} destination(s)"
|
||||
elif ok:
|
||||
state, message = "partial", f"Backup stored in {ok} of {len(results)} destinations"
|
||||
else:
|
||||
state, message = "error", "Backup failed in every destination"
|
||||
_finish(state, message)
|
||||
store.history_finish(hist_id, state, message, results)
|
||||
except Exception as e:
|
||||
logger.exception("Backup failed")
|
||||
message = str(e)[:500] if isinstance(e, BackupError) else f"Backup failed: {type(e).__name__}: {str(e)[:300]}"
|
||||
for i in range(len(selected)):
|
||||
_result(i, state="skipped", message="Package was not created")
|
||||
_finish("error", message)
|
||||
store.history_finish(hist_id, "error", message, [])
|
||||
finally:
|
||||
if work:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
# --- restore -------------------------------------------------------------------------------
|
||||
|
||||
RESTORE_STAGES = ["download", "decrypt", "verify", "prepare", "safety_backup", "stop_openvpn",
|
||||
"replace", "finalize"]
|
||||
|
||||
|
||||
def start_restore(destination_id: int, package_name: str, passphrase: Optional[str]) -> None:
|
||||
rec = store.get_destination(destination_id, with_secrets=True)
|
||||
if not rec:
|
||||
raise Invalid("Destination not found")
|
||||
meta = package.parse_package_name(package_name)
|
||||
if not meta:
|
||||
raise Invalid("Invalid package name")
|
||||
if meta["encrypted"] and not passphrase:
|
||||
raise Invalid("The package is encrypted: enter its passphrase")
|
||||
if pki.is_init_running():
|
||||
raise Busy("PKI initialization is running")
|
||||
if is_running():
|
||||
raise Busy(f"A {status()['kind']} is already running")
|
||||
# Only names from the destination's listing are restored
|
||||
if package_name not in {o["name"] for o in build_dest(rec).list()}:
|
||||
raise Invalid("The package is not in the destination")
|
||||
stages = [s for s in RESTORE_STAGES if s != "decrypt" or meta["encrypted"]]
|
||||
_claim("restore", stages, [{"destination_id": rec["id"], "name": rec["name"], "type": rec["type"],
|
||||
"state": "running", "message": None, "package": package_name}])
|
||||
pki.set_restore_running(True)
|
||||
hist_id = store.history_start("restore")
|
||||
threading.Thread(target=_restore_worker, args=(rec, package_name, meta["encrypted"], passphrase, hist_id),
|
||||
daemon=True).start()
|
||||
|
||||
|
||||
def core_dir() -> Optional[str]:
|
||||
"""Directory of the monitoring component (it owns the migrations of openvpn_monitor.db):
|
||||
migrate.py with migrations.py and db.py (standard library only).
|
||||
OVPMON_CORE_DIR (profiler image: /opt/core), else APP_CORE next to APP_PROFILER (system
|
||||
services, all-in-one container). None for an old profiler image without that directory."""
|
||||
env = os.environ.get("OVPMON_CORE_DIR", "").strip()
|
||||
if not env:
|
||||
code = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
env = os.path.join(os.path.dirname(code), "APP_CORE")
|
||||
if all(os.path.isfile(os.path.join(env, f)) for f in ("migrate.py", "migrations.py", "db.py")):
|
||||
return env
|
||||
return None
|
||||
|
||||
|
||||
def _migrate_monitor(db_file: str) -> None:
|
||||
"""Bring the monitoring database of the package up to this release's schema.
|
||||
|
||||
The migrations live in the monitoring component, which this process cannot import (separate
|
||||
virtualenv). Its own migrate.py runs on the staged copy with the interpreter of APP_CORE/venv
|
||||
(or this one: the code uses the standard library only). Without the code on disk (an old
|
||||
profiler image) only a package with exactly the schema of the running monitoring database is
|
||||
accepted: the monitoring services would otherwise read an unmigrated database."""
|
||||
version = package.schema_version(db_file)
|
||||
core = core_dir()
|
||||
if core:
|
||||
venv_python = os.path.join(core, "venv", "bin", "python")
|
||||
python = venv_python if os.path.isfile(venv_python) else sys.executable
|
||||
try:
|
||||
r = subprocess.run([python, "migrate.py", "--db", db_file], cwd=core, capture_output=True,
|
||||
text=True, timeout=300)
|
||||
except (OSError, subprocess.TimeoutExpired) as e:
|
||||
raise BackupError(f"Cannot run the monitoring database migration: {e}") from e
|
||||
if r.returncode != 0:
|
||||
lines = [ln for ln in (r.stderr or r.stdout or "").strip().splitlines() if ln.strip()]
|
||||
raise BackupError("The monitoring database of the package cannot be migrated: "
|
||||
+ (lines[-1][:300] if lines else f"exit code {r.returncode}"))
|
||||
return
|
||||
live = package.schema_version(monitor_db_path())
|
||||
if not live:
|
||||
raise BackupError("The monitoring database schema cannot be checked: the monitoring component "
|
||||
"is not available to this service and its database is not initialized")
|
||||
if version != live:
|
||||
which = "newer" if (version or 0) > live else "older"
|
||||
raise BackupError(
|
||||
f"The package has a {which} monitoring database schema ({version}) than this installation "
|
||||
f"({live}). The migration code of the monitoring component (OVPMON_CORE_DIR) is not "
|
||||
f"available to this service. Rebuild the profiler image or restore on the same release.")
|
||||
|
||||
|
||||
def _prepare_staged(extracted: str, manifest: dict) -> None:
|
||||
"""Checks and migrations on the unpacked copies: nothing of the running system is touched yet."""
|
||||
prof = os.path.join(extracted, package.DB_PROFILER)
|
||||
mon = os.path.join(extracted, package.DB_MONITOR)
|
||||
for path in (prof, mon):
|
||||
if not package.integrity_ok(path):
|
||||
raise BackupError(f"{os.path.basename(path)} in the package failed the integrity check")
|
||||
version, latest = package.schema_version(prof), migrations.latest_version()
|
||||
if version is None or version > latest:
|
||||
raise BackupError(f"The package was made by a newer release (profiler database schema {version}, "
|
||||
f"this release knows up to {latest}). Update this installation first.")
|
||||
try:
|
||||
migrations.run(prof)
|
||||
except migrations.MigrationError as e:
|
||||
raise BackupError(f"The profiler database of the package cannot be migrated: {str(e)[:300]}") from e
|
||||
_migrate_monitor(mon)
|
||||
|
||||
|
||||
def _safety_backup() -> str:
|
||||
"""Package of the current state in the local pre-restore folder. Raises when it cannot be made."""
|
||||
try:
|
||||
passphrase = store.get_passphrase()
|
||||
except BackupError:
|
||||
passphrase = None
|
||||
_warn("The safety copy is not encrypted: the stored passphrase cannot be decrypted")
|
||||
work = _work_dir()
|
||||
try:
|
||||
path, name, manifest = create_package(work, passphrase)
|
||||
dest = destinations.LocalDestination({"folder": PRE_RESTORE_FOLDER}, {})
|
||||
name = put_unique(dest, path, name)
|
||||
try:
|
||||
rotate(dest, PRE_RESTORE_KEEP, name, manifest["server_name"])
|
||||
except Exception as e:
|
||||
logger.warning(f"[BACKUP] pre-restore rotation failed: {type(e).__name__}")
|
||||
return name
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def _replace_db(target: str, new_file: str, tag: str, undo: list) -> None:
|
||||
"""Atomic replacement of a database file. The old file (and its -wal/-shm) is kept under a
|
||||
.old-<tag> name until the whole restore succeeded."""
|
||||
tmp = f"{target}.restore-{tag}"
|
||||
old = f"{target}.old-{tag}"
|
||||
shutil.copyfile(new_file, tmp)
|
||||
os.chmod(tmp, (os.stat(target).st_mode & 0o777) if os.path.exists(target) else 0o600)
|
||||
if os.path.exists(target):
|
||||
try:
|
||||
os.link(target, old)
|
||||
except OSError:
|
||||
shutil.copy2(target, old)
|
||||
undo.append(("db", target, old))
|
||||
# A leftover journal of the old database must never be applied to the new file
|
||||
for suffix in ("-wal", "-shm"):
|
||||
if os.path.exists(target + suffix):
|
||||
os.replace(target + suffix, old + suffix)
|
||||
else:
|
||||
undo.append(("db_new", target, old))
|
||||
os.replace(tmp, target)
|
||||
|
||||
|
||||
def _swap_dir(target: str, extracted: str, tag: str, undo: list) -> None:
|
||||
"""Replace the CONTENT of a directory (the directory itself may be a volume mount point):
|
||||
old entries move into .restore-old-<tag>, new ones come from .restore-new-<tag>."""
|
||||
os.makedirs(target, mode=0o700, exist_ok=True)
|
||||
staged = os.path.join(target, f".restore-new-{tag}")
|
||||
old = os.path.join(target, f".restore-old-{tag}")
|
||||
if os.path.isdir(extracted):
|
||||
shutil.copytree(extracted, staged)
|
||||
else:
|
||||
os.mkdir(staged, 0o700)
|
||||
os.mkdir(old, 0o700)
|
||||
undo.append(("dir", target, old, staged))
|
||||
for name in os.listdir(target):
|
||||
if not name.startswith(".restore-"):
|
||||
os.replace(os.path.join(target, name), os.path.join(old, name))
|
||||
for name in os.listdir(staged):
|
||||
os.replace(os.path.join(staged, name), os.path.join(target, name))
|
||||
os.rmdir(staged)
|
||||
|
||||
|
||||
def _remove(path: str) -> None:
|
||||
if os.path.isdir(path) and not os.path.islink(path):
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
elif os.path.lexists(path):
|
||||
os.remove(path)
|
||||
|
||||
|
||||
def _rollback(undo: list) -> None:
|
||||
for item in reversed(undo):
|
||||
try:
|
||||
if item[0] == "db":
|
||||
_, target, old = item
|
||||
for suffix in ("", "-wal", "-shm"):
|
||||
if os.path.exists(old + suffix):
|
||||
os.replace(old + suffix, target + suffix)
|
||||
elif item[0] == "db_new":
|
||||
_remove(item[1])
|
||||
else:
|
||||
_, target, old, staged = item
|
||||
for name in os.listdir(target):
|
||||
if not name.startswith(".restore-"):
|
||||
_remove(os.path.join(target, name))
|
||||
for name in os.listdir(old):
|
||||
os.replace(os.path.join(old, name), os.path.join(target, name))
|
||||
shutil.rmtree(old, ignore_errors=True)
|
||||
shutil.rmtree(staged, ignore_errors=True)
|
||||
except Exception:
|
||||
logger.exception("[BACKUP] rollback step failed")
|
||||
|
||||
|
||||
def _commit(undo: list) -> None:
|
||||
for item in undo:
|
||||
if item[0] == "db":
|
||||
for suffix in ("", "-wal", "-shm"):
|
||||
if os.path.lexists(item[2] + suffix):
|
||||
_remove(item[2] + suffix)
|
||||
elif item[0] == "dir":
|
||||
shutil.rmtree(item[2], ignore_errors=True)
|
||||
shutil.rmtree(item[3], ignore_errors=True)
|
||||
|
||||
|
||||
def _apply_server_config() -> bool:
|
||||
"""Regenerate server.conf and publish the CRL through the same code as POST /server/configure."""
|
||||
from fastapi import HTTPException
|
||||
from routers import server as server_router
|
||||
db = SessionLocal()
|
||||
try:
|
||||
server_router.configure_server(db)
|
||||
return True
|
||||
except HTTPException as e:
|
||||
_warn(f"server.conf was not regenerated: {e.detail}")
|
||||
except Exception as e:
|
||||
_warn(f"server.conf was not regenerated: {type(e).__name__}: {str(e)[:200]}")
|
||||
finally:
|
||||
db.close()
|
||||
return False
|
||||
|
||||
|
||||
def _start_openvpn(was_running: bool) -> None:
|
||||
if not was_running:
|
||||
return
|
||||
res = process.control_service("start")
|
||||
if res.get("status") == "error":
|
||||
_warn(f"OpenVPN was running before the restore, but could not be started: {res.get('message')}")
|
||||
|
||||
|
||||
def _restore_worker(rec: dict, name: str, encrypted: bool, passphrase: Optional[str], hist_id: int) -> None:
|
||||
work = None
|
||||
undo = []
|
||||
was_running = False
|
||||
stopped = False
|
||||
committed = False
|
||||
try:
|
||||
work = _work_dir()
|
||||
downloaded = os.path.join(work, "downloaded")
|
||||
_stage("download")
|
||||
build_dest(rec).get(name, downloaded)
|
||||
|
||||
archive = downloaded
|
||||
if encrypted:
|
||||
_stage("decrypt")
|
||||
archive = os.path.join(work, "package.tar.gz")
|
||||
crypto.decrypt_file(downloaded, archive, passphrase)
|
||||
os.remove(downloaded)
|
||||
elif crypto.is_encrypted(downloaded):
|
||||
raise BackupError("The package is encrypted but its name says it is not")
|
||||
|
||||
_stage("verify")
|
||||
extracted = os.path.join(work, "extracted")
|
||||
manifest = package.safe_extract(archive, extracted)
|
||||
os.remove(archive)
|
||||
|
||||
_stage("prepare")
|
||||
_prepare_staged(extracted, manifest)
|
||||
|
||||
_stage("safety_backup")
|
||||
safety = _safety_backup()
|
||||
|
||||
_stage("stop_openvpn")
|
||||
was_running = process.get_process_stats().get("status") == "running"
|
||||
if was_running:
|
||||
res = process.control_service("stop")
|
||||
if res.get("status") == "error":
|
||||
raise BackupError(f"Cannot stop OpenVPN: {res.get('message')}")
|
||||
stopped = True
|
||||
|
||||
_stage("replace")
|
||||
tag = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
|
||||
try:
|
||||
sa_engine.dispose()
|
||||
_swap_dir(pki_dir(), os.path.join(extracted, "pki"), tag, undo)
|
||||
_swap_dir(client_dir(), os.path.join(extracted, "client-config"), tag, undo)
|
||||
_replace_db(monitor_db_path(), os.path.join(extracted, package.DB_MONITOR), tag, undo)
|
||||
_replace_db(profiler_db_path(), os.path.join(extracted, package.DB_PROFILER), tag, undo)
|
||||
marker = pki._marker_path()
|
||||
if os.path.exists(marker):
|
||||
os.remove(marker)
|
||||
except Exception:
|
||||
logger.exception("[BACKUP] replacement failed, rolling back")
|
||||
_rollback(undo)
|
||||
sa_engine.dispose()
|
||||
raise
|
||||
_commit(undo)
|
||||
committed = True
|
||||
sa_engine.dispose()
|
||||
|
||||
_stage("finalize")
|
||||
configured = _apply_server_config()
|
||||
if configured:
|
||||
_start_openvpn(was_running)
|
||||
elif was_running:
|
||||
_warn("OpenVPN was running before the restore and was not started")
|
||||
message = f"Restored from {name}. The previous state is saved as {PRE_RESTORE_FOLDER}/{safety}"
|
||||
_result(0, state="ok", message=message)
|
||||
_finish("done", message, relogin=True)
|
||||
store.history_finish(hist_id, "done", message, status()["results"])
|
||||
except Exception as e:
|
||||
logger.exception("Restore failed")
|
||||
message = str(e)[:500] if isinstance(e, BackupError) else f"Restore failed: {type(e).__name__}: {str(e)[:300]}"
|
||||
if committed:
|
||||
message += ". The data was restored, but the final steps failed (see the log)."
|
||||
else:
|
||||
message += ". Nothing was changed." if not undo else ". The previous state was put back."
|
||||
if stopped:
|
||||
try:
|
||||
_start_openvpn(True)
|
||||
except Exception:
|
||||
logger.exception("[BACKUP] OpenVPN start after a failed restore")
|
||||
_result(0, state="error", message=message)
|
||||
_finish("error", message)
|
||||
store.history_finish(hist_id, "error", message, status()["results"])
|
||||
finally:
|
||||
pki.set_restore_running(False)
|
||||
if work:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
@@ -0,0 +1,335 @@
|
||||
"""Backup package: naming, building (snapshots), reading and safe extraction.
|
||||
|
||||
A package is a tar.gz named ovpmon-backup_<server-name>_<YYYYMMDDTHHMMSS>Z.ovpbak (plus .enc when
|
||||
encrypted; -2, -3 after the Z when several packages are made in the same second) with this content:
|
||||
db/openvpn_monitor.db, db/ovpn_profiler.db consistent online snapshots (sqlite3 backup API)
|
||||
pki/... the easy-rsa PKI directory
|
||||
client-config/*.ovpn issued client profiles
|
||||
manifest.json format version, server name, schema versions, SHA-256 of every file
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import sqlite3
|
||||
import stat
|
||||
import tarfile
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from . import BackupError
|
||||
|
||||
FORMAT_NAME = "ovpmon-backup"
|
||||
FORMAT_VERSION = 1
|
||||
MANIFEST = "manifest.json"
|
||||
DB_MONITOR = "db/openvpn_monitor.db"
|
||||
DB_PROFILER = "db/ovpn_profiler.db"
|
||||
TOP_LEVEL = {"db", "pki", "client-config", MANIFEST} # allowlist of top-level names
|
||||
|
||||
SERVER_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9.-]{0,62}$")
|
||||
# Packages of the first pass carry the host name in the same place; they match too
|
||||
PACKAGE_RE = re.compile(
|
||||
r"^ovpmon-backup_(?P<host>[A-Za-z0-9][A-Za-z0-9.-]{0,62})_(?P<ts>\d{8}T\d{6}Z)(?:-(?P<seq>\d{1,3}))?"
|
||||
r"\.ovpbak(?P<enc>\.enc)?$")
|
||||
|
||||
MAX_FILES = 200000
|
||||
MAX_UNPACKED = int(os.environ.get("OVPMON_BACKUP_MAX_UNPACKED_BYTES", str(20 * 1024 ** 3)))
|
||||
MAX_MANIFEST = 64 * 1024 * 1024
|
||||
|
||||
|
||||
def sanitize_name(text: str) -> str:
|
||||
"""Make a server name of arbitrary text (host name, address); empty when nothing is left."""
|
||||
name = re.sub(r"[^A-Za-z0-9.-]", "-", text or "")[:63].strip("-.")
|
||||
return name if SERVER_NAME_RE.match(name) else ""
|
||||
|
||||
|
||||
def host_name() -> str:
|
||||
return sanitize_name(socket.gethostname()) or "host"
|
||||
|
||||
|
||||
def utc_stamp(now=None) -> str:
|
||||
return (now or datetime.now(timezone.utc)).strftime("%Y%m%dT%H%M%SZ")
|
||||
|
||||
|
||||
def package_name(server: str, stamp: str, encrypted: bool, seq: int = 1) -> str:
|
||||
return (f"ovpmon-backup_{server}_{stamp}" + (f"-{seq}" if seq > 1 else "")
|
||||
+ ".ovpbak" + (".enc" if encrypted else ""))
|
||||
|
||||
|
||||
def unique_package_name(server: str, stamp: str, encrypted: bool, existing) -> str:
|
||||
"""The name for a new package: the plain one, or with -2, -3 ... when the destination already
|
||||
holds a package of the same second. An existing file is never overwritten."""
|
||||
taken = set(existing)
|
||||
for seq in range(1, 1000):
|
||||
name = package_name(server, stamp, encrypted, seq)
|
||||
if name not in taken:
|
||||
return name
|
||||
raise BackupError("Too many packages with the same time stamp in the destination")
|
||||
|
||||
|
||||
def parse_package_name(name: str):
|
||||
"""{'host' (server name),'created_at' (ISO UTC),'encrypted','stamp','seq'} or None when the name is not ours."""
|
||||
m = PACKAGE_RE.match(name or "")
|
||||
if not m:
|
||||
return None
|
||||
ts = datetime.strptime(m.group("ts"), "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc)
|
||||
return {"host": m.group("host"), "created_at": ts.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
||||
"encrypted": bool(m.group("enc")), "stamp": m.group("ts"), "seq": int(m.group("seq") or 1)}
|
||||
|
||||
|
||||
# --- SQLite helpers ------------------------------------------------------------------------
|
||||
|
||||
def schema_version(db_path: str):
|
||||
"""Highest applied migration of a database (0: no migrations table), None if unreadable."""
|
||||
try:
|
||||
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30)
|
||||
try:
|
||||
has = conn.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_migrations'").fetchone()
|
||||
if not has:
|
||||
return 0
|
||||
return conn.execute("SELECT COALESCE(MAX(version), 0) FROM schema_migrations").fetchone()[0]
|
||||
finally:
|
||||
conn.close()
|
||||
except sqlite3.Error:
|
||||
return None
|
||||
|
||||
|
||||
def integrity_ok(db_path: str) -> bool:
|
||||
try:
|
||||
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=30)
|
||||
try:
|
||||
return [r[0] for r in conn.execute("PRAGMA integrity_check")] == ["ok"]
|
||||
finally:
|
||||
conn.close()
|
||||
except sqlite3.Error:
|
||||
return False
|
||||
|
||||
|
||||
def snapshot_db(src_path: str, dst_path: str) -> None:
|
||||
"""Consistent copy of a live database (online backup API); the copy is a single file
|
||||
(journal mode DELETE), so no -wal/-shm files belong to it."""
|
||||
if not os.path.isfile(src_path):
|
||||
raise BackupError(f"Database not found: {os.path.basename(src_path)}")
|
||||
src = sqlite3.connect(f"file:{src_path}?mode=ro", uri=True, timeout=60)
|
||||
dst = sqlite3.connect(dst_path)
|
||||
try:
|
||||
src.backup(dst)
|
||||
dst.execute("PRAGMA journal_mode=DELETE")
|
||||
dst.commit()
|
||||
except sqlite3.Error as e:
|
||||
raise BackupError(f"Cannot snapshot {os.path.basename(src_path)}: {e}") from e
|
||||
finally:
|
||||
src.close()
|
||||
dst.close()
|
||||
os.chmod(dst_path, 0o600)
|
||||
|
||||
|
||||
# --- building ------------------------------------------------------------------------------
|
||||
|
||||
def _copy_tree_regular(src: str, dst: str) -> int:
|
||||
"""Copy regular files and directories only (links and special files are skipped). Returns file count."""
|
||||
count = 0
|
||||
os.makedirs(dst, mode=0o700, exist_ok=True)
|
||||
for root, dirs, files in os.walk(src, followlinks=False):
|
||||
rel = os.path.relpath(root, src)
|
||||
target = dst if rel == "." else os.path.join(dst, rel)
|
||||
os.makedirs(target, mode=0o700, exist_ok=True)
|
||||
dirs[:] = [d for d in dirs if not os.path.islink(os.path.join(root, d))]
|
||||
for name in files:
|
||||
path = os.path.join(root, name)
|
||||
st = os.lstat(path)
|
||||
if not stat.S_ISREG(st.st_mode):
|
||||
continue
|
||||
out = os.path.join(target, name)
|
||||
shutil.copyfile(path, out)
|
||||
os.chmod(out, stat.S_IMODE(st.st_mode) & 0o777)
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def _sha256(path: str) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for block in iter(lambda: f.read(1024 * 1024), b""):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def build_package(out_path: str, work_dir: str, profiler_db: str, monitor_db: str,
|
||||
pki_dir: str, client_dir: str, runtime: str, server_name: str = "") -> dict:
|
||||
"""Write the (not encrypted) package tar.gz to out_path. Returns the manifest."""
|
||||
stage = os.path.join(work_dir, "stage")
|
||||
os.makedirs(os.path.join(stage, "db"), mode=0o700)
|
||||
snapshot_db(profiler_db, os.path.join(stage, DB_PROFILER))
|
||||
snapshot_db(monitor_db, os.path.join(stage, DB_MONITOR))
|
||||
if os.path.isdir(pki_dir):
|
||||
_copy_tree_regular(pki_dir, os.path.join(stage, "pki"))
|
||||
else:
|
||||
os.makedirs(os.path.join(stage, "pki"), mode=0o700)
|
||||
if os.path.isdir(client_dir):
|
||||
for name in sorted(os.listdir(client_dir)):
|
||||
path = os.path.join(client_dir, name)
|
||||
if name.endswith(".ovpn") and os.path.isfile(path) and not os.path.islink(path):
|
||||
os.makedirs(os.path.join(stage, "client-config"), mode=0o700, exist_ok=True)
|
||||
shutil.copyfile(path, os.path.join(stage, "client-config", name))
|
||||
os.makedirs(os.path.join(stage, "client-config"), mode=0o700, exist_ok=True)
|
||||
|
||||
files = {}
|
||||
for root, _dirs, names in os.walk(stage):
|
||||
for name in names:
|
||||
path = os.path.join(root, name)
|
||||
arc = os.path.relpath(path, stage).replace(os.sep, "/")
|
||||
files[arc] = {"sha256": _sha256(path), "size": os.path.getsize(path),
|
||||
"mode": stat.S_IMODE(os.stat(path).st_mode) & 0o777}
|
||||
profiles = 0
|
||||
try:
|
||||
conn = sqlite3.connect(os.path.join(stage, DB_PROFILER))
|
||||
try:
|
||||
profiles = conn.execute("SELECT COUNT(*) FROM user_profiles").fetchone()[0]
|
||||
finally:
|
||||
conn.close()
|
||||
except sqlite3.Error:
|
||||
pass
|
||||
manifest = {
|
||||
"format": FORMAT_NAME,
|
||||
"format_version": FORMAT_VERSION,
|
||||
"created_at": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
||||
"server_name": server_name or host_name(),
|
||||
"hostname": socket.gethostname(),
|
||||
"runtime": runtime,
|
||||
"schema": {"profiler": schema_version(os.path.join(stage, DB_PROFILER)),
|
||||
"monitor": schema_version(os.path.join(stage, DB_MONITOR))},
|
||||
"profiles": profiles,
|
||||
"files": files,
|
||||
}
|
||||
manifest_path = os.path.join(stage, MANIFEST)
|
||||
with open(manifest_path, "w") as f:
|
||||
json.dump(manifest, f, indent=1, sort_keys=True)
|
||||
|
||||
fd = os.open(out_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "wb") as raw, tarfile.open(fileobj=raw, mode="w:gz") as tar:
|
||||
# Directories first (so empty ones survive), then files; fixed owner, no time-dependent names
|
||||
entries = []
|
||||
for root, dirs, names in os.walk(stage):
|
||||
for name in dirs + names:
|
||||
path = os.path.join(root, name)
|
||||
entries.append((os.path.relpath(path, stage).replace(os.sep, "/"), path))
|
||||
for arc, path in sorted(entries):
|
||||
info = tar.gettarinfo(path, arcname=arc)
|
||||
info.uid = info.gid = 0
|
||||
info.uname = info.gname = ""
|
||||
if info.isdir():
|
||||
tar.addfile(info)
|
||||
else:
|
||||
with open(path, "rb") as f:
|
||||
tar.addfile(info, f)
|
||||
shutil.rmtree(stage, ignore_errors=True)
|
||||
return manifest
|
||||
|
||||
|
||||
# --- reading and safe extraction -----------------------------------------------------------
|
||||
|
||||
def _check_member_name(name: str):
|
||||
if not name or name.startswith("/") or "\\" in name or "\x00" in name:
|
||||
raise BackupError(f"Unsafe path in package: {name!r}")
|
||||
parts = name.split("/")
|
||||
if any(p in ("", ".", "..") for p in parts):
|
||||
raise BackupError(f"Unsafe path in package: {name!r}")
|
||||
if parts[0] not in TOP_LEVEL:
|
||||
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||
if parts[0] == MANIFEST and len(parts) != 1:
|
||||
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||
if parts[0] == "db" and name not in ("db", DB_MONITOR, DB_PROFILER):
|
||||
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||
if parts[0] == "client-config" and len(parts) > 2:
|
||||
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||
if parts[0] == "client-config" and len(parts) == 2 and not parts[1].endswith(".ovpn"):
|
||||
raise BackupError(f"Unexpected entry in package: {name!r}")
|
||||
|
||||
|
||||
def safe_extract(package_path: str, dest: str) -> dict:
|
||||
"""Extract an unencrypted package into the empty directory dest, checking every entry.
|
||||
Only regular files and directories under the allowlisted names are accepted: absolute paths,
|
||||
'..', links, devices and oversized content are rejected. Returns the verified manifest."""
|
||||
os.makedirs(dest, mode=0o700, exist_ok=True)
|
||||
base = os.path.realpath(dest)
|
||||
total, count = 0, 0
|
||||
try:
|
||||
tar = tarfile.open(package_path, mode="r:gz")
|
||||
except (tarfile.TarError, OSError, EOFError) as e:
|
||||
raise BackupError(f"Cannot read the package: {e}") from e
|
||||
try:
|
||||
for member in tar:
|
||||
count += 1
|
||||
if count > MAX_FILES:
|
||||
raise BackupError("Package has too many entries")
|
||||
name = member.name.rstrip("/") if member.isdir() else member.name
|
||||
_check_member_name(name)
|
||||
if not (member.isreg() or member.isdir()):
|
||||
raise BackupError(f"Package contains a link or special file: {name!r}")
|
||||
target = os.path.realpath(os.path.join(base, name))
|
||||
if target != base and not target.startswith(base + os.sep):
|
||||
raise BackupError(f"Unsafe path in package: {name!r}")
|
||||
if member.isdir():
|
||||
os.makedirs(target, mode=0o700, exist_ok=True)
|
||||
continue
|
||||
if member.size < 0 or total + member.size > MAX_UNPACKED:
|
||||
raise BackupError("Package is larger than the allowed unpacked size")
|
||||
if name == MANIFEST and member.size > MAX_MANIFEST:
|
||||
raise BackupError("Manifest is too large")
|
||||
total += member.size
|
||||
os.makedirs(os.path.dirname(target), mode=0o700, exist_ok=True)
|
||||
src = tar.extractfile(member)
|
||||
fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, "wb") as out:
|
||||
shutil.copyfileobj(src, out)
|
||||
os.chmod(target, member.mode & 0o777 & ~0o7000)
|
||||
except (tarfile.TarError, OSError, EOFError) as e:
|
||||
if isinstance(e, FileExistsError):
|
||||
raise BackupError("Package contains duplicate entries") from e
|
||||
raise BackupError(f"Package is damaged or cannot be unpacked: {e}") from e
|
||||
finally:
|
||||
tar.close()
|
||||
return verify_extracted(dest)
|
||||
|
||||
|
||||
def verify_extracted(dest: str) -> dict:
|
||||
"""Read manifest.json and check that the extracted files are exactly the listed ones with the
|
||||
listed sizes and SHA-256 sums. Returns the manifest."""
|
||||
path = os.path.join(dest, MANIFEST)
|
||||
if not os.path.isfile(path):
|
||||
raise BackupError("Package has no manifest.json")
|
||||
try:
|
||||
with open(path) as f:
|
||||
manifest = json.load(f)
|
||||
files = manifest["files"]
|
||||
fmt, version = manifest["format"], manifest["format_version"]
|
||||
manifest["schema"]["profiler"], manifest["schema"]["monitor"]
|
||||
except (ValueError, KeyError, TypeError) as e:
|
||||
raise BackupError("Package manifest is invalid") from e
|
||||
if fmt != FORMAT_NAME or not isinstance(version, int) or version > FORMAT_VERSION or version < 1:
|
||||
raise BackupError(f"Unknown package format (format_version {version!r}); "
|
||||
f"this release reads format {FORMAT_VERSION}")
|
||||
if not isinstance(files, dict):
|
||||
raise BackupError("Package manifest is invalid")
|
||||
present = set()
|
||||
for root, _dirs, names in os.walk(dest):
|
||||
for name in names:
|
||||
rel = os.path.relpath(os.path.join(root, name), dest).replace(os.sep, "/")
|
||||
if rel != MANIFEST:
|
||||
present.add(rel)
|
||||
if present != set(files):
|
||||
extra, missing = sorted(present - set(files)), sorted(set(files) - present)
|
||||
raise BackupError("Package content does not match the manifest"
|
||||
+ (f" (not listed: {extra[0]})" if extra else "")
|
||||
+ (f" (missing: {missing[0]})" if missing else ""))
|
||||
for rel, meta in files.items():
|
||||
full = os.path.join(dest, rel)
|
||||
if os.path.getsize(full) != meta.get("size") or _sha256(full) != meta.get("sha256"):
|
||||
raise BackupError(f"Checksum mismatch: {rel}. The package is damaged")
|
||||
for required in (DB_PROFILER, DB_MONITOR):
|
||||
if required not in files:
|
||||
raise BackupError(f"Package has no {required}")
|
||||
return manifest
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Settings, destinations and history of the backup feature.
|
||||
|
||||
A separate SQLite file (ovpmon_backup.db) next to the profiler database. A restore replaces
|
||||
ovpn_profiler.db and openvpn_monitor.db, but never this file, so the destinations survive it and
|
||||
never travel inside a package. The schema is created at service start (own version table, the
|
||||
migrations of the two application databases are not involved).
|
||||
|
||||
Secrets (destination keys, the package passphrase) are encrypted at rest with a key derived
|
||||
(HKDF-SHA256) from the JWT signing key. They are never returned by the API and never logged.
|
||||
If the JWT key changes they cannot be decrypted any more and have to be entered again.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sqlite3
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||
|
||||
from . import BackupError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
DEFAULT_RETENTION = 14
|
||||
HISTORY_KEEP = 100
|
||||
MASK = "********"
|
||||
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def db_file() -> str:
|
||||
from database import db_path
|
||||
return os.path.join(os.path.dirname(os.path.abspath(db_path)), "ovpmon_backup.db")
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _conn():
|
||||
conn = sqlite3.connect(db_file(), timeout=30)
|
||||
conn.row_factory = sqlite3.Row
|
||||
try:
|
||||
yield conn
|
||||
conn.commit()
|
||||
except BaseException:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def init() -> None:
|
||||
"""Create the schema (idempotent). Called at service start."""
|
||||
path = db_file()
|
||||
new = not os.path.exists(path)
|
||||
with _lock, _conn() as c:
|
||||
c.execute("CREATE TABLE IF NOT EXISTS backup_schema (version INTEGER NOT NULL)")
|
||||
c.execute("CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)")
|
||||
c.execute("""CREATE TABLE IF NOT EXISTS destinations (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
type TEXT NOT NULL,
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
retention_count INTEGER NOT NULL DEFAULT 14,
|
||||
params TEXT NOT NULL DEFAULT '{}',
|
||||
secrets_enc TEXT NOT NULL DEFAULT '',
|
||||
last_status TEXT,
|
||||
last_message TEXT,
|
||||
last_at TEXT,
|
||||
created_at TEXT NOT NULL)""")
|
||||
c.execute("""CREATE TABLE IF NOT EXISTS history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
kind TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
started_at TEXT NOT NULL,
|
||||
finished_at TEXT,
|
||||
message TEXT,
|
||||
results TEXT NOT NULL DEFAULT '[]')""")
|
||||
if not c.execute("SELECT 1 FROM backup_schema").fetchone():
|
||||
c.execute("INSERT INTO backup_schema (version) VALUES (?)", (SCHEMA_VERSION,))
|
||||
# A job that was running when the service stopped did not finish
|
||||
c.execute("UPDATE history SET state='interrupted', finished_at=? WHERE state='running'", (_now(),))
|
||||
if new:
|
||||
os.chmod(path, 0o600)
|
||||
|
||||
|
||||
# --- secrets -------------------------------------------------------------------------------
|
||||
|
||||
def _fernet() -> Fernet:
|
||||
from utils.auth import SECRET_KEY
|
||||
key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None,
|
||||
info=b"ovpmon-backup-secrets-v1").derive(SECRET_KEY.encode("utf-8"))
|
||||
return Fernet(base64.urlsafe_b64encode(key))
|
||||
|
||||
|
||||
def encrypt_text(text: str) -> str:
|
||||
return _fernet().encrypt(text.encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def decrypt_text(token: str) -> str:
|
||||
try:
|
||||
return _fernet().decrypt(token.encode("ascii")).decode("utf-8")
|
||||
except (InvalidToken, ValueError):
|
||||
raise BackupError("Stored secrets cannot be decrypted (the JWT secret changed). "
|
||||
"Enter them again.") from None
|
||||
|
||||
|
||||
# --- settings ------------------------------------------------------------------------------
|
||||
|
||||
def _get_setting(key):
|
||||
with _conn() as c:
|
||||
row = c.execute("SELECT value FROM settings WHERE key=?", (key,)).fetchone()
|
||||
return row["value"] if row else None
|
||||
|
||||
|
||||
def _set_setting(key, value):
|
||||
with _lock, _conn() as c:
|
||||
if value is None:
|
||||
c.execute("DELETE FROM settings WHERE key=?", (key,))
|
||||
else:
|
||||
c.execute("INSERT INTO settings (key, value) VALUES (?, ?) "
|
||||
"ON CONFLICT(key) DO UPDATE SET value=excluded.value", (key, value))
|
||||
|
||||
|
||||
def has_passphrase() -> bool:
|
||||
return bool(_get_setting("passphrase_enc"))
|
||||
|
||||
|
||||
def get_passphrase():
|
||||
"""The package passphrase, or None when none is set. Raises BackupError if it cannot be decrypted."""
|
||||
token = _get_setting("passphrase_enc")
|
||||
return decrypt_text(token) if token else None
|
||||
|
||||
|
||||
def set_passphrase(value) -> None:
|
||||
_set_setting("passphrase_enc", encrypt_text(value) if value else None)
|
||||
|
||||
|
||||
def default_retention() -> int:
|
||||
try:
|
||||
return int(_get_setting("default_retention") or DEFAULT_RETENTION)
|
||||
except ValueError:
|
||||
return DEFAULT_RETENTION
|
||||
|
||||
|
||||
def set_default_retention(n: int) -> None:
|
||||
_set_setting("default_retention", str(int(n)))
|
||||
|
||||
|
||||
def get_server_name() -> str:
|
||||
"""The server name set by the administrator ('' when none). Lives here, not in the profiler
|
||||
database: a restore replaces that one, and the name belongs to this server."""
|
||||
return _get_setting("server_name") or ""
|
||||
|
||||
|
||||
def set_server_name(value) -> None:
|
||||
_set_setting("server_name", value or None)
|
||||
|
||||
|
||||
# --- destinations --------------------------------------------------------------------------
|
||||
|
||||
def _row_to_dest(row, with_secrets=False):
|
||||
d = {"id": row["id"], "name": row["name"], "type": row["type"], "enabled": bool(row["enabled"]),
|
||||
"retention_count": row["retention_count"], "params": json.loads(row["params"]),
|
||||
"last_status": row["last_status"], "last_message": row["last_message"], "last_at": row["last_at"]}
|
||||
secrets, secrets_ok = {}, True
|
||||
if row["secrets_enc"]:
|
||||
try:
|
||||
secrets = json.loads(decrypt_text(row["secrets_enc"]))
|
||||
except BackupError:
|
||||
secrets_ok = False
|
||||
d["secrets_ok"] = secrets_ok
|
||||
if with_secrets:
|
||||
d["secrets"] = secrets
|
||||
else:
|
||||
# Masked: the UI only learns which secrets are set
|
||||
d["secrets"] = {k: MASK for k, v in secrets.items() if v}
|
||||
return d
|
||||
|
||||
|
||||
def list_destinations(with_secrets=False):
|
||||
with _conn() as c:
|
||||
rows = c.execute("SELECT * FROM destinations ORDER BY id").fetchall()
|
||||
return [_row_to_dest(r, with_secrets) for r in rows]
|
||||
|
||||
|
||||
def get_destination(dest_id: int, with_secrets=False):
|
||||
with _conn() as c:
|
||||
row = c.execute("SELECT * FROM destinations WHERE id=?", (dest_id,)).fetchone()
|
||||
return _row_to_dest(row, with_secrets) if row else None
|
||||
|
||||
|
||||
def save_destination(dest_id, name, dtype, enabled, retention_count, params, secrets) -> int:
|
||||
"""Insert (dest_id None) or update. Raises BackupError on a duplicate name."""
|
||||
enc = encrypt_text(json.dumps(secrets)) if secrets else ""
|
||||
try:
|
||||
with _lock, _conn() as c:
|
||||
if dest_id is None:
|
||||
cur = c.execute(
|
||||
"INSERT INTO destinations (name, type, enabled, retention_count, params, secrets_enc, created_at) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
(name, dtype, int(enabled), retention_count, json.dumps(params), enc, _now()))
|
||||
return cur.lastrowid
|
||||
c.execute("UPDATE destinations SET name=?, type=?, enabled=?, retention_count=?, params=?, "
|
||||
"secrets_enc=? WHERE id=?",
|
||||
(name, dtype, int(enabled), retention_count, json.dumps(params), enc, dest_id))
|
||||
return dest_id
|
||||
except sqlite3.IntegrityError:
|
||||
raise BackupError(f"A destination named '{name}' already exists") from None
|
||||
|
||||
|
||||
def delete_destination(dest_id: int) -> bool:
|
||||
with _lock, _conn() as c:
|
||||
return c.execute("DELETE FROM destinations WHERE id=?", (dest_id,)).rowcount > 0
|
||||
|
||||
|
||||
def set_last_result(dest_id: int, ok: bool, message: str) -> None:
|
||||
with _lock, _conn() as c:
|
||||
c.execute("UPDATE destinations SET last_status=?, last_message=?, last_at=? WHERE id=?",
|
||||
("ok" if ok else "error", (message or "")[:500], _now(), dest_id))
|
||||
|
||||
|
||||
# --- history -------------------------------------------------------------------------------
|
||||
|
||||
def history_start(kind: str) -> int:
|
||||
with _lock, _conn() as c:
|
||||
return c.execute("INSERT INTO history (kind, state, started_at) VALUES (?, 'running', ?)",
|
||||
(kind, _now())).lastrowid
|
||||
|
||||
|
||||
def history_finish(hist_id: int, state: str, message: str, results: list) -> None:
|
||||
with _lock, _conn() as c:
|
||||
c.execute("UPDATE history SET state=?, finished_at=?, message=?, results=? WHERE id=?",
|
||||
(state, _now(), (message or "")[:1000], json.dumps(results), hist_id))
|
||||
c.execute("DELETE FROM history WHERE id NOT IN (SELECT id FROM history ORDER BY id DESC LIMIT ?)",
|
||||
(HISTORY_KEEP,))
|
||||
|
||||
|
||||
def history_list(limit: int = 20) -> list:
|
||||
with _conn() as c:
|
||||
rows = c.execute("SELECT * FROM history ORDER BY id DESC LIMIT ?", (limit,)).fetchall()
|
||||
return [{"id": r["id"], "kind": r["kind"], "state": r["state"], "started_at": r["started_at"],
|
||||
"finished_at": r["finished_at"], "message": r["message"], "results": json.loads(r["results"])}
|
||||
for r in rows]
|
||||
@@ -144,6 +144,19 @@ def is_init_running() -> bool:
|
||||
with _init_lock:
|
||||
return _init_job["state"] == "running"
|
||||
|
||||
# A backup restore replaces the PKI, the profile files and the databases: while it runs,
|
||||
# everything that changes them is refused (set by services/backup/engine.py)
|
||||
_restore_running = False
|
||||
|
||||
def set_restore_running(value: bool):
|
||||
global _restore_running
|
||||
_restore_running = bool(value)
|
||||
|
||||
def is_restore_running() -> bool:
|
||||
return _restore_running
|
||||
|
||||
RESTORE_RUNNING_MSG = "A backup restore is running"
|
||||
|
||||
class PkiNotReady(Exception):
|
||||
"""An operation needs keys that are not there (PKI absent, init running or server files missing)."""
|
||||
|
||||
@@ -243,6 +256,8 @@ def start_init_async(db: Session):
|
||||
with _init_lock:
|
||||
if _init_job["state"] == "running":
|
||||
raise InitConflict("PKI initialization is already running")
|
||||
if is_restore_running():
|
||||
raise InitConflict(RESTORE_RUNNING_MSG)
|
||||
if is_initialized():
|
||||
raise InitConflict("PKI is already initialized")
|
||||
# Here the PKI is absent, has no CA, or carries the marker of an interrupted run:
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
import io
|
||||
import os
|
||||
import sqlite3
|
||||
import tarfile
|
||||
import tempfile
|
||||
import types
|
||||
|
||||
import pytest
|
||||
|
||||
# The DB path must be set before database.py is imported (via main)
|
||||
_tmp = tempfile.TemporaryDirectory()
|
||||
os.environ.setdefault("OVPMON_PROFILER_DB_PATH", os.path.join(_tmp.name, "test.db"))
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
import migrations
|
||||
from services import pki, process
|
||||
from services.backup import BackupError, crypto, destinations, engine, package, store
|
||||
from utils.auth import verify_token
|
||||
|
||||
app.dependency_overrides[verify_token] = lambda: {"sub": "test"}
|
||||
client = TestClient(app)
|
||||
|
||||
PASS = "correct horse battery"
|
||||
|
||||
|
||||
class InlineThread:
|
||||
"""Runs the job in the calling thread: the tests need no polling."""
|
||||
def __init__(self, target, args=(), daemon=None):
|
||||
self.target, self.args = target, args
|
||||
|
||||
def start(self):
|
||||
self.target(*self.args)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env(tmp_path, monkeypatch):
|
||||
"""A complete data layout in a temporary directory, nothing of the real system is touched."""
|
||||
data = tmp_path / "data"
|
||||
data.mkdir()
|
||||
prof, mon = str(data / "ovpn_profiler.db"), str(data / "openvpn_monitor.db")
|
||||
migrations.run(prof)
|
||||
conn = sqlite3.connect(mon)
|
||||
conn.executescript("CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, name TEXT, applied_at TEXT);"
|
||||
"INSERT INTO schema_migrations VALUES (2, 'x', 'now');"
|
||||
"CREATE TABLE users (name TEXT); INSERT INTO users VALUES ('admin');")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
pki_dir, client_dir = tmp_path / "easy-rsa" / "pki", tmp_path / "client-config"
|
||||
(pki_dir / "private").mkdir(parents=True)
|
||||
(pki_dir / "ca.crt").write_text("CA")
|
||||
(pki_dir / "private" / "ca.key").write_text("SECRET")
|
||||
os.chmod(pki_dir / "private" / "ca.key", 0o600)
|
||||
client_dir.mkdir()
|
||||
(client_dir / "alice.ovpn").write_text("client config")
|
||||
monkeypatch.setenv("OVPMON_BACKUP_LOCAL_ROOT", str(tmp_path / "backups"))
|
||||
monkeypatch.setattr(engine, "profiler_db_path", lambda: prof)
|
||||
monkeypatch.setattr(engine, "monitor_db_path", lambda: mon)
|
||||
monkeypatch.setattr(engine, "client_dir", lambda: str(client_dir))
|
||||
monkeypatch.setattr(engine, "core_dir", lambda: None) # the schemas are equal: no migration needed
|
||||
monkeypatch.setattr(pki, "PKI_DIR", str(pki_dir))
|
||||
monkeypatch.setattr(process, "get_process_stats", lambda: {"status": "stopped"})
|
||||
monkeypatch.setattr(engine, "threading", types.SimpleNamespace(Thread=InlineThread))
|
||||
monkeypatch.setattr(store, "db_file", lambda: str(tmp_path / "ovpmon_backup.db"))
|
||||
store.init()
|
||||
return types.SimpleNamespace(root=tmp_path, prof=prof, mon=mon, pki=pki_dir, clients=client_dir)
|
||||
|
||||
|
||||
def test_package_round_trip_and_wrong_passphrase(env, tmp_path):
|
||||
work = tmp_path / "w"
|
||||
work.mkdir()
|
||||
path, name, manifest = engine.create_package(str(work), PASS)
|
||||
assert name.endswith(".ovpbak.enc") and package.parse_package_name(name)["encrypted"]
|
||||
assert crypto.is_encrypted(path) and b"SECRET" not in open(path, "rb").read()
|
||||
assert manifest["schema"]["monitor"] == 2 and "pki/private/ca.key" in manifest["files"]
|
||||
|
||||
with pytest.raises(crypto.WrongPassphrase):
|
||||
crypto.decrypt_file(path, str(tmp_path / "bad.tar.gz"), "wrong passphrase")
|
||||
crypto.decrypt_file(path, str(tmp_path / "ok.tar.gz"), PASS)
|
||||
out = tmp_path / "out"
|
||||
package.safe_extract(str(tmp_path / "ok.tar.gz"), str(out))
|
||||
assert (out / "pki" / "ca.crt").read_text() == "CA"
|
||||
assert (out / "pki" / "private" / "ca.key").read_text() == "SECRET"
|
||||
assert oct(os.stat(out / "pki" / "private" / "ca.key").st_mode & 0o777) == "0o600"
|
||||
assert (out / "client-config" / "alice.ovpn").read_text() == "client config"
|
||||
assert sqlite3.connect(out / "db" / "openvpn_monitor.db").execute("SELECT name FROM users").fetchone() == ("admin",)
|
||||
assert package.integrity_ok(str(out / "db" / "ovpn_profiler.db"))
|
||||
|
||||
|
||||
def _tar(path, members):
|
||||
with tarfile.open(path, "w:gz") as tar:
|
||||
for info, data in members:
|
||||
tar.addfile(info, io.BytesIO(data) if data is not None else None)
|
||||
|
||||
|
||||
def test_safe_extraction_and_newer_schema(env, tmp_path):
|
||||
def reg(name, data=b"x"):
|
||||
info = tarfile.TarInfo(name)
|
||||
info.size = len(data)
|
||||
return info, data
|
||||
|
||||
link = tarfile.TarInfo("pki/link")
|
||||
link.type, link.linkname = tarfile.SYMTYPE, "/etc/passwd"
|
||||
for i, members in enumerate([[reg("../evil")], [reg("/abs/evil")], [reg("pki/../../evil")],
|
||||
[(link, None)], [reg("other/file")], [reg("db/extra.db")]]):
|
||||
bad = str(tmp_path / f"bad{i}.tar.gz")
|
||||
_tar(bad, members)
|
||||
with pytest.raises(BackupError):
|
||||
package.safe_extract(bad, str(tmp_path / f"out{i}"))
|
||||
assert not (tmp_path / "evil").exists()
|
||||
|
||||
# A valid package from a newer release is refused before anything is touched
|
||||
work = tmp_path / "w"
|
||||
work.mkdir()
|
||||
path, _name, _ = engine.create_package(str(work), None)
|
||||
out = tmp_path / "ok"
|
||||
manifest = package.safe_extract(path, str(out))
|
||||
conn = sqlite3.connect(out / "db" / "ovpn_profiler.db")
|
||||
conn.execute("INSERT INTO schema_migrations VALUES (999, 'future', 'now')")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
with pytest.raises(BackupError, match="newer release"):
|
||||
engine._prepare_staged(str(out), manifest)
|
||||
# An unknown format version is refused too
|
||||
import json
|
||||
manifest["format_version"] = 99
|
||||
(out / "manifest.json").write_text(json.dumps(manifest))
|
||||
with pytest.raises(BackupError, match="Unknown package format"):
|
||||
package.verify_extracted(str(out))
|
||||
|
||||
|
||||
class FailingDestination(destinations.Destination):
|
||||
type = "stub"
|
||||
label = "Stub"
|
||||
|
||||
def put(self, local_path, name):
|
||||
raise destinations.DestinationError("disk on fire")
|
||||
|
||||
def list(self):
|
||||
return []
|
||||
|
||||
|
||||
def test_multi_destination_backup_rotation_and_restore(env, tmp_path, monkeypatch):
|
||||
monkeypatch.setitem(destinations.DESTINATION_TYPES, "stub", FailingDestination)
|
||||
good = store.save_destination(None, "local-good", "local", True, 2, {"folder": "daily"}, {})
|
||||
bad = store.save_destination(None, "broken", "stub", True, 14, {}, {})
|
||||
stamps = iter(f"20261007T1000{i:02d}Z" for i in range(10))
|
||||
monkeypatch.setattr(package, "utc_stamp", lambda now=None: next(stamps))
|
||||
|
||||
for _ in range(3):
|
||||
engine.start_backup(None)
|
||||
job = engine.status()
|
||||
assert job["state"] == "partial" # one failed, the other still got the package
|
||||
by_name = {r["name"]: r for r in job["results"]}
|
||||
assert by_name["local-good"]["state"] == "ok" and by_name["broken"]["state"] == "error"
|
||||
assert "disk on fire" in by_name["broken"]["message"]
|
||||
assert store.get_destination(bad)["last_status"] == "error"
|
||||
names = sorted(p["name"] for p in engine.list_packages(good))
|
||||
assert len(names) == 2 and names[0].endswith("100001Z.ovpbak") # oldest of 3 rotated away
|
||||
|
||||
# Restore the newest package after the live data was damaged
|
||||
newest = engine.list_packages(good)[0]["name"]
|
||||
env.pki.joinpath("ca.crt").write_text("DAMAGED")
|
||||
(env.clients / "alice.ovpn").unlink()
|
||||
(env.clients / "stray.ovpn").write_text("not in the package")
|
||||
sqlite3.connect(env.mon).execute("DROP TABLE users").connection.commit()
|
||||
engine.start_restore(good, newest, None)
|
||||
job = engine.status()
|
||||
assert job["state"] == "done", job["message"]
|
||||
assert job["relogin"] is True
|
||||
assert env.pki.joinpath("ca.crt").read_text() == "CA"
|
||||
assert (env.clients / "alice.ovpn").read_text() == "client config" and not (env.clients / "stray.ovpn").exists()
|
||||
assert sqlite3.connect(env.mon).execute("SELECT name FROM users").fetchone() == ("admin",)
|
||||
assert not [p for p in os.listdir(env.pki) if p.startswith(".restore-")]
|
||||
# the previous state was saved first, locally
|
||||
pre = destinations.LocalDestination({"folder": "pre-restore"}, {}).list()
|
||||
assert len(pre) == 1 and package.parse_package_name(pre[0]["name"])
|
||||
|
||||
# A package that is not in the listing is not accepted
|
||||
with pytest.raises(BackupError):
|
||||
engine.start_restore(good, "ovpmon-backup_x_20200101T000000Z.ovpbak", None)
|
||||
|
||||
|
||||
def test_api_requires_jwt_masks_secrets_and_refuses_remote_without_passphrase(env):
|
||||
saved = app.dependency_overrides.pop(verify_token)
|
||||
try:
|
||||
for method, path in [("get", "/api/backup/settings"), ("put", "/api/backup/settings"),
|
||||
("get", "/api/backup/destinations"), ("post", "/api/backup/destinations"),
|
||||
("put", "/api/backup/destinations/1"), ("delete", "/api/backup/destinations/1"),
|
||||
("post", "/api/backup/destinations/1/test"), ("get", "/api/backup/destinations/1/packages"),
|
||||
("post", "/api/backup/run"), ("post", "/api/backup/restore"),
|
||||
("get", "/api/backup/status"), ("get", "/api/backup/history")]:
|
||||
assert getattr(client, method)(path).status_code == 401, (method, path)
|
||||
finally:
|
||||
app.dependency_overrides[verify_token] = saved
|
||||
|
||||
s3 = {"name": "bucket", "type": "s3", "params": {"endpoint": "s3.example.com", "bucket": "my-backups"},
|
||||
"secrets": {"access_key": "AKIAEXAMPLE", "secret_key": "TOPSECRETVALUE"}}
|
||||
r = client.post("/api/backup/destinations", json=s3)
|
||||
assert r.status_code == 201
|
||||
dest = r.json()
|
||||
assert "TOPSECRETVALUE" not in r.text and "AKIAEXAMPLE" not in r.text
|
||||
assert dest["secrets"] == {"access_key": store.MASK, "secret_key": store.MASK}
|
||||
assert "TOPSECRETVALUE" not in client.get("/api/backup/destinations").text
|
||||
assert "TOPSECRETVALUE" not in open(store.db_file(), "rb").read().decode("latin-1") # encrypted at rest
|
||||
|
||||
# Only implemented types; updating with the mask keeps the stored secret
|
||||
assert client.post("/api/backup/destinations", json={**s3, "name": "x", "type": "smb"}).status_code == 400
|
||||
s3["secrets"] = {"access_key": store.MASK, "secret_key": ""}
|
||||
assert client.put(f"/api/backup/destinations/{dest['id']}", json=s3).status_code == 200
|
||||
assert store.get_destination(dest["id"], with_secrets=True)["secrets"]["secret_key"] == "TOPSECRETVALUE"
|
||||
|
||||
# Remote destination without a passphrase: no backup
|
||||
r = client.post("/api/backup/run", json={})
|
||||
assert r.status_code == 400 and "passphrase" in r.json()["detail"].lower()
|
||||
assert client.put("/api/backup/settings", json={"passphrase": "short"}).status_code == 400
|
||||
r = client.put("/api/backup/settings", json={"passphrase": PASS})
|
||||
assert r.status_code == 200 and r.json()["encryption_enabled"] is True and PASS not in r.text
|
||||
assert client.put("/api/backup/settings", json={"clear_passphrase": True}).status_code == 400 # remote needs it
|
||||
|
||||
|
||||
def test_package_name_server_name_fallback_and_unique_names(env, tmp_path, monkeypatch):
|
||||
import re
|
||||
import socket
|
||||
monkeypatch.setattr(socket, "gethostname", lambda: "3f9a1c0b2d44")
|
||||
assert engine.effective_server_name() == ("3f9a1c0b2d44", "hostname")
|
||||
conn = sqlite3.connect(env.prof)
|
||||
conn.execute("INSERT INTO system_settings (id, public_ip) VALUES (1, 'vpn.example.com')")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
assert engine.effective_server_name() == ("vpn.example.com", "public_ip")
|
||||
|
||||
# The setting wins, is validated, and can be cleared again
|
||||
assert client.put("/api/backup/settings", json={"server_name": "bad name!"}).status_code == 400
|
||||
r = client.put("/api/backup/settings", json={"server_name": "vpn-main"}).json()
|
||||
assert (r["server_name"], r["effective_server_name"], r["server_name_source"]) == ("vpn-main", "vpn-main", "setting")
|
||||
assert client.put("/api/backup/settings", json={"server_name": ""}).json()["server_name_source"] == "public_ip"
|
||||
store.set_server_name("vpn-main")
|
||||
|
||||
# Name format, manifest, and -2 / -3 when the same second is taken (nothing is overwritten)
|
||||
monkeypatch.setattr(package, "utc_stamp", lambda now=None: "20261007T101500Z")
|
||||
dest = store.save_destination(None, "local-daily", "local", True, 2, {"folder": "daily"}, {})
|
||||
old = "ovpmon-backup_oldhost_20200101T000000Z.ovpbak" # first-pass name: listed, never rotated
|
||||
destinations.LocalDestination({"folder": "daily"}, {}).put(str(env.prof), old)
|
||||
for _ in range(3):
|
||||
engine.start_backup(None)
|
||||
assert engine.status()["state"] == "done"
|
||||
packages = engine.list_packages(dest)
|
||||
assert [p["name"] for p in packages] == [
|
||||
"ovpmon-backup_vpn-main_20261007T101500Z-3.ovpbak",
|
||||
"ovpmon-backup_vpn-main_20261007T101500Z-2.ovpbak", old] # newest first; -1 rotated away
|
||||
assert packages[0]["server_name"] == "vpn-main" and packages[2]["server_name"] == "oldhost"
|
||||
work = tmp_path / "w"
|
||||
work.mkdir()
|
||||
_path, name, manifest = engine.create_package(str(work), None)
|
||||
assert name == "ovpmon-backup_vpn-main_20261007T101500Z.ovpbak"
|
||||
assert manifest["server_name"] == "vpn-main" and manifest["hostname"] == "3f9a1c0b2d44"
|
||||
assert re.match(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$", manifest["created_at"])
|
||||
|
||||
|
||||
class FakeKey:
|
||||
blob = b"server-host-key-A"
|
||||
|
||||
def asbytes(self):
|
||||
return self.blob
|
||||
|
||||
def get_name(self):
|
||||
return "ssh-ed25519"
|
||||
|
||||
|
||||
class FakeSFTP:
|
||||
files, dirs = {}, set()
|
||||
|
||||
def get_channel(self):
|
||||
return types.SimpleNamespace(settimeout=lambda t: None)
|
||||
|
||||
def stat(self, path):
|
||||
if path in self.dirs:
|
||||
return types.SimpleNamespace(st_mode=0o40700)
|
||||
raise FileNotFoundError(path)
|
||||
|
||||
def mkdir(self, path, mode=0o777):
|
||||
self.dirs.add(path)
|
||||
|
||||
def put(self, local, remote, confirm=True):
|
||||
self.files[remote] = open(local, "rb").read()
|
||||
|
||||
def putfo(self, fh, remote):
|
||||
self.files[remote] = fh.read()
|
||||
|
||||
def posix_rename(self, a, b):
|
||||
self.files[b] = self.files.pop(a)
|
||||
|
||||
def remove(self, path):
|
||||
del self.files[path]
|
||||
|
||||
def listdir_attr(self, directory):
|
||||
return [types.SimpleNamespace(filename=p.rsplit("/", 1)[-1], st_mode=0o100600, st_size=len(v), st_mtime=1.0)
|
||||
for p, v in self.files.items() if p.rsplit("/", 1)[0] == directory]
|
||||
|
||||
def getfo(self, remote, out):
|
||||
out.write(self.files[remote])
|
||||
|
||||
|
||||
class FakeSSH:
|
||||
connects = []
|
||||
|
||||
def set_missing_host_key_policy(self, policy):
|
||||
self.policy = policy
|
||||
|
||||
def connect(self, host, **kw):
|
||||
FakeSSH.connects.append((host, kw.get("password"), kw.get("pkey")))
|
||||
self.policy.missing_host_key(self, host, FakeKey()) # raises unless the key is the pinned one
|
||||
|
||||
def open_sftp(self):
|
||||
return FakeSFTP()
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
def test_sftp_ftp_validation_and_host_key_pinning(env, monkeypatch):
|
||||
import paramiko
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ed25519
|
||||
monkeypatch.setattr(paramiko, "SSHClient", FakeSSH)
|
||||
FakeSFTP.files, FakeSFTP.dirs = {}, set()
|
||||
FakeSSH.connects.clear()
|
||||
sftp, ftp = destinations.SFTPDestination, destinations.FTPDestination
|
||||
base = {"host": "files.example.com", "port": 22, "username": "backup", "directory": "ovpmon/daily"}
|
||||
|
||||
# Parameter and secret rules
|
||||
for bad in ({"host": "bad host!"}, {"port": 70000}, {"username": ""}, {"directory": "../x"}, {"directory": "/etc"}):
|
||||
with pytest.raises(ValueError):
|
||||
sftp.validate({**base, **bad}, {"password": "pw"})
|
||||
with pytest.raises(ValueError):
|
||||
sftp.validate(base, {}) # neither password nor key
|
||||
with pytest.raises(ValueError):
|
||||
sftp.validate(base, {"password": "pw", "private_key": "x"}) # both
|
||||
with pytest.raises(ValueError):
|
||||
sftp.validate(base, {"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\nnot a key\n"})
|
||||
key = ed25519.Ed25519PrivateKey.generate().private_bytes(
|
||||
serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, serialization.NoEncryption()).decode()
|
||||
assert sftp.validate(base, {"private_key": key})[1] == {"private_key": key.strip() + "\n"}
|
||||
with pytest.raises(ValueError):
|
||||
sftp.validate({**base, "host_key": "SHA256:x"}, {"password": "pw"}) # a pin never comes with the form
|
||||
fclean, _ = ftp.validate({"host": "ftp.example.com", "username": "u", "directory": "bk"}, {"password": "pw"})
|
||||
assert (fclean["port"], fclean["tls"], fclean["verify_cert"], fclean["passive"]) == (21, True, True, True)
|
||||
with pytest.raises(ValueError):
|
||||
ftp.validate({"host": "ftp.example.com", "username": "u", "directory": "bk"}, {}) # no password
|
||||
|
||||
# Not pinned: Test shows the fingerprint, nothing else works, no connection is even opened
|
||||
body = {"name": "offsite", "type": "sftp", "params": base, "secrets": {"password": "pw"}}
|
||||
dest = client.post("/api/backup/destinations", json=body).json()
|
||||
assert dest["secrets"] == {"password": store.MASK} and "host_key" not in dest["params"]
|
||||
shown = engine.test_destination(dest["id"])
|
||||
assert shown["ok"] is False and shown["needs_trust"] is True and shown["key_changed"] is False
|
||||
fp = shown["fingerprint"]
|
||||
assert fp == destinations._ssh_fingerprint(FakeKey())
|
||||
rec = store.get_destination(dest["id"], with_secrets=True)
|
||||
unpinned = destinations.build_destination("sftp", rec["params"], rec["secrets"])
|
||||
n = len(FakeSSH.connects)
|
||||
for call in (lambda: unpinned.put(__file__, "ovpmon-backup_x_20260101T000000Z.ovpbak"), unpinned.list,
|
||||
lambda: unpinned.get("ovpmon-backup_x_20260101T000000Z.ovpbak", "/dev/null"),
|
||||
lambda: unpinned.delete("ovpmon-backup_x_20260101T000000Z.ovpbak")):
|
||||
with pytest.raises(destinations.DestinationError, match="not trusted"):
|
||||
call()
|
||||
assert len(FakeSSH.connects) == n
|
||||
|
||||
# Trust: only the fingerprint the administrator saw is accepted
|
||||
with pytest.raises(BackupError):
|
||||
engine.trust_host_key(dest["id"], "SHA256:" + "A" * 43)
|
||||
pinned = engine.trust_host_key(dest["id"], fp)
|
||||
assert pinned["params"]["host_key"] == fp and pinned["secrets"] == {"password": store.MASK}
|
||||
assert engine.test_destination(dest["id"])["ok"] is True
|
||||
rec = store.get_destination(dest["id"], with_secrets=True)
|
||||
d = destinations.build_destination("sftp", rec["params"], rec["secrets"])
|
||||
name = "ovpmon-backup_vpn_20261007T101500Z.ovpbak"
|
||||
d.put(__file__, name)
|
||||
assert f"ovpmon/daily/{name}" in FakeSFTP.files and not [f for f in FakeSFTP.files if f.endswith(".part")]
|
||||
FakeSFTP.files["ovpmon/daily/notes.txt"] = b"x"
|
||||
assert [o["name"] for o in d.list()] == [name] # only our package names
|
||||
out = os.path.join(os.path.dirname(env.prof), "got")
|
||||
d.get(name, out)
|
||||
assert open(out, "rb").read() == open(__file__, "rb").read()
|
||||
|
||||
# Pin and the form: an edit of other fields keeps the pin, a client cannot set it, a new host drops it
|
||||
edit = {**body, "params": {**base, "host_key": "SHA256:" + "B" * 43, "directory": "ovpmon/other"}, "secrets": {}}
|
||||
r = client.put(f"/api/backup/destinations/{dest['id']}", json=edit).json()
|
||||
assert r["params"]["host_key"] == fp and r["params"]["directory"] == "ovpmon/other"
|
||||
r = client.put(f"/api/backup/destinations/{dest['id']}", json={**edit, "params": {**base, "host": "other.example.com"}}).json()
|
||||
assert "host_key" not in r["params"]
|
||||
client.put(f"/api/backup/destinations/{dest['id']}", json={**edit, "params": base})
|
||||
engine.trust_host_key(dest["id"], fp)
|
||||
|
||||
# A different key from the server: connection refused, Test offers the new fingerprint (changed)
|
||||
FakeKey.blob = b"server-host-key-B"
|
||||
try:
|
||||
with pytest.raises(destinations.DestinationError, match="host key of the server changed"):
|
||||
d.list()
|
||||
changed = engine.test_destination(dest["id"])
|
||||
assert changed["needs_trust"] is True and changed["key_changed"] is True and changed["fingerprint"] != fp
|
||||
finally:
|
||||
FakeKey.blob = b"server-host-key-A"
|
||||
@@ -0,0 +1,10 @@
|
||||
from fastapi import HTTPException
|
||||
|
||||
from services import pki
|
||||
|
||||
|
||||
def forbid_during_restore():
|
||||
"""Dependency of the routes that change the PKI, the profiles or the settings: 409 while a
|
||||
backup restore replaces them."""
|
||||
if pki.is_restore_running():
|
||||
raise HTTPException(status_code=409, detail=pki.RESTORE_RUNNING_MSG)
|
||||
@@ -55,6 +55,9 @@
|
||||
<router-link to="/server" class="nav-link" active-class="active" title="Server Process">
|
||||
<i class="fas fa-terminal"></i> <span>Server Process</span>
|
||||
</router-link>
|
||||
<router-link to="/backup" class="nav-link" active-class="active" title="Backup and Restore">
|
||||
<i class="fas fa-box-archive"></i> <span>Backup and Restore</span>
|
||||
</router-link>
|
||||
|
||||
<!-- SECTION: ACCOUNT -->
|
||||
<div class="nav-section-header mt-3">ACCOUNT</div>
|
||||
|
||||
@@ -1999,4 +1999,40 @@ input[type="number"].config-input {
|
||||
.stats-grid .stat-item.full-width {
|
||||
grid-column: span 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* --- BACKUP AND RESTORE PAGE --- */
|
||||
.backup-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 24px;
|
||||
padding: 40px 0;
|
||||
background-color: var(--bg-body);
|
||||
}
|
||||
|
||||
/* Same card as the configuration pages, wider for the tables */
|
||||
.config-card.backup-card {
|
||||
width: 960px;
|
||||
}
|
||||
|
||||
.backup-steps {
|
||||
list-style: none;
|
||||
margin: 0 0 12px;
|
||||
padding: 0;
|
||||
color: var(--text-main);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.backup-steps li {
|
||||
padding: 3px 0;
|
||||
}
|
||||
|
||||
.backup-steps li i {
|
||||
width: 22px;
|
||||
}
|
||||
|
||||
.backup-result {
|
||||
padding: 6px 0;
|
||||
border-top: 1px solid var(--border-subtle);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<BaseModal id="confirmModal" :title="title" ref="modal">
|
||||
<template #body>
|
||||
<p class="text-main">{{ message }}</p>
|
||||
<p class="text-main" style="white-space: pre-line;">{{ message }}</p>
|
||||
</template>
|
||||
<template #footer>
|
||||
<button v-if="showCancel" type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
|
||||
|
||||
@@ -37,6 +37,11 @@ const routes = [
|
||||
name: 'ServerManagement',
|
||||
component: () => import('../views/ServerManagement.vue')
|
||||
},
|
||||
{
|
||||
path: '/backup',
|
||||
name: 'BackupRestore',
|
||||
component: () => import('../views/BackupRestore.vue')
|
||||
},
|
||||
{
|
||||
path: '/account',
|
||||
name: 'Account',
|
||||
|
||||
@@ -0,0 +1,803 @@
|
||||
<template>
|
||||
<div class="backup-page">
|
||||
|
||||
<!-- DESTINATIONS -->
|
||||
<div class="config-card backup-card">
|
||||
<div class="config-header">
|
||||
<h1>Backup Destinations</h1>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
|
||||
<span class="text-muted small">Where backup packages are stored. A backup goes to every selected destination.</span>
|
||||
<button type="button" class="btn-action btn-action-save btn-sm" @click="openAdd" :disabled="!settings.types.length">
|
||||
<i class="fas fa-plus"></i> Add destination
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover mb-0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Status</th>
|
||||
<th>Last result</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading">
|
||||
<td colspan="5" class="text-center py-4">
|
||||
<div class="spinner-border spinner-border-sm text-primary" role="status">
|
||||
<span class="visually-hidden">Loading...</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-else-if="destinations.length === 0">
|
||||
<td colspan="5" class="empty-state text-center py-4">
|
||||
<i class="fas fa-box-archive fa-2x mb-3 text-muted"></i>
|
||||
<p class="text-muted mb-0">No destinations yet. Add one to start making backups.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-for="d in destinations" :key="d.id">
|
||||
<td>
|
||||
<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">
|
||||
<span v-if="d.params.host_key" class="status-badge status-valid" :title="d.params.host_key">
|
||||
<i class="fas fa-fingerprint me-1"></i>Host key trusted
|
||||
</span>
|
||||
<span v-else class="status-badge status-warning">
|
||||
<i class="fas fa-triangle-exclamation me-1"></i>Host key not trusted: press Test and confirm it
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="plainFtp(d)" class="small mt-1">
|
||||
<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>
|
||||
<span :class="['status-badge', d.enabled ? 'status-valid' : 'status-secondary']">
|
||||
{{ d.enabled ? 'Enabled' : 'Disabled' }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<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' }}
|
||||
</span>
|
||||
<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>
|
||||
<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>
|
||||
<i v-else class="fas fa-plug"></i>
|
||||
</button>
|
||||
<button class="btn btn-sm btn-link text-warning p-0 me-2" title="Edit" @click="openEdit(d)" :disabled="isRunning">
|
||||
<i class="fas fa-pen"></i>
|
||||
</button>
|
||||
<button class="btn btn-sm btn-link text-danger p-0" title="Delete" @click="askDelete(d)" :disabled="isRunning">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- BACKUP -->
|
||||
<div class="config-card backup-card">
|
||||
<div class="config-header">
|
||||
<h1>Backup</h1>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-2">
|
||||
<div>
|
||||
<span v-if="settings.encryption_enabled" class="status-badge status-valid">
|
||||
<i class="fas fa-lock me-1"></i>Packages are encrypted
|
||||
</span>
|
||||
<span v-else class="status-badge status-warning">
|
||||
<i class="fas fa-triangle-exclamation me-1"></i>Packages are NOT encrypted
|
||||
</span>
|
||||
</div>
|
||||
<button type="button" class="btn-action btn-action-secondary btn-sm" @click="openPassphrase" :disabled="isRunning">
|
||||
<i class="fas fa-key"></i> {{ settings.encryption_enabled ? 'Change passphrase' : 'Set passphrase' }}
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-muted small mb-3">
|
||||
A package contains the CA private key, the certificates and the password hashes of the administrators.
|
||||
<template v-if="!settings.encryption_enabled">Remote destinations need an encryption passphrase; a local folder can be used without it.</template>
|
||||
<template v-else>Keep the passphrase: a package cannot be restored without it, and it is not stored in the package.</template>
|
||||
</p>
|
||||
|
||||
<div class="config-divider"></div>
|
||||
|
||||
<label class="config-label">Server name</label>
|
||||
<div class="config-input-group">
|
||||
<input type="text" class="config-input" v-model="serverNameInput" maxlength="63" autocomplete="off"
|
||||
placeholder="e.g. vpn-main" :disabled="isRunning" @keyup.enter="saveServerName">
|
||||
<button type="button" class="btn-action btn-action-secondary btn-sm" @click="saveServerName"
|
||||
:disabled="isRunning || saving || serverNameInput.trim() === settings.server_name">
|
||||
<i class="fas fa-floppy-disk"></i> Save
|
||||
</button>
|
||||
</div>
|
||||
<p class="text-muted small mt-2 mb-0">
|
||||
Package names will start with <strong class="text-main">{{ settings.effective_server_name }}</strong>
|
||||
<span v-if="settings.server_name_source === 'public_ip'">(the server address from the VPN settings: no name is set)</span>
|
||||
<span v-else-if="settings.server_name_source === 'hostname'">(the host name, in a container a random identifier: set a name)</span>.
|
||||
Letters, digits, '.' and '-'. Only packages with the same name in the same folder count for "copies to keep".
|
||||
The name is not part of a package: set it again on a new server.
|
||||
</p>
|
||||
|
||||
<div class="config-divider"></div>
|
||||
|
||||
<label class="config-label">Destinations for this backup</label>
|
||||
<div v-if="enabledDestinations.length === 0" class="text-muted small mb-3">
|
||||
No enabled destinations. Add or enable one above.
|
||||
</div>
|
||||
<div v-else class="mb-3">
|
||||
<div v-for="d in enabledDestinations" :key="d.id" class="form-check mb-1">
|
||||
<input class="form-check-input" type="checkbox" :id="'bk-dest-' + d.id" :value="d.id"
|
||||
v-model="selectedIds" :disabled="needsPassphrase(d)">
|
||||
<label class="form-check-label text-main" :for="'bk-dest-' + d.id">
|
||||
{{ d.name }} <span class="text-muted small">({{ typeLabel(d.type) }})</span>
|
||||
<span v-if="needsPassphrase(d)" class="text-muted small"> - set a passphrase first</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="btn-action-group justify-content-center mt-3">
|
||||
<button type="button" class="btn-action btn-action-primary" @click="runBackup"
|
||||
:disabled="isRunning || selectedIds.length === 0">
|
||||
<i v-if="isRunning && job.kind === 'backup'" class="fas fa-spinner fa-spin"></i>
|
||||
<i v-else class="fas fa-box-archive"></i>
|
||||
Backup now
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Progress and result of the last backup -->
|
||||
<div v-if="job.kind === 'backup' && job.state !== 'idle'" class="nested-box fade-in mt-4">
|
||||
<label class="nested-label d-flex justify-content-between">
|
||||
<span>{{ job.state === 'running' ? 'Backup in progress' : 'Last backup' }}</span>
|
||||
<span v-if="job.state !== 'running'" :class="['status-badge', jobBadge(job.state)]">{{ jobLabel(job.state) }}</span>
|
||||
</label>
|
||||
<ul class="backup-steps">
|
||||
<li v-for="s in job.stages" :key="s.name">
|
||||
<i :class="stageIcon(s.state)"></i> {{ stageLabel(s.name) }}
|
||||
</li>
|
||||
</ul>
|
||||
<div v-for="r in job.results" :key="r.destination_id" class="backup-result">
|
||||
<span :class="['status-badge', resultBadge(r.state)]">
|
||||
<i v-if="r.state === 'running'" class="fas fa-spinner fa-spin me-1"></i>{{ resultLabel(r.state) }}
|
||||
</span>
|
||||
<span class="fw-semibold ms-2" style="color: var(--text-heading);">{{ r.name }}</span>
|
||||
<div v-if="r.message" class="text-muted small ms-1 mt-1">{{ r.message }}</div>
|
||||
</div>
|
||||
<div v-if="job.state !== 'running' && job.message" class="text-muted small mt-2">{{ job.message }}</div>
|
||||
</div>
|
||||
|
||||
<!-- History -->
|
||||
<div v-if="history.length" class="mt-4">
|
||||
<label class="config-label">History</label>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover mb-0">
|
||||
<thead>
|
||||
<tr><th>Time</th><th>Action</th><th>Result</th><th>Details</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="h in history" :key="h.id">
|
||||
<td>{{ formatTime(h.started_at) }}</td>
|
||||
<td class="text-capitalize">{{ h.kind }}</td>
|
||||
<td><span :class="['status-badge', jobBadge(h.state)]">{{ jobLabel(h.state) }}</span></td>
|
||||
<td class="small text-muted">{{ h.message }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- RESTORE -->
|
||||
<div class="config-card backup-card">
|
||||
<div class="config-header">
|
||||
<h1>Restore</h1>
|
||||
</div>
|
||||
|
||||
<p class="text-muted small mb-3">
|
||||
Restores the databases, the PKI and the client profiles from a package, also one made on another server.
|
||||
The current state is saved to a local safety copy first.
|
||||
</p>
|
||||
|
||||
<div class="config-row">
|
||||
<div class="config-col">
|
||||
<label class="config-label">Source</label>
|
||||
<div class="select-container">
|
||||
<select class="config-select" v-model="restore.sourceId" :disabled="isRunning">
|
||||
<option :value="null" disabled>Select a destination</option>
|
||||
<option v-for="d in destinations" :key="d.id" :value="d.id">{{ d.name }} ({{ typeLabel(d.type) }})</option>
|
||||
</select>
|
||||
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
|
||||
</div>
|
||||
<div v-if="restore.checking" class="text-muted small mt-2">
|
||||
<i class="fas fa-spinner fa-spin me-1"></i>Checking the source...
|
||||
</div>
|
||||
<div v-else-if="restore.sourceError" class="mt-2">
|
||||
<span class="status-badge status-expired"><i class="fas fa-times-circle me-1"></i>Source check failed</span>
|
||||
<div class="text-muted small mt-1">{{ restore.sourceError }}</div>
|
||||
</div>
|
||||
<div v-else-if="restore.sourceId !== null" class="mt-2">
|
||||
<span class="status-badge status-valid"><i class="fas fa-check-circle me-1"></i>Source reachable</span>
|
||||
<span class="text-muted small ms-2">{{ restore.packages.length }} package(s) found</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="config-row">
|
||||
<div class="config-col">
|
||||
<label class="config-label">Package (newest first)</label>
|
||||
<div class="select-container">
|
||||
<select class="config-select" v-model="restore.packageName"
|
||||
:disabled="isRunning || restore.checking || restore.packages.length === 0">
|
||||
<option :value="''" disabled>{{ restore.packages.length ? 'Select a package' : 'No packages' }}</option>
|
||||
<option v-for="p in restore.packages" :key="p.name" :value="p.name">{{ packageLabel(p) }}</option>
|
||||
</select>
|
||||
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedPackage && selectedPackage.encrypted" class="config-row">
|
||||
<div class="config-col">
|
||||
<label class="config-label">Package passphrase</label>
|
||||
<input type="password" class="config-input" v-model="restore.passphrase" autocomplete="off"
|
||||
placeholder="Passphrase used when the package was made">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="btn-action-group justify-content-center">
|
||||
<button type="button" class="btn-action btn-action-danger" @click="askRestore" :disabled="!canRestore">
|
||||
<i v-if="isRunning && job.kind === 'restore'" class="fas fa-spinner fa-spin"></i>
|
||||
<i v-else class="fas fa-rotate-left"></i>
|
||||
Restore
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Progress and result of the restore -->
|
||||
<div v-if="job.kind === 'restore' && job.state !== 'idle'" class="nested-box fade-in mt-4">
|
||||
<label class="nested-label d-flex justify-content-between">
|
||||
<span>{{ job.state === 'running' ? 'Restore in progress. Do not close the server.' : 'Last restore' }}</span>
|
||||
<span v-if="job.state !== 'running'" :class="['status-badge', jobBadge(job.state)]">{{ jobLabel(job.state) }}</span>
|
||||
</label>
|
||||
<ul class="backup-steps">
|
||||
<li v-for="s in job.stages" :key="s.name">
|
||||
<i :class="stageIcon(s.state)"></i> {{ stageLabel(s.name) }}
|
||||
</li>
|
||||
</ul>
|
||||
<div v-if="job.state !== 'running' && job.message" class="small mt-2" :class="job.state === 'done' ? 'text-main' : 'text-danger'">
|
||||
{{ job.message }}
|
||||
</div>
|
||||
<div v-for="(w, i) in job.warnings" :key="i" class="small mt-1">
|
||||
<span class="status-badge status-warning"><i class="fas fa-triangle-exclamation me-1"></i>{{ w }}</span>
|
||||
</div>
|
||||
<div v-if="restoreFinishedHere && job.relogin" class="mt-3">
|
||||
<p class="text-main small mb-2">
|
||||
The accounts now come from the package. Log in again with the account of the restored server.
|
||||
Check the server address in the VPN settings if the package comes from another server.
|
||||
</p>
|
||||
<button type="button" class="btn-action btn-action-primary btn-sm" @click="logInAgain">
|
||||
<i class="fas fa-sign-in-alt"></i> Log in again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Add / edit destination -->
|
||||
<BaseModal id="destinationModal" :title="destForm.id ? 'Edit Destination' : 'Add Destination'" ref="destModal">
|
||||
<template #body>
|
||||
<form @submit.prevent="saveDestination" id="destForm" autocomplete="off">
|
||||
<div class="mb-3">
|
||||
<label class="form-label small fw-bold text-muted text-uppercase">Name</label>
|
||||
<input type="text" class="form-control" v-model="destForm.name" maxlength="64" required placeholder="e.g. offsite-bucket">
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label class="form-label small fw-bold text-muted text-uppercase">Type</label>
|
||||
<div class="select-container">
|
||||
<select class="config-select" v-model="destForm.type" @change="onTypeChange">
|
||||
<option v-for="t in settings.types" :key="t.id" :value="t.id">{{ t.label }}</option>
|
||||
</select>
|
||||
<div class="select-arrow"><i class="fas fa-chevron-down"></i></div>
|
||||
</div>
|
||||
<div v-if="currentType && currentType.remote && !settings.encryption_enabled" class="form-text mt-2 small text-warning">
|
||||
<i class="fas fa-triangle-exclamation me-1"></i>Backups to this type need an encryption passphrase.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-for="f in currentFields" :key="f.name" class="mb-3">
|
||||
<template v-if="f.kind === 'bool'">
|
||||
<label class="form-label small fw-bold text-muted text-uppercase d-block">{{ f.label }}</label>
|
||||
<div class="toggle-wrapper">
|
||||
<label class="toggle-switch">
|
||||
<input type="checkbox" v-model="destForm.params[f.name]">
|
||||
<span class="toggle-slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="f.kind === 'secret'">
|
||||
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||
<input type="password" class="form-control" v-model="destForm.secrets[f.name]"
|
||||
autocomplete="new-password"
|
||||
:placeholder="secretIsSet(f.name) ? '(unchanged)' : ''">
|
||||
<div v-if="f.hint" class="form-text mt-1 text-muted small">{{ f.hint }}</div>
|
||||
</template>
|
||||
<template v-else-if="f.kind === 'secret_multiline'">
|
||||
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||
<textarea class="form-control" rows="5" v-model="destForm.secrets[f.name]" spellcheck="false"
|
||||
autocomplete="off" style="font-family: monospace; font-size: 12px;"
|
||||
:placeholder="secretIsSet(f.name) ? '(unchanged: paste a new key to replace it)' : '-----BEGIN OPENSSH PRIVATE KEY-----'"></textarea>
|
||||
</template>
|
||||
<template v-else-if="f.kind === 'number'">
|
||||
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||
<input type="number" class="form-control" v-model.number="destForm.params[f.name]" min="1" max="65535">
|
||||
</template>
|
||||
<template v-else>
|
||||
<label class="form-label small fw-bold text-muted text-uppercase">{{ f.label }}</label>
|
||||
<input type="text" class="form-control" v-model="destForm.params[f.name]" :placeholder="f.default || ''">
|
||||
<div v-if="f.hint" class="form-text mt-1 text-muted small">{{ f.hint }}</div>
|
||||
</template>
|
||||
<div v-if="f.warning && destForm.params[f.name] === f.warn_if" class="form-text mt-2 small text-warning">
|
||||
<i class="fas fa-triangle-exclamation me-1"></i>{{ f.warning }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="currentType && currentType.pins_host_key" class="mb-3">
|
||||
<label class="form-label small fw-bold text-muted text-uppercase">Server host key (SHA-256)</label>
|
||||
<div v-if="destForm.params.host_key" class="small text-main" style="word-break: break-all;">
|
||||
{{ destForm.params.host_key }}
|
||||
</div>
|
||||
<div v-else class="form-text small text-warning">
|
||||
<i class="fas fa-triangle-exclamation me-1"></i>Not trusted yet. Save the destination, press Test and confirm the fingerprint. Nothing is copied before that.
|
||||
</div>
|
||||
<div class="form-text mt-1 text-muted small">Changing the host or the port clears the trusted key.</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label small fw-bold text-muted text-uppercase">Copies to keep</label>
|
||||
<input type="number" class="form-control" v-model.number="destForm.retention_count" min="1" max="1000">
|
||||
<div class="form-text mt-1 text-muted small">The oldest packages of this server beyond this number are deleted after a successful backup.</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-1 d-flex align-items-center">
|
||||
<div class="toggle-wrapper me-2">
|
||||
<label class="toggle-switch">
|
||||
<input type="checkbox" v-model="destForm.enabled" id="destEnabled">
|
||||
<span class="toggle-slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<label class="user-select-none text-muted" for="destEnabled" style="cursor: pointer;">Enabled</label>
|
||||
</div>
|
||||
</form>
|
||||
</template>
|
||||
<template #footer>
|
||||
<button type="button" class="btn-action btn-action-secondary" @click="destModal.hide()">Cancel</button>
|
||||
<button type="submit" form="destForm" class="btn-action btn-action-save" :disabled="saving">
|
||||
<span v-if="saving" class="spinner-border spinner-border-sm me-2"></span>
|
||||
{{ destForm.id ? 'Save' : 'Add' }}
|
||||
</button>
|
||||
</template>
|
||||
</BaseModal>
|
||||
|
||||
<!-- Passphrase -->
|
||||
<BaseModal id="passphraseModal" title="Encryption Passphrase" ref="passModal">
|
||||
<template #body>
|
||||
<form @submit.prevent="savePassphrase" id="passForm" autocomplete="off">
|
||||
<p class="text-main small">
|
||||
Packages made after this change are encrypted with the new passphrase. Older packages keep the
|
||||
passphrase they were made with: keep it as long as you need them.
|
||||
</p>
|
||||
<div class="mb-3">
|
||||
<label class="form-label small fw-bold text-muted text-uppercase">New passphrase</label>
|
||||
<input type="password" class="form-control" v-model="passForm.value" autocomplete="new-password"
|
||||
placeholder="Min. 8 characters" required>
|
||||
</div>
|
||||
<div class="mb-2">
|
||||
<label class="form-label small fw-bold text-muted text-uppercase">Confirm passphrase</label>
|
||||
<input type="password" class="form-control" v-model="passForm.confirm" autocomplete="new-password" required>
|
||||
</div>
|
||||
</form>
|
||||
</template>
|
||||
<template #footer>
|
||||
<button v-if="settings.encryption_enabled" type="button" class="btn-action btn-action-danger me-auto" @click="removePassphrase" :disabled="saving">
|
||||
Remove passphrase
|
||||
</button>
|
||||
<button type="button" class="btn-action btn-action-secondary" @click="passModal.hide()">Cancel</button>
|
||||
<button type="submit" form="passForm" class="btn-action btn-action-save" :disabled="saving">
|
||||
<span v-if="saving" class="spinner-border spinner-border-sm me-2"></span>
|
||||
Save
|
||||
</button>
|
||||
</template>
|
||||
</BaseModal>
|
||||
|
||||
<ConfirmModal ref="deleteModal" @confirm="confirmDelete" />
|
||||
<ConfirmModal ref="restoreModal" @confirm="confirmRestore" />
|
||||
<ConfirmModal ref="trustModal" @confirm="confirmTrust" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, reactive, computed, watch, onMounted, onUnmounted } from 'vue';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import { useToast } from '../composables/useToast';
|
||||
import { useFormatters } from '../composables/useFormatters';
|
||||
import BaseModal from '../components/BaseModal.vue';
|
||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||
|
||||
const { profilesApiClient } = useApi();
|
||||
const toast = useToast();
|
||||
const { formatBytes } = useFormatters();
|
||||
|
||||
const loading = ref(true);
|
||||
const saving = ref(false);
|
||||
const testingId = ref(null);
|
||||
const settings = reactive({ encryption_enabled: false, default_retention: 14, local_root: '', types: [],
|
||||
server_name: '', effective_server_name: '', server_name_source: 'hostname' });
|
||||
const serverNameInput = ref('');
|
||||
const destinations = ref([]);
|
||||
const history = ref([]);
|
||||
const selectedIds = ref([]);
|
||||
const job = reactive({ kind: null, state: 'idle', stages: [], results: [], warnings: [], message: null, relogin: false });
|
||||
const restoreFinishedHere = ref(false);
|
||||
|
||||
const destModal = ref(null);
|
||||
const passModal = ref(null);
|
||||
const deleteModal = ref(null);
|
||||
const restoreModal = ref(null);
|
||||
const trustModal = ref(null);
|
||||
|
||||
const destForm = reactive({ id: null, name: '', type: 'local', enabled: true, retention_count: 14, params: {}, secrets: {} });
|
||||
const existingSecrets = ref({});
|
||||
const passForm = reactive({ value: '', confirm: '' });
|
||||
const restore = reactive({ sourceId: null, checking: false, sourceError: '', packages: [], packageName: '', passphrase: '' });
|
||||
|
||||
let pollTimer = null;
|
||||
|
||||
const errText = (e) => e.response?.data?.detail || e.message;
|
||||
const isRunning = computed(() => job.state === 'running');
|
||||
const enabledDestinations = computed(() => destinations.value.filter((d) => d.enabled));
|
||||
const typeInfo = (id) => settings.types.find((t) => t.id === id);
|
||||
const typeLabel = (id) => typeInfo(id)?.label || id;
|
||||
const currentType = computed(() => typeInfo(destForm.type));
|
||||
const currentFields = computed(() => currentType.value?.fields || []);
|
||||
const needsPassphrase = (d) => !!typeInfo(d.type)?.remote && !settings.encryption_enabled;
|
||||
const selectedPackage = computed(() => restore.packages.find((p) => p.name === restore.packageName) || null);
|
||||
const canRestore = computed(() => !isRunning.value && !!selectedPackage.value
|
||||
&& (!selectedPackage.value.encrypted || restore.passphrase.length > 0));
|
||||
|
||||
// --- formatting ---
|
||||
const formatTime = (iso) => {
|
||||
if (!iso) return '';
|
||||
const d = new Date(iso);
|
||||
return isNaN(d) ? iso : d.toLocaleString();
|
||||
};
|
||||
// Package time: UTC (as in the file name) and the browser's local time
|
||||
const utcTime = (iso) => (iso ? iso.replace('T', ' ').replace(/(\.\d+)?Z$/, '') + ' UTC' : '');
|
||||
const packageLabel = (p) => `${p.server_name} - ${utcTime(p.created_at)} (${formatTime(p.created_at)} local) - ${formatBytes(p.size)} - ${p.encrypted ? 'encrypted' : 'not encrypted'}`;
|
||||
const destinationSummary = (d) => {
|
||||
const p = d.params || {};
|
||||
if (d.type === 'local') return `${settings.local_root || ''}/${p.folder || ''}`.replace('//', '/');
|
||||
if (d.type === 's3') return `${p.bucket}${p.prefix ? '/' + p.prefix : ''} @ ${p.endpoint}`;
|
||||
if (d.type === 'sftp') return `sftp://${p.username}@${p.host}:${p.port}/${p.directory}`;
|
||||
if (d.type === 'ftp') return `${p.tls ? 'ftps' : 'ftp'}://${p.username}@${p.host}:${p.port}/${p.directory}`;
|
||||
return '';
|
||||
};
|
||||
const plainFtp = (d) => d.type === 'ftp' && d.params && d.params.tls === false;
|
||||
const STAGES = {
|
||||
package: 'Create package', encrypt: 'Encrypt', upload: 'Send to destinations',
|
||||
download: 'Download package', decrypt: 'Decrypt', verify: 'Verify and unpack',
|
||||
prepare: 'Check and migrate databases', safety_backup: 'Save current state (safety copy)',
|
||||
stop_openvpn: 'Stop OpenVPN if running', replace: 'Replace data', finalize: 'Regenerate server config, start OpenVPN'
|
||||
};
|
||||
const stageLabel = (n) => STAGES[n] || n;
|
||||
const stageIcon = (s) => ({
|
||||
pending: 'far fa-circle text-muted', running: 'fas fa-spinner fa-spin text-primary',
|
||||
done: 'fas fa-check-circle text-success', error: 'fas fa-times-circle text-danger'
|
||||
}[s] || 'far fa-circle text-muted');
|
||||
const jobBadge = (s) => ({ done: 'status-valid', partial: 'status-warning', error: 'status-expired', interrupted: 'status-expired', running: 'status-warning' }[s] || 'status-secondary');
|
||||
const jobLabel = (s) => ({ done: 'Success', partial: 'Partial', error: 'Failed', interrupted: 'Interrupted', running: 'Running' }[s] || s);
|
||||
const resultBadge = (s) => ({ ok: 'status-valid', error: 'status-expired', running: 'status-warning' }[s] || 'status-secondary');
|
||||
const resultLabel = (s) => ({ ok: 'Stored', error: 'Failed', running: 'Sending', pending: 'Waiting', skipped: 'Skipped' }[s] || s);
|
||||
|
||||
// --- loading ---
|
||||
const loadSettings = async () => {
|
||||
const res = await profilesApiClient.get('/backup/settings');
|
||||
Object.assign(settings, res.data);
|
||||
serverNameInput.value = settings.server_name || '';
|
||||
};
|
||||
const loadDestinations = async () => {
|
||||
const res = await profilesApiClient.get('/backup/destinations');
|
||||
destinations.value = res.data;
|
||||
// Keep the choice of the user, drop what no longer exists or is not usable
|
||||
const usable = new Set(enabledDestinations.value.filter((d) => !needsPassphrase(d)).map((d) => d.id));
|
||||
selectedIds.value = selectedIds.value.filter((id) => usable.has(id));
|
||||
};
|
||||
const loadHistory = async () => {
|
||||
const res = await profilesApiClient.get('/backup/history', { params: { limit: 10 } });
|
||||
history.value = res.data;
|
||||
};
|
||||
const selectAllUsable = () => {
|
||||
selectedIds.value = enabledDestinations.value.filter((d) => !needsPassphrase(d)).map((d) => d.id);
|
||||
};
|
||||
|
||||
const stopPolling = () => {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
|
||||
};
|
||||
const startPolling = () => {
|
||||
if (!pollTimer) pollTimer = setInterval(loadStatus, 2000);
|
||||
};
|
||||
const loadStatus = async () => {
|
||||
const wasRunning = job.state === 'running';
|
||||
try {
|
||||
const res = await profilesApiClient.get('/backup/status');
|
||||
Object.assign(job, res.data);
|
||||
} catch (e) {
|
||||
return; // keep polling, the next tick may succeed
|
||||
}
|
||||
if (job.state === 'running') {
|
||||
startPolling();
|
||||
return;
|
||||
}
|
||||
stopPolling();
|
||||
if (wasRunning) await onJobFinished();
|
||||
};
|
||||
|
||||
const onJobFinished = async () => {
|
||||
if (job.kind === 'restore') {
|
||||
restoreFinishedHere.value = true;
|
||||
toast.show(job.message || 'Restore finished', job.state === 'done' ? 'success' : 'error');
|
||||
} else {
|
||||
toast.show(job.message || 'Backup finished', job.state === 'done' ? 'success' : (job.state === 'partial' ? 'warning' : 'error'));
|
||||
}
|
||||
try {
|
||||
await Promise.all([loadDestinations(), loadHistory()]);
|
||||
} catch (e) { /* the session may be gone after a restore: the interceptor redirects */ }
|
||||
if (job.kind === 'restore') await checkSource();
|
||||
};
|
||||
|
||||
// --- destinations ---
|
||||
const defaultsFor = (typeId) => {
|
||||
const params = {};
|
||||
(typeInfo(typeId)?.fields || []).forEach((f) => {
|
||||
if (!f.kind.startsWith('secret')) params[f.name] = f.default ?? (f.kind === 'bool' ? false : '');
|
||||
});
|
||||
return params;
|
||||
};
|
||||
const secretIsSet = (name) => !!existingSecrets.value[name];
|
||||
|
||||
const openAdd = () => {
|
||||
const type = settings.types[0]?.id || 'local';
|
||||
Object.assign(destForm, { id: null, name: '', type, enabled: true, retention_count: settings.default_retention,
|
||||
params: defaultsFor(type), secrets: {} });
|
||||
existingSecrets.value = {};
|
||||
destModal.value.show();
|
||||
};
|
||||
const openEdit = (d) => {
|
||||
Object.assign(destForm, { id: d.id, name: d.name, type: d.type, enabled: d.enabled,
|
||||
retention_count: d.retention_count, params: { ...defaultsFor(d.type), ...d.params }, secrets: {} });
|
||||
existingSecrets.value = { ...d.secrets };
|
||||
destModal.value.show();
|
||||
};
|
||||
const onTypeChange = () => {
|
||||
destForm.params = defaultsFor(destForm.type);
|
||||
destForm.secrets = {};
|
||||
existingSecrets.value = {};
|
||||
};
|
||||
const saveDestination = async () => {
|
||||
saving.value = true;
|
||||
const body = { name: destForm.name, type: destForm.type, enabled: destForm.enabled,
|
||||
retention_count: destForm.retention_count, params: destForm.params, secrets: destForm.secrets };
|
||||
try {
|
||||
if (destForm.id) await profilesApiClient.put(`/backup/destinations/${destForm.id}`, body);
|
||||
else await profilesApiClient.post('/backup/destinations', body);
|
||||
toast.show('Destination saved.', 'success');
|
||||
destModal.value.hide();
|
||||
await loadDestinations();
|
||||
if (!destForm.id) selectAllUsable();
|
||||
} catch (e) {
|
||||
toast.show(errText(e), 'error');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
const testDestination = async (d) => {
|
||||
testingId.value = d.id;
|
||||
try {
|
||||
const res = await profilesApiClient.post(`/backup/destinations/${d.id}/test`);
|
||||
if (res.data.needs_trust) askTrust(d, res.data);
|
||||
else toast.show(res.data.message, res.data.ok ? 'success' : 'error');
|
||||
await loadDestinations();
|
||||
} catch (e) {
|
||||
toast.show(errText(e), 'error');
|
||||
} finally {
|
||||
testingId.value = null;
|
||||
}
|
||||
};
|
||||
// SFTP: the server shows its host key; the administrator compares the fingerprint and trusts it
|
||||
const askTrust = (d, r) => {
|
||||
trustModal.value.open({
|
||||
title: r.key_changed ? 'Host Key Changed' : 'Trust This Server?',
|
||||
message:
|
||||
(r.key_changed
|
||||
? 'WARNING: the server now shows a different host key than the trusted one. This happens after a reinstall of the server, but also during an attack.\n\n'
|
||||
: `The server of "${d.name}" showed this host key. Compare it with the fingerprint you know (ssh-keygen -lf on the server) before you trust it.\n\n`) +
|
||||
`Type: ${r.key_type}\nSHA-256: ${r.fingerprint}\n\n` +
|
||||
'Packages are sent only to a server with exactly this key.',
|
||||
confirmText: r.key_changed ? 'Trust the new key' : 'Trust',
|
||||
confirmBtnClass: r.key_changed ? 'btn-action-danger' : 'btn-action-primary',
|
||||
data: { id: d.id, name: d.name, fingerprint: r.fingerprint }
|
||||
});
|
||||
};
|
||||
const confirmTrust = async (t) => {
|
||||
try {
|
||||
await profilesApiClient.post(`/backup/destinations/${t.id}/trust-host-key`, { fingerprint: t.fingerprint });
|
||||
toast.show(`Host key of ${t.name} trusted. Press Test to check the connection.`, 'success');
|
||||
await loadDestinations();
|
||||
} catch (e) {
|
||||
toast.show(errText(e), 'error');
|
||||
}
|
||||
};
|
||||
const askDelete = (d) => {
|
||||
deleteModal.value.open({
|
||||
title: 'Delete Destination?',
|
||||
message: `Delete "${d.name}"? Packages already stored there are not deleted.`,
|
||||
confirmText: 'Yes, Delete',
|
||||
data: d
|
||||
});
|
||||
};
|
||||
const confirmDelete = async (d) => {
|
||||
try {
|
||||
await profilesApiClient.delete(`/backup/destinations/${d.id}`);
|
||||
toast.show(`${d.name} deleted.`, 'success');
|
||||
if (restore.sourceId === d.id) restore.sourceId = null;
|
||||
await loadDestinations();
|
||||
} catch (e) {
|
||||
toast.show(errText(e), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
// --- passphrase ---
|
||||
const openPassphrase = () => {
|
||||
passForm.value = '';
|
||||
passForm.confirm = '';
|
||||
passModal.value.show();
|
||||
};
|
||||
const savePassphrase = async () => {
|
||||
if (passForm.value !== passForm.confirm) {
|
||||
toast.show('Passphrases do not match.', 'error');
|
||||
return;
|
||||
}
|
||||
await updateSettings({ passphrase: passForm.value }, 'Passphrase saved.');
|
||||
};
|
||||
const removePassphrase = async () => {
|
||||
await updateSettings({ clear_passphrase: true }, 'Passphrase removed. New packages are not encrypted.');
|
||||
};
|
||||
const saveServerName = async () => {
|
||||
const value = serverNameInput.value.trim();
|
||||
if (value === (settings.server_name || '')) return;
|
||||
saving.value = true;
|
||||
try {
|
||||
const res = await profilesApiClient.put('/backup/settings', { server_name: value });
|
||||
Object.assign(settings, res.data);
|
||||
serverNameInput.value = settings.server_name || '';
|
||||
toast.show(value ? 'Server name saved.' : 'Server name cleared.', 'success');
|
||||
} catch (e) {
|
||||
toast.show(errText(e), 'error');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
const updateSettings = async (body, okText) => {
|
||||
saving.value = true;
|
||||
try {
|
||||
const res = await profilesApiClient.put('/backup/settings', body);
|
||||
Object.assign(settings, res.data);
|
||||
toast.show(okText, 'success');
|
||||
passModal.value.hide();
|
||||
await loadDestinations();
|
||||
} catch (e) {
|
||||
toast.show(errText(e), 'error');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// --- backup ---
|
||||
const runBackup = async () => {
|
||||
try {
|
||||
await profilesApiClient.post('/backup/run', { destination_ids: selectedIds.value });
|
||||
restoreFinishedHere.value = false;
|
||||
job.kind = 'backup';
|
||||
job.state = 'running';
|
||||
await loadStatus();
|
||||
startPolling();
|
||||
} catch (e) {
|
||||
if (e.response?.status === 409) await loadStatus();
|
||||
toast.show(errText(e), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
// --- restore ---
|
||||
const checkSource = async () => {
|
||||
restore.packages = [];
|
||||
restore.packageName = '';
|
||||
restore.passphrase = '';
|
||||
restore.sourceError = '';
|
||||
if (restore.sourceId === null) return;
|
||||
restore.checking = true;
|
||||
try {
|
||||
const res = await profilesApiClient.get(`/backup/destinations/${restore.sourceId}/packages`);
|
||||
restore.packages = res.data.packages;
|
||||
} catch (e) {
|
||||
restore.sourceError = errText(e);
|
||||
} finally {
|
||||
restore.checking = false;
|
||||
}
|
||||
};
|
||||
watch(() => restore.sourceId, checkSource);
|
||||
|
||||
const askRestore = () => {
|
||||
const p = selectedPackage.value;
|
||||
restoreModal.value.open({
|
||||
title: 'Restore from Backup?',
|
||||
message:
|
||||
`Package: ${p.server_name}, ${utcTime(p.created_at)} (${formatTime(p.created_at)} local)\n\n` +
|
||||
'This replaces:\n' +
|
||||
'- the monitoring database (statistics, administrator accounts, 2FA),\n' +
|
||||
'- the profiler database and the server settings,\n' +
|
||||
'- the PKI (CA, keys, certificates) and the client profiles.\n\n' +
|
||||
'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: p
|
||||
});
|
||||
};
|
||||
const confirmRestore = async (p) => {
|
||||
try {
|
||||
await profilesApiClient.post('/backup/restore', {
|
||||
destination_id: restore.sourceId,
|
||||
package: p.name,
|
||||
passphrase: p.encrypted ? restore.passphrase : null
|
||||
});
|
||||
restoreFinishedHere.value = false;
|
||||
restore.passphrase = '';
|
||||
job.kind = 'restore';
|
||||
job.state = 'running';
|
||||
await loadStatus();
|
||||
startPolling();
|
||||
} catch (e) {
|
||||
toast.show(errText(e), 'error');
|
||||
}
|
||||
};
|
||||
const logInAgain = () => {
|
||||
localStorage.removeItem('ovpmon_token');
|
||||
localStorage.removeItem('ovpmon_user');
|
||||
window.location.href = '/login';
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await loadSettings();
|
||||
await loadDestinations();
|
||||
selectAllUsable();
|
||||
await Promise.all([loadHistory(), loadStatus()]);
|
||||
} catch (e) {
|
||||
toast.show(`Failed to load backup settings: ${errText(e)}`, 'error');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
onUnmounted(stopPolling);
|
||||
</script>
|
||||
@@ -0,0 +1,51 @@
|
||||
# Резервное копирование и восстановление: сводка, проход 1 из 3 (2026-10-07)
|
||||
|
||||
План: [2026-10-07_Backup_Restore_PLAN.md](2026-10-07_Backup_Restore_PLAN.md). Руководство: [Backup and Restore](../Profiler_Management/Backup_Restore.md).
|
||||
|
||||
Проход 1 по плану: формат пакета, шифрование, безопасная распаковка, хранилище настроек, назначения **Local и S3 (`minio`)**, все маршруты API, движок восстановления, весь UI. FTP, SFTP, SMB, расписание: позже.
|
||||
|
||||
## Что сделано
|
||||
|
||||
**Backend (`APP_PROFILER`)**
|
||||
- `services/backup/package.py`: имя пакета и разбор регулярным выражением; онлайн-снимок обеих БД (`Connection.backup`, одиночный файл без `-wal`); сборка tar.gz с `manifest.json` (формат, версии схем, SHA-256, среда, хост); безопасная распаковка (белый список верхних имён, отказ для абсолютных путей, `..`, ссылок, устройств, дублей, лимиты размера и числа записей); сверка манифеста с содержимым.
|
||||
- `services/backup/crypto.py`: AES-256-GCM по блокам 1 МиБ, ключ из фразы через scrypt (N=2^15), заголовок с солью и параметрами, заголовок и признак последнего блока входят в AAD (обрезка и подмена обнаруживаются); границы параметров из заголовка.
|
||||
- `services/backup/destinations.py`: общий интерфейс `test/put/list/get/delete`, реестр типов (расширение для ftp/sftp/smb: новый класс и запись в `DESTINATION_TYPES`; API принимает только реализованные типы). `local`: подпапка внутри `OVPMON_BACKUP_LOCAL_ROOT`, отказ при выходе из корня и символических ссылках, запись через временный файл. `s3`: библиотека `minio`, endpoint/TLS/регион/bucket/prefix/ключи, проверка форматов, таймауты.
|
||||
- `services/backup/store.py`: отдельный файл `ovpmon_backup.db` рядом с БД профилировщика (настройки, назначения, история, таблица версии схемы, создаётся при старте); секреты назначений и парольная фраза шифруются Fernet-ключом из HKDF от ключа JWT, API отдаёт маску.
|
||||
- `services/backup/engine.py`: одна фоновая задача на сервис (409 иначе), этапы и результат по каждому назначению, сбой одного назначения не останавливает остальные; ротация по `retention_count` (только пакеты нашего шаблона **этого хоста**); восстановление по п. 4 плана; история.
|
||||
- `routers/backup.py`: маршруты п. 5 плана, все под `verify_token`; `utils/guards.py` и `pki.set_restore_running`: во время восстановления изменяющие PKI, профили, настройки и процесс OpenVPN запросы получают 409.
|
||||
- `main.py`: создание хранилища при старте (сбой не останавливает управление VPN), регистрация роутера.
|
||||
|
||||
**Миграции монитора при восстановлении (решение).** Миграции БД мониторинга живут в `APP_CORE`, из процесса профилировщика их импортировать нельзя (отдельные venv, в образе профилировщика варианта B `APP_CORE` нет). Выбрано: миграции запускаются **на распакованных копиях до замены** (профилировщик: `migrations.run` в процессе; монитор: `python migrate.py --db <копия>` из каталога `APP_CORE`, найденного рядом с `APP_PROFILER` или по `OVPMON_CORE_DIR`, интерпретатор из `APP_CORE/venv`, иначе текущий). Так в рабочую систему попадает уже мигрированная БД, а при ошибке ничего не меняется. Если код миграций недоступен, пакет принимается только при **равной** версии схемы монитора, иначе отказ с понятным сообщением (в образе профилировщика варианта B код миграций добавлен позже: см. [Fixes](2026-10-07_Backup_Restore_Fixes.md), R3). Причина: Core применяет миграции только при своём старте, а восстановление его не перезапускает.
|
||||
|
||||
**UI (`APP_UI`)**: `views/BackupRestore.vue`, маршрут `/backup`, пункт Backup and Restore в MANAGEMENT; таблица назначений и модальное окно (поля типов приходят из `GET /backup/settings`), панель Backup (статус шифрования, флажки, Backup now, прогресс по назначениям, история), панель Restore (источник, автопроверка, пакеты новые сверху, фраза, красная кнопка, подтверждение с перечнем последствий, прогресс, вход заново); опрос статуса раз в 2 с. Небольшой блок стилей в `main.css`; `ConfirmModal` понимает переводы строк. Собранный UI `deploy/ui-dist` обновлён через `build-ui.sh --docker --publish`, `check-ui.sh`: актуален.
|
||||
|
||||
**Развёртывание**: `cryptography` и `minio` в `requirements.txt`; том `ovp_backups` на `/app/backups` и `OVPMON_BACKUP_LOCAL_ROOT=/app/backups` в обоих compose-файлах (в `deploy/docker/lib.sh` `VOLUMES` не менялся); каталог в образах. Системные службы: unit systemd разрешает запись в `/var/lib/ovpmon`, каталог `backups` создаётся службой, установщик не менялся.
|
||||
|
||||
**Документация**: `Profiler_Management/Backup_Restore.md`, `Profiler_Management/API_Reference.md`, `UI/Architecture.md`, `General/Overview.md`, `General/Configuration.md`, `Deployment/Containers/Reference.md`, `Deployment/System_Services/Reference.md`, `README.md`, `DOCS/README.md`, `DOCS/Changes/README.md`.
|
||||
|
||||
## Проверено
|
||||
|
||||
- Автотесты `APP_PROFILER/test_backup.py` (5 шт., без сети и без S3): круг пакета с шифрованием и неверной фразой; безопасная распаковка (`../`, абсолютный путь, ссылка, чужое имя, лишний файл в `db/`), пакет с более новой схемой и неизвестным форматом; два назначения (рабочее Local и падающая заглушка), результат по каждому, ротация, восстановление через движок с проверкой PKI, профилей и БД, страховочная копия; API: все маршруты без JWT дают 401, секреты замаскированы и зашифрованы в файле, тип ftp отклонён, удалённое назначение без фразы даёт 400. Весь `pytest` в `APP_PROFILER`: 20 пройдено, 2 прежних падения (`test_get_stats`, `test_control_invalid`, 404), не связаны с изменением.
|
||||
- Запуск `migrate.py` из `APP_CORE` на копии БД со схемой 1: 1 -> 2.
|
||||
- Драйвер S3: проверка форматов, создание клиента `minio`; сетевых вызовов не было.
|
||||
- `docker compose config` обоих файлов; сборка UI (Vite, Node 20 в контейнере) без ошибок.
|
||||
|
||||
## Не проверено, открытые вопросы
|
||||
|
||||
- S3 на реальном бакете (проверит владелец); права ключа: list, put, get, delete.
|
||||
- Ручной круг на стенде (копия, повреждение, восстановление, перенос между чистыми окружениями) и работа в системных службах через root-помощник.
|
||||
- UI не просматривался в браузере (светлая и тёмная темы): только сборка.
|
||||
- Образы с новыми зависимостями не собирались; сборка `cryptography` и `minio` на Alpine (musl) не проверена.
|
||||
- Восстановление не перезапускает Core: файл БД монитора заменяется на месте, соединения открываются на каждую операцию; процесс, державший открытое соединение в момент замены, увидит новую БД при следующем обращении.
|
||||
- Состояние задачи в памяти (один процесс профилировщика); прерванная перезапуском задача помечается `interrupted` в истории при старте.
|
||||
- Смена ключа JWT делает сохранённые секреты нечитаемыми: их нужно ввести заново (в UI показывается ошибка при проверке).
|
||||
- `General/Security_Architecture.md` (п. 11 плана) не обновлялся: файл описывает план аутентификации; описание рисков копий дано в руководстве.
|
||||
|
||||
## Отклонения от плана
|
||||
|
||||
- Миграции восстановленных БД выполняются **до** замены, на распакованных копиях, а не после (безопаснее: рабочая система не получает немигрированную БД).
|
||||
- Для БД монитора без кода миграций принимаются только пакеты с равной схемой (в варианте B снято в проходе исправлений, R3).
|
||||
- Ротация затрагивает только пакеты **своего хоста** (общий bucket нескольких серверов).
|
||||
- Страховочные копии `pre-restore` лежат в отдельной папке `<корень>/pre-restore/` (последние 5), а не в выбранном назначении.
|
||||
- Содержимое каталогов `pki/` и `client-config/` заменяется поэлементно (сам каталог может быть точкой монтирования тома), с откатом.
|
||||
- Тестов пять вместо 3-4: добавлен тест восстановления через движок.
|
||||
@@ -0,0 +1,94 @@
|
||||
# Резервное копирование: замечания и недостающие назначения, сводка (2026-10-07)
|
||||
|
||||
План: [2026-10-07_Backup_Restore_Fixes_PLAN.md](2026-10-07_Backup_Restore_Fixes_PLAN.md). Основа: [сводка прохода 1](2026-10-07_Backup_Restore.md). Руководство: [Backup and Restore](../Profiler_Management/Backup_Restore.md).
|
||||
|
||||
В этом проходе реализованы R1, R2, R3, R6, R7. R4 (варианты установки) и R5 (браузер) выполняют ассистент и владелец.
|
||||
|
||||
## Статус по пунктам
|
||||
|
||||
| ID | Статус | Что сделано |
|
||||
|---|---|---|
|
||||
| R1 | сделано | Имя сервера и время в имени пакета |
|
||||
| R2 | сделано в коде и тесте; **восстановление на реальном стеке проверит ассистент** | Ограничение частоты сообщений gatherer |
|
||||
| R3 | сделано в коде и документации; **реальную сборку образа проверит ассистент** | Код миграций монитора в образе профилировщика |
|
||||
| R6 | сделано | Раздел Backups в `General/Security_Architecture.md` |
|
||||
| R7 | сделано в коде, UI и тесте с подменой клиента; **на реальных серверах SFTP, FTP, FTPS проверит ассистент** | Назначения SFTP и FTP/FTPS |
|
||||
|
||||
## R1: имя сервера и время
|
||||
|
||||
- Настройка `server_name` хранится в `ovpmon_backup.db` (не в `ovpn_profiler.db`), проверка `^[A-Za-z0-9][A-Za-z0-9.-]{0,62}$`; `GET/PUT /backup/settings` отдают `server_name`, `effective_server_name` и `server_name_source` (`setting`, `public_ip`, `hostname`). Цепочка: настройка, затем `public_ip` из `system_settings` БД профилировщика (чтение только на чтение, пусто или нет таблицы: пропускается), затем очищенный hostname.
|
||||
- Имя пакета: `ovpmon-backup_<имя>_<YYYYMMDDTHHMMSS>Z.ovpbak[.enc]`; при совпадении секунды в назначении добавляется `-2`, `-3` после `Z` (имена существующих файлов проверяются по списку назначения, перезаписи нет). Регулярное выражение имени обратно совместимо: пакеты прохода 1 с hostname видны и восстанавливаются.
|
||||
- `manifest.json`: `server_name`, `hostname`, `created_at` с миллисекундами UTC.
|
||||
- Ротация считает пакеты с тем же именем сервера в той же папке, порядок по (время, суффикс). Пакеты с другим именем (в том числе старые по hostname) не ротируются.
|
||||
- Список пакетов отдаёт `server_name` вместо `host` (потребитель один, UI), сортировка по времени и суффиксу.
|
||||
- UI: поле Server name в панели Backup с показом фактически используемого имени и источника; в списке пакетов Restore имя сервера, время в UTC и в местном времени браузера; то же в окне подтверждения.
|
||||
|
||||
## R2: журнал gatherer
|
||||
|
||||
`run_monitoring_cycle`: сообщение о пропуске тика пишется на 1-м тике, на пороге `status_invalid_max` (ERROR) и далее на каждом 60-м; при возврате файла один раз INFO `Status file is readable again after N skipped ticks`. Поведение БД и кэша без изменений. Тест `test_missing_status_file_logs_sparingly_and_reports_recovery` (125 тиков без файла: сообщения на 1, 6, 60, 120; восстановление: одна строка INFO). Тесты `APP_CORE`: 17 пройдено.
|
||||
|
||||
**К проверке ассистентом на стенде:** чистый стек, восстановление пакета, запуск OpenVPN, по журналу gatherer убедиться, что он перешёл к обычной работе и сессии появились.
|
||||
|
||||
## R3: миграции монитора в образе профилировщика
|
||||
|
||||
**Проверка до применения.** `APP_CORE/migrations.py` использует только стандартную библиотеку. `APP_CORE/migrate.py` импортирует `migrations` и `db`; `db.py` тоже только стандартная библиотека (`sqlite3`, `configparser`, `os`, `logging`, `migrations`). Сторонних пакетов нет, пункт применён.
|
||||
|
||||
**Отклонение от плана:** кроме `migrations.py` и `migrate.py` в образ копируется и **`db.py`** (`COPY --from=core migrations.py migrate.py db.py /opt/core/`): `migrate.py` импортирует его при запуске (без файла запуск падает с `ModuleNotFoundError`, проверено). Запуск как в движке (`python migrate.py --db <копия>`, cwd = каталог с файлами) проверен на копии БД: 0 -> 2.
|
||||
|
||||
- `APP_PROFILER/Dockerfile`: `COPY --from=core ...`, `ENV OVPMON_CORE_DIR=/opt/core`. `docker-compose.yml`: у `app-profiler` `build.context: ./APP_PROFILER` и `additional_contexts: core: ./APP_CORE`. `docker compose config` обоих файлов разбирается; `docker-compose.allinone.yml` не менялся.
|
||||
- `engine.core_dir()` требует три файла (`migrate.py`, `migrations.py`, `db.py`); при найденном каталоге пакеты с более старой схемой монитора мигрируются, отказ по несовпадению схем остаётся только для старого образа без каталога (сообщение предлагает пересобрать образ).
|
||||
- Требование docker compose 2.17+ записано в `DOCS/Deployment/Containers/README.md` (требования) и `Reference.md`. Проверки версии compose в `deploy/docker/lib.sh` нет (проверяется только наличие `docker compose` или `docker-compose`), поэтому предупреждение в скрипты не добавлялось.
|
||||
- Оговорка про вариант B убрана из `Backup_Restore.md` и из сводки прохода 1.
|
||||
|
||||
**К проверке ассистентом:** реальная сборка образа профилировщика (Alpine) и восстановление пакета со схемой монитора v1 в стек с v2.
|
||||
|
||||
## R6: документация
|
||||
|
||||
`General/Security_Architecture.md`: раздел «Backups» перед «Verification Plan» (состав пакета, шифрование, секреты назначений, закрепление отпечатка SFTP, права каталогов, восстановление как граница доверия, ограничения). Остальной текст файла не менялся.
|
||||
|
||||
## R7: SFTP и FTP
|
||||
|
||||
- `services/backup/destinations.py`: классы `SFTPDestination` (`paramiko`) и `FTPDestination` (`ftplib`), метаданные `FIELDS` (новые виды `number` и `secret_multiline`, поля `warning` + `warn_if`), регистрация в `DESTINATION_TYPES` (удалённые типы требуют парольную фразу автоматически).
|
||||
- **SFTP:** пароль или закрытый ключ (RSA, ECDSA, Ed25519; фраза ключа); пароль и ключ одновременно, без обоих, нечитаемый ключ отклоняются при сохранении. Политика ключей хоста `MissingHostKeyPolicy` принимает только закреплённый отпечаток SHA-256 (известные ключи не загружаются, AutoAdd нет); проверка происходит до отправки учётных данных. Незакреплённый узел: `test` возвращает `needs_trust`, `fingerprint`, `key_type`; `put/list/get/delete` отказывают без подключения; несовпадение: отказ (Test предлагает новый отпечаток с флагом `key_changed`). Закрепление: `POST /backup/destinations/{id}/trust-host-key` (сервер заново подключается и принимает ключ, только если он совпадает с показанным). `host_key` и `host_key_type` приходят только из этого вызова, клиентские значения отбрасываются, при правке без смены host и port закрепление сохраняется, при смене сбрасывается.
|
||||
- **FTP:** `FTP_TLS` (explicit FTPS) по умолчанию, проверка сертификата по умолчанию (явное отключение), пассивный режим по умолчанию, обычный FTP допустим (предупреждение в форме, бейдж в списке и текст результата Test).
|
||||
- **Оба:** загрузка во `.<имя>.part` и переименование; список только по регулярному выражению имени пакета; каталог относительный (как у Local, ведущий `/` отвергается), до 4 уровней, создаётся при записи; таймаут соединения 15 с, передачи 120 с; ошибки текстом без секретов; секреты шифруются и маскируются как у S3.
|
||||
- `requirements.txt`: добавлен `paramiko`. (`cryptography` и `minio` добавлены проходом 1; в `git diff` относительно последнего коммита видны все три.)
|
||||
- UI: типы SFTP и FTP в выборе, форма из `FIELDS` (число, многострочный секрет, предупреждения), показ закреплённого ключа, окно с отпечатком и кнопкой Trust после Test (при смене ключа предупреждение и красная кнопка), бейджи в таблице. Сборка `deploy/ui-dist`: `deploy/native/build-ui.sh --docker --publish`, `check-ui.sh`: актуален.
|
||||
- Документация: `Backup_Restore.md`, `API_Reference.md`, `UI/Architecture.md`, `Core_Monitoring/Data_Architecture.md`, `DOCS/Changes/README.md`, `README.md`, `DOCS/README.md`.
|
||||
|
||||
**К проверке ассистентом на тестовых серверах** (`atmoz/sftp`, `vsftpd`/`pure-ftpd` с TLS и без): тест, копия, список, восстановление, ротация, одновременная запись в 3-4 назначения и сбой одного. Не проверялось: реальная работа `paramiko` и `ftplib` по сети (только подмена клиента), перенос данных через TLS 1.3 у `ftplib` (`unwrap` после загрузки у части серверов), `MLSD`/`NLST` у конкретных серверов, сборка `paramiko` (`cryptography`, `bcrypt`, `pynacl`) на Alpine.
|
||||
|
||||
## Тесты
|
||||
|
||||
Новые: 3 (`test_backup.py`: имя пакета, цепочка имён, уникальность, ротация по имени; SFTP/FTP параметры, закрепление и отказы с подменой клиента; `test_gatherer.py`: частота сообщений и восстановление). В существующем тесте API заменён «неподдерживаемый тип» `ftp` на `smb` (ftp теперь реализован). `pytest APP_PROFILER`: 22 пройдено, 2 прежних падения в `test_server_process.py` (`test_get_stats`, `test_control_invalid`) не тронуты. `pytest APP_CORE`: 17 пройдено.
|
||||
|
||||
## Результаты проверки на стендах (ассистент, 2026-10-07)
|
||||
|
||||
| Пункт | Результат |
|
||||
|---|---|
|
||||
| R1 имя и время | Имя `ovpn-stand` из настроек, формат `ovpmon-backup_ovpn-stand_20261007T061132Z.ovpbak.enc`; без имени берётся `public_ip`, затем `hostname`. |
|
||||
| R2 журнал gatherer | Чистый стек: сообщения на 1-м и 6-м тике (ERROR), затем редко; после запуска OpenVPN запись `Status file is readable again after 7 skipped ticks`, сессии пошли. |
|
||||
| R3 миграции в образе B | Образ профилировщика собран на Alpine, `/opt/core` с `migrate.py`, `migrations.py`, `db.py`. Пакет со схемой мониторинга v1 восстановлен в стек B, схема стала v2 (колонка `session_id` есть), gatherer работает. |
|
||||
| R4 вариант A | Отдельный проект и порты: копия в Local, перенос пакета из стенда B по SFTP, вход прежним администратором, профили и `ca.crt` совпали, OpenVPN запустился, процессы supervisor работают. |
|
||||
| R4 системные службы | Одноразовый контейнер Debian 12 с systemd: `install.sh` отработал, зависимости (`minio`, `paramiko`, `cryptography`) поставлены; копия в Local; восстановление пакета из стенда B по SFTP; владельцы и права (`ovpmon`, 600/700) верны; `server.conf` установлен помощником; OpenVPN запущен через помощник (`openvpn-server@server`); `ca.crt` совпал; схема БД мониторинга 2. |
|
||||
| R7 SFTP | `atmoz/sftp`: отпечаток показан и совпал с `ssh-keygen -lf`; неверный отпечаток отклонён; без закрепления операции отклоняются; копия, список, восстановление, ротация (лимит 2: удалён старый) работают. |
|
||||
| R7 FTP/FTPS | `pure-ftpd` с самоподписанным сертификатом: проверка сертификата отклоняет подключение с понятным текстом; без проверки FTPS работает (загрузка, список, восстановление, TLS 1.3 у `ftplib` без проблем); обычный FTP работает с предупреждением. |
|
||||
| Несколько назначений | Одновременная запись в Local + SFTP + FTP: 3 из 3; при остановленном FTP: 2 из 3, у FTP «Host name cannot be resolved», остальные не затронуты. |
|
||||
| R6 | Раздел «Backups» добавлен в `Security_Architecture.md`. |
|
||||
|
||||
Тестовые серверы, клоны и одноразовый контейнер удалены вместе с их томами и файлами секретов.
|
||||
|
||||
## Не проверено
|
||||
|
||||
- Страница в браузере (R5, владелец): светлая и тёмная темы, форма SFTP/FTP, окно Trust.
|
||||
- Вход в SFTP по закрытому ключу (только подмена клиента), реальное изменение ключа хоста (`key_changed`), PKCS8-ключи Ed25519.
|
||||
- Системные службы на Alpine (OpenRC); на Debian проверено в контейнере, а не на отдельной машине.
|
||||
- Обратный перенос A или служб в контейнеры стенда B.
|
||||
- S3: владелец проверил копирование в бакет (успешно, 2026-10-07); восстановление из S3 и ротация в S3 не подтверждены.
|
||||
- SMB (вне плана, в очереди).
|
||||
|
||||
## Отклонения от плана
|
||||
|
||||
- В образ профилировщика копируется ещё и `db.py` (R3).
|
||||
- В списке пакетов поле `host` переименовано в `server_name`.
|
||||
- Каталог SFTP/FTP с ведущим `/` отвергается (у Local он молча нормализуется).
|
||||
@@ -0,0 +1,85 @@
|
||||
# Резервное копирование: замечания и недостающие назначения (план, 2026-10-07)
|
||||
|
||||
Основание: проверка первого прохода ([сводка](2026-10-07_Backup_Restore.md), [исходный план](2026-10-07_Backup_Restore_PLAN.md)) и проверка владельца в браузере: в настройке назначения доступны только локальная папка и S3, **SFTP и FTP из исходного требования отсутствуют**.
|
||||
|
||||
Вне этого плана: S3 (ждём бакет владельца), SMB (проход 3 исходного плана, остаётся в очереди), проверка страницы в браузере (выполняет владелец).
|
||||
|
||||
## 1. Список
|
||||
|
||||
| ID | Замечание | Решение |
|
||||
|---|---|---|
|
||||
| R1 | В имени пакета стоит `hostname`; в контейнере это случайный идентификатор | Имя пакета строится из **имени сервера из настроек** и точного времени (п. 2) |
|
||||
| R2 | Gatherer на свежей или восстановленной установке пишет ERROR каждые 10 с, пока OpenVPN не запущен; восстановление после появления файла статуса не подтверждено | Ограничить частоту сообщений, писать о восстановлении, проверить на стенде (п. 3) |
|
||||
| R3 | Вариант B: профилировщик не может мигрировать БД мониторинга из пакета с другой версией схемы (в образе нет кода `APP_CORE`), восстановление отказывает | Положить `migrations.py` и `migrate.py` из `APP_CORE` в образ профилировщика (п. 4) |
|
||||
| R4 | Не проверено: вариант A (всё в одном контейнере), системные службы с root-помощником | Проверка по сценариям п. 6 |
|
||||
| R6 | `General/Security_Architecture.md` не описывает резервные копии | Короткий раздел (п. 8) |
|
||||
| R7 | Нет назначений **SFTP** и **FTP** | Реализовать (п. 5) |
|
||||
|
||||
(R5, проверка в браузере, выполняется владельцем и в план не входит.)
|
||||
|
||||
## 2. R1: имя сервера и время в имени пакета
|
||||
|
||||
В настройках **нет** поля «имя сервера» (есть только `public_ip`), поэтому:
|
||||
|
||||
- В настройки резервного копирования (**не** в `ovpn_profiler.db`, которая заменяется при восстановлении) добавляется поле **Server name**: `^[A-Za-z0-9][A-Za-z0-9.-]{0,62}$`, хранится в `ovpmon_backup.db`; API `GET/PUT /backup/settings` (`server_name`), поле на странице Backup and Restore. После переноса на новый сервер имя задаётся заново, оно не приезжает из пакета.
|
||||
- Если имя не задано: `public_ip` из настроек VPN (если есть), иначе `hostname`. UI показывает, какое имя будет использовано.
|
||||
- Формат: `ovpmon-backup_<server-name>_<YYYYMMDDTHHMMSS>Z.ovpbak[.enc]`: время UTC, до секунды, суффикс `Z`. При совпадении имени (две копии в одну секунду) добавляется `-2`, `-3`, файл не перезаписывается.
|
||||
- В `manifest.json`: `server_name`, `hostname` (как сейчас), `created_at` с миллисекундами в UTC.
|
||||
- Список пакетов в UI: имя сервера, время **в UTC и в локальном времени браузера**, размер, шифрование; сортировка по времени.
|
||||
- Старые пакеты с прежним форматом имени остаются видимыми и восстанавливаются.
|
||||
- Ротация считает пакеты с тем же именем сервера в одной папке; пакеты со старым `hostname` в ротации не участвуют (указать в документации). Серверы с одним именем в одной папке ротируют друг друга: имена задаёт владелец.
|
||||
|
||||
## 3. R2: журнал gatherer
|
||||
|
||||
- В `run_monitoring_cycle`: сообщение о пропуске тика пишется на 1-м тике, на пороге `status_invalid_max` (ERROR) и далее раз в 60 тиков (около 10 минут при интервале 10 с); при возврате файла один раз INFO «status file is readable again after N skipped ticks».
|
||||
- Состояние БД и кэша при пропуске не меняется, как сейчас.
|
||||
- Проверка: тест на счётчик сообщений; на стенде: чистый стек, восстановление пакета, запуск OpenVPN, по журналу gatherer убедиться, что он перешёл к обычной работе и сессии появились.
|
||||
|
||||
## 4. R3: миграции мониторинга в образе профилировщика
|
||||
|
||||
- `docker-compose.yml`: `additional_contexts: core: ./APP_CORE` для `app-profiler`; `APP_PROFILER/Dockerfile`: `COPY --from=core migrations.py migrate.py /opt/core/`, переменная `OVPMON_CORE_DIR=/opt/core`. Контекст сборки профилировщика не меняется. Для `deploy/allinone` изменений нет (там `APP_CORE` уже есть).
|
||||
- Сначала проверить, что `APP_CORE/migrations.py` и `migrate.py` используют только стандартную библиотеку; если нет, пункт отменяется, остаётся прежнее ограничение (отказ при другой версии схемы), документировать.
|
||||
- Убрать из `Backup_Restore.md` и сводки оговорку о варианте B; проверить восстановление пакета со схемой мониторинга v1 в стек с v2. Поддержка `additional_contexts` в `docker compose` хоста: нужна версия 2.17+ (на хосте 2.38); в документации указать требование.
|
||||
|
||||
## 5. R7: назначения SFTP и FTP
|
||||
|
||||
Те же интерфейс (`test`, `put`, `list`, `get`, `delete`), шифрование секретов, правила и ротация, что у Local и S3. Параметры описываются в `FIELDS` назначения, форма в UI строится из них (добавить вид поля «многострочный секрет» для закрытого ключа).
|
||||
|
||||
| | SFTP (`paramiko`) | FTP (`ftplib`) |
|
||||
|---|---|---|
|
||||
| Параметры | хост, порт (22), пользователь, каталог | хост, порт (21), пользователь, каталог, пассивный режим (вкл), **TLS (explicit FTPS), по умолчанию вкл**, проверка сертификата (вкл) |
|
||||
| Секреты | пароль **или** закрытый ключ (+ его парольная фраза) | пароль |
|
||||
| Проверка узла | **отпечаток ключа хоста (SHA-256) закрепляется**: первая проверка показывает отпечаток, администратор подтверждает кнопкой «Trust», он сохраняется в параметрах; при несовпадении подключение отклоняется. Копирование, список, восстановление без закреплённого отпечатка запрещены | при TLS проверяется сертификат; отключение проверки (самоподписанный) допускается явно, в UI предупреждение; без TLS в UI предупреждение, что пароль идёт открытым текстом |
|
||||
| Запись | загрузка во временное имя `.part`, затем переименование | то же |
|
||||
| Список | только файлы нашего формата имени | то же |
|
||||
|
||||
- Удалённые назначения требуют парольную фразу пакета (правило плана остаётся), а значит и SFTP, и FTP.
|
||||
- Каталог проверяется как для Local (относительный, без `..`); имена файлов формируются только приложением.
|
||||
- Таймауты подключения и передачи ограничены; ошибки возвращаются понятным текстом без секретов.
|
||||
- Зависимость `paramiko` в `requirements.txt`; сборка образа на Alpine проверяется (зависит от `cryptography`, `bcrypt`, `pynacl`).
|
||||
- Проверка на стенде тестовыми серверами в контейнерах в сети стенда: SFTP (`atmoz/sftp`), FTP и FTPS (`vsftpd` или `pure-ftpd`). Локальный S3 по-прежнему не поднимается. Круг на каждом: тест, копия, список в Restore, восстановление, ротация, одновременная запись в 3-4 назначения (Local + SFTP + FTP + при желании ещё одно) и сбой одного из них. Тестовые серверы и тома удаляются после проверки.
|
||||
|
||||
## 6. R4: проверки вариантов установки
|
||||
|
||||
**Вариант A (all-in-one).** Отдельный проект и порты (`ovp-allinone` не конфликтует с `ovp-*`), собрать образ, настроить локальное назначение (и SFTP/FTP), сделать копию, изменить данные, восстановить; затем **перенос пакета из стенда варианта B в A** и обратно. Проект удалить по окончании.
|
||||
|
||||
**Системные службы (root-помощник).** Устанавливать на этот хост нельзя (Debian, рабочие службы). Используется одноразовый **контейнер Debian 12 с systemd** (privileged, удаляется после проверки), в нём `deploy/native/install.sh`. Проверяем: установку новых зависимостей установщиком и `update.sh`; права `ovpmon` на `/var/lib/ovpmon/backups`; песочницу юнитов (`ReadWritePaths`); замену БД и каталогов под `ovpmon`; миграцию БД мониторинга через `APP_CORE/venv`; создание `server.conf`, публикацию CRL и перезапуск OpenVPN через помощник; перенос пакета из контейнерного стека в службы. Если контейнер с systemd не заработает, проверка сводится к разбору кода и юнитов, и это явно записывается в сводку как непроверенное.
|
||||
|
||||
## 7. Тесты
|
||||
|
||||
Не более 3 новых или изменённых автотестов: формат имени пакета и порядок выбора имени (настройка → `public_ip` → `hostname`) с уникальностью; ограничение частоты сообщений gatherer; проверка параметров SFTP/FTP и закрепления отпечатка (без сети, с подменой клиента). Всё остальное проверяется на стендах.
|
||||
|
||||
## 8. Документация (R6 и сопутствующая)
|
||||
|
||||
Раздел «Backups» в `General/Security_Architecture.md` (что в пакете, шифрование, секреты назначений, закрепление отпечатка SFTP, права каталогов, границы доверия); обновление `Profiler_Management/Backup_Restore.md` (SFTP, FTP, имя сервера, формат имени, ротация, вариант B), `API_Reference.md`, `UI/Architecture.md`, `Deployment/*/Reference.md` при необходимости, таблица в `Changes/README.md`, сводка `2026-10-07_Backup_Restore_Fixes.md`.
|
||||
|
||||
## 9. Решения по умолчанию (владелец поручил взять остальное в работу)
|
||||
|
||||
- Имя сервера задаётся в разделе Backup and Restore (не общим полем VPN-настроек).
|
||||
- Системные службы проверяются в одноразовом контейнере Debian 12 с systemd.
|
||||
|
||||
## 10. Порядок
|
||||
|
||||
1. План утверждён владельцем (2026-10-07).
|
||||
2. Реализация субагентом (Sonnet 5.5, Medium Effort): R1, R2, R3, R6, R7 (код, тесты, документация).
|
||||
3. Проверки R2, R3, R4, R7 на стендах ассистентом, результаты в сводку; страницу в браузере проверяет владелец.
|
||||
@@ -0,0 +1,132 @@
|
||||
# Резервное копирование и восстановление (план, 2026-10-07)
|
||||
|
||||
Цель: создавать пакеты резервных копий и восстанавливать из них, в том числе **на другом сервере** (другая физическая или виртуальная машина, контейнеры; из контейнеров в системные службы и обратно). Управление есть в API и в UI: в разделе **Management** появляется пункт **Backup and Restore**.
|
||||
|
||||
Не путать с `deploy/docker/backup.sh` и `update.sh`: они копируют тома Docker целиком перед обновлением и работают только из командной строки. Новая функция работает из UI/API на уровне данных приложения и не зависит от способа установки.
|
||||
|
||||
## 1. Что входит в пакет
|
||||
|
||||
| Содержимое | Источник | Почему |
|
||||
|---|---|---|
|
||||
| `db/openvpn_monitor.db` | мониторинг: статистика, учётные записи, 2FA | консистентный снимок через онлайн-копию SQLite (`Connection.backup`), остановка не нужна |
|
||||
| `db/ovpn_profiler.db` | профили, настройки сервера и PKI | то же |
|
||||
| `pki/` (каталог `easy-rsa/pki`) | CA, ключи и сертификаты, CRL, `ta.key`, `dh.pem` | **секретные данные** |
|
||||
| `client-config/*.ovpn` | выданные профили | пути в базе относительные, совпадают во всех вариантах установки |
|
||||
| `manifest.json` | версия формата, время, хост, среда (`container`/`host`), версии схем БД, SHA-256 каждого файла, число профилей | проверка до восстановления |
|
||||
|
||||
Не входит (специально): `server.conf` (создаётся заново из настроек), `/etc/ovpmon/env` и `JWT_SECRET` (свои на каждом сервере), TLS-сертификат веб-интерфейса, логи, настройки назначений резервного копирования (см. п. 3), `ipp.txt`.
|
||||
|
||||
Имя пакета: `ovpmon-backup_<host>_<YYYYMMDDTHHMMSSZ>.ovpbak` (tar.gz); при шифровании добавляется `.enc`. Имя разбирается регулярным выражением, всё остальное в назначении игнорируется.
|
||||
|
||||
**Шифрование.** Пакет содержит закрытый ключ CA и хеши паролей. Опциональная парольная фраза в настройках: AES-256-GCM по блокам, ключ из фразы через scrypt, соль и параметры в заголовке (библиотека `cryptography`). Правило: **без фразы резервное копирование на удалённые назначения запрещено** (400), в локальную папку разрешено с предупреждением в UI. Фраза не возвращается API; при восстановлении вводится вручную.
|
||||
|
||||
## 2. Назначения (несколько одновременно)
|
||||
|
||||
Назначение = именованная запись: тип, параметры, секреты, флаг «включено», число хранимых копий (по умолчанию 14). «Backup now» отправляет пакет **во все включённые назначения** (или в выбранные), результат по каждому отдельно: сбой одного не отменяет остальные.
|
||||
|
||||
| Тип | Реализация | Параметры |
|
||||
|---|---|---|
|
||||
| Local | каталог на сервере | подпапка внутри корня `OVPMON_BACKUP_LOCAL_ROOT` (системные службы: `/var/lib/ovpmon/backups`, контейнеры: `/app/backups`, том `ovp_backups`); пути вне корня и символические ссылки отклоняются |
|
||||
| FTP | `ftplib` (+ FTPS explicit TLS) | хост, порт, пользователь, пароль, каталог, TLS |
|
||||
| SFTP | `paramiko` | хост, порт, пользователь, пароль или ключ, каталог; **отпечаток ключа хоста** фиксируется при первой проверке и далее обязателен |
|
||||
| S3 | `minio` (Python SDK; работает с AWS S3 и совместимыми хранилищами, решение владельца) | endpoint, TLS вкл/выкл, регион (необязательно), bucket, префикс, access/secret key; режим адресации (path/virtual-host) при необходимости |
|
||||
| SMB (Samba) | `smbprotocol` (клиент, без монтирования ОС и без root) | хост, порт, общая папка (share), каталог, пользователь, пароль, домен |
|
||||
|
||||
Общий интерфейс: `test()`, `put(file)`, `list()`, `get(name)`, `delete(name)`. Ротация: после успешной записи удаляются самые старые пакеты **нашего формата имени** сверх лимита.
|
||||
|
||||
Секреты назначений шифруются в базе ключом из `OVPMON_API_SECRET_KEY` (HKDF), API возвращает их только как маску. Они **не попадают в пакет** (на новом сервере назначения настраиваются заново; секреты старого сервера не переносятся). Смена ключа подписи требует повторного ввода секретов.
|
||||
|
||||
## 3. Хранение настроек резервного копирования
|
||||
|
||||
**Отдельный файл SQLite** рядом с базой профилировщика (`ovpmon_backup.db`): назначения, настройки, история запусков. Причина: восстановление заменяет `ovpn_profiler.db` и `openvpn_monitor.db`; настройки назначений не должны ни попадать в пакет, ни пропадать при восстановлении. Схема создаётся при старте сервиса (`CREATE IF NOT EXISTS` + таблица версии), существующие миграции не затрагиваются.
|
||||
|
||||
## 4. Восстановление
|
||||
|
||||
Поток в UI: **Source** (выпадающий список назначений) → автоматическая проверка источника (подключение, права на чтение, поиск пакетов) → **Package** (выпадающий список: дата, хост, размер, признак шифрования, новые сверху) → поле фразы (если пакет зашифрован) → отдельная кнопка **Restore** → окно подтверждения → прогресс.
|
||||
|
||||
Шаги на сервере (фоновая задача, одна на весь сервис, как асинхронная инициализация PKI):
|
||||
|
||||
1. Скачать пакет во временный каталог, расшифровать, проверить `manifest.json` и SHA-256 всех файлов.
|
||||
2. **Безопасная распаковка**: только ожидаемые имена верхнего уровня; абсолютные пути, `..`, ссылки, устройства и превышение лимита размера отклоняются.
|
||||
3. Отказ, если схема БД в пакете **новее** кода (версии в манифесте), или формат пакета неизвестен. Пакеты со старой схемой допустимы: после замены запускаются существующие миграции.
|
||||
4. **Страховочная копия текущего состояния** в локальное назначение (`pre-restore`); если сделать её не удалось, восстановление не начинается.
|
||||
5. Остановить OpenVPN (если запущен), заменить БД атомарным `os.replace`, `pki/` и `client-config/` каталогами через временные имена с откатом при ошибке; сбросить пул соединений SQLAlchemy профилировщика. Мониторинг и gatherer открывают БД на каждую операцию, остановка не нужна.
|
||||
6. Миграции восстановленных БД; перегенерировать `server.conf` и опубликовать CRL существующим путём (в системных службах через root-помощник; помощник и его белый список не меняются); запустить OpenVPN, если он работал.
|
||||
7. Результат в историю. UI предлагает войти заново (учётные записи теперь из пакета).
|
||||
|
||||
Во время восстановления изменяющие PKI и профили запросы получают 409 (тот же механизм, что у инициализации PKI). После переноса на новый сервер администратор проверяет адрес сервера (`remote`) в настройках VPN: он приходит из пакета.
|
||||
|
||||
## 5. API (Profiler API, префикс `/api`, снаружи `/profiles-api/`, все маршруты под JWT)
|
||||
|
||||
| Метод | Путь | Назначение |
|
||||
|---|---|---|
|
||||
| GET, PUT | `/backup/settings` | флаг и смена парольной фразы (значение не возвращается), корень локальных копий, лимит по умолчанию |
|
||||
| GET, POST | `/backup/destinations` | список, создание |
|
||||
| PUT, DELETE | `/backup/destinations/{id}` | изменение, удаление |
|
||||
| POST | `/backup/destinations/{id}/test` | проверка подключения и записи |
|
||||
| POST | `/backup/run` | запуск копирования (`destination_ids` необязательно), 202 |
|
||||
| GET | `/backup/destinations/{id}/packages` | проверить источник и перечислить пакеты (имя, время, размер, шифрование) |
|
||||
| POST | `/backup/restore` | `destination_id`, `package`, `passphrase` (необязательно), 202 |
|
||||
| GET | `/backup/status` | текущая задача: этапы и результат по назначениям |
|
||||
| GET | `/backup/history` | последние запуски |
|
||||
|
||||
Имя пакета проверяется регулярным выражением и берётся только из листинга; пути от клиента не принимаются.
|
||||
|
||||
## 6. UI
|
||||
|
||||
Новый вид `APP_UI/src/views/BackupRestore.vue`, маршрут `/backup`, пункт **Backup and Restore** в разделе MANAGEMENT боковой панели (рядом с Certificates и Server Process, тот же стиль ссылки и значка). Внешний вид повторяет существующие страницы: `config-wrapper` / `config-card` / `config-header`, `status-badge`, `BaseModal`, `ConfirmModal`, `useToast`, оба светлых и тёмных оформления; английские подписи, как везде.
|
||||
|
||||
1. **Destinations**: таблица (имя, тип, статус «включено», последний результат, действия Test / Edit / Delete), кнопка «Add destination», модальное окно с полями выбранного типа.
|
||||
2. **Backup**: статус шифрования (предупреждение, если фразы нет), флажки назначений, кнопка **Backup now**, прогресс и результат по каждому назначению, история.
|
||||
3. **Restore**: выбор источника, список пакетов, фраза, кнопка **Restore** (красная, с подтверждением, перечисляющим последствия).
|
||||
|
||||
## 7. Развёртывание
|
||||
|
||||
- Зависимости в `APP_PROFILER/requirements.txt`: `cryptography`, `paramiko`, `minio`, `smbprotocol`. Если сценарий S3 не получится реализовать на `minio`, драйвер S3 откатывается (решение владельца: сначала `minio`); интерфейс назначений от этого не меняется.
|
||||
- Контейнеры: новый том `ovp_backups` на `/app/backups` в `docker-compose.yml` и `docker-compose.allinone.yml`. Список томов в `deploy/docker/lib.sh` (`VOLUMES`, пять томов) **не расширяется**: том с копиями не копируется внутрь копий томов.
|
||||
- Системные службы: каталог `/var/lib/ovpmon/backups` создаётся службой (владелец `ovpmon`), установщик не меняется; сборка Python-зависимостей на Alpine проверяется.
|
||||
- Nginx: изменений нет (задачи асинхронные, опрос статуса).
|
||||
|
||||
## 8. Шаги реализации (три прохода, после каждого проверка)
|
||||
|
||||
Приоритет владельца: резервное копирование и восстановление **в бакет S3 и из него**. Поэтому S3 входит в первый проход.
|
||||
|
||||
| Проход | Содержимое | Проверка |
|
||||
|---|---|---|
|
||||
| 1 | Формат пакета, шифрование, безопасная распаковка, хранилище настроек, назначения **Local и S3 (`minio`)**, API (все маршруты), движок восстановления, весь UI | автотесты; ручной круг на стенде с локальным назначением (копия, повреждение данных, восстановление, перенос между чистыми окружениями); S3 проверяется владельцем на его бакете вместе с ассистентом, **локальный S3 для эмуляции не поднимается** |
|
||||
| 2 | FTP, SFTP | на стенде тестовые контейнеры (vsftpd/pure-ftpd, `atmoz/sftp`) |
|
||||
| 3 | SMB, ротация во всех типах, документация, сводка | тестовый контейнер Samba; одновременная запись в 3-4 назначения и сбой одного из них |
|
||||
|
||||
## 9. Автотесты (минимум, 3-4 шт., `APP_PROFILER`)
|
||||
|
||||
1. Полный круг пакета: создать, зашифровать, проверить, восстановить во временные каталоги (БД читаются, PKI и профили совпадают), неверная фраза отклоняется.
|
||||
2. Безопасная распаковка: пакет с `../` и ссылкой отклоняется; пакет с более новой схемой отклоняется.
|
||||
3. Несколько назначений: одно рабочее (Local) и одно с ошибкой, результат по каждому, ротация по лимиту.
|
||||
4. API: маршруты требуют JWT; секреты в ответах замаскированы; удалённое назначение без фразы отклоняется.
|
||||
|
||||
Клиенты S3/FTP/SFTP/SMB проверяются вручную (раздел 8), без юнит-тестов; для S3 драйвер подменяется в тесте заглушкой интерфейса назначений, настоящий S3 в автотестах не используется.
|
||||
|
||||
## 10. Риски
|
||||
|
||||
- Пакет содержит ключ CA и хеши паролей: шифрование обязательно для удалённых назначений, права локальных каталогов 700/600, секреты не пишутся в журнал.
|
||||
- Восстановление заменяет учётные записи и PKI: обязательная страховочная копия и подтверждение с перечнем последствий.
|
||||
- Сервер подключается к адресам, заданным администратором (SSRF в рамках функции); доступ только по JWT единственной роли, адреса и порты проверяются по формату.
|
||||
- Размер: база статистики может быть большой; пакет собирается потоково через временный файл, нужен запас места в `/tmp` или в корне локальных копий.
|
||||
- Возврат к прежнему состоянию после неудачного восстановления: каталоги и БД заменяются через временные имена, страховочная копия остаётся.
|
||||
|
||||
## 11. Документация
|
||||
|
||||
Новый `DOCS/Profiler_Management/Backup_Restore.md` (руководство, включая перенос между серверами в обоих вариантах установки), обновление `Profiler_Management/API_Reference.md`, `UI/Architecture.md`, `General/Overview.md` (где лежат данные), `General/Security_Architecture.md`, `Deployment/Containers/Reference.md` (новый том), `Deployment/System_Services/Reference.md` (каталог копий), README.md (таблица документации), `DOCS/Changes/README.md`, сводка `2026-10-07_Backup_Restore.md`.
|
||||
|
||||
## 12. Порядок
|
||||
|
||||
1. Утверждение плана (и решений из раздела «Вопросы»).
|
||||
2. Реализация субагентом (Sonnet 5.5, Medium Effort), три прохода.
|
||||
3. Проверка на стенде после каждого прохода, затем документация и сводка.
|
||||
|
||||
## Решения владельца (2026-10-07)
|
||||
|
||||
1. Парольная фраза обязательна для удалённых назначений: **да**.
|
||||
2. Расписание автоматических копий: **позже, отдельным шагом**.
|
||||
3. Загрузка пакета с компьютера как источник восстановления: **нет**.
|
||||
4. Драйвер S3: **`minio`**; при невозможности реализовать сценарий откат на другой драйвер. Тестирование на бакете владельца, локальный S3 не поднимается.
|
||||
@@ -20,3 +20,7 @@ Every change has a plan (`*_PLAN.md`) before it and a summary of what was done a
|
||||
| 2026-10-05 | Комплексный анализ кодовой базы на основе графа знаний: безопасность, корректность, архитектура, тесты, рекомендации P0-P2 | [plan](2026-10-05_Code_Review_PLAN.md) · [change](2026-10-05_Code_Review.md) · [отчёт](../code_review/2026-10-05_1607Z_Codebase_Analysis.md) |
|
||||
| 2026-10-05 | Сборщик трафика: устойчивый цикл, остановка по сигналу, проверка целостности и свежести файла статуса, учёт сессий по времени их начала (BUG-02, BUG-03) | [plan](2026-10-05_Gatherer_Reliability_PLAN.md) · [change](2026-10-05_Gatherer_Reliability.md) |
|
||||
| 2026-10-05 | Ключ подписи JWT без значения по умолчанию: Core и Profiler не запускаются при пустом, слабом или заимствованном из примера ключе; проверка в установщиках, `update.sh` выпускает ключ при необходимости (SEC-01) | [plan](2026-10-05_JWT_Secret_Fail_Closed_PLAN.md) · [change](2026-10-05_JWT_Secret_Fail_Closed.md) |
|
||||
| 2026-10-06 | Учёт нескольких сессий одного пользователя: ключ сессии по `Client ID` (устойчив к `float`), одна запись на CN за тик, скорость и история суммируются по сессиям (MS-1..MS-5); миграция 002 | [plan](2026-10-06_Multi_Session_Stats_PLAN.md) · [change](2026-10-06_Multi_Session_Stats.md) |
|
||||
| 2026-10-07 | Шаблоны OpenVPN по мануалу 2.7: из клиентского профиля убраны `windows-driver`, `tls-client`, `user`/`group`, для udp добавлен `explicit-exit-notify`; из серверного убраны `tls-server`, дубль `# explicit-exit-notify`, строка `log` | [plan](2026-10-07_OVPN_Templates_PLAN.md) · [change](2026-10-07_OVPN_Templates.md) |
|
||||
| 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) |
|
||||
@@ -31,7 +31,7 @@ Both variants use the **same five named volumes with the same in-container paths
|
||||
|
||||
## Requirements
|
||||
|
||||
- Docker Engine with the compose plugin (`docker compose`, v2, preferred) or `docker-compose`.
|
||||
- Docker Engine with the compose plugin (`docker compose`, v2, preferred) or `docker-compose`. **Variant B needs docker compose 2.17 or newer** (the profiler image is built with `additional_contexts`; the old `docker-compose` v1 does not support it). Variant A is not affected.
|
||||
- The Docker daemon running and usable by the user that runs the scripts (root, or a member of the `docker` group).
|
||||
- Access to `/dev/net/tun` on the host and the `NET_ADMIN` capability (already set in the compose files).
|
||||
- Free disk space: about 2 GB for images and builds, plus room for backups (the scripts check both).
|
||||
|
||||
@@ -32,7 +32,12 @@ Variables of the scripts (environment of the shell, not `.env`): `OVPMON_BACKUP_
|
||||
| `ovp_config` | `/etc/openvpn` | `server.conf` generated by the profiler | profiler |
|
||||
| `ovp_pki` | `/app/easy-rsa` | easy-rsa scripts and `pki/` (CA, server and client keys and certificates, CRL, `ta.key`, `dh.pem`) | profiler |
|
||||
| `ovp_client_config` | `/app/client-config` | generated client `.ovpn` files | profiler |
|
||||
| `db_data` | `/app/db` | `ovpn_profiler.db`, `openvpn_monitor.db`, migration backups `*.db.bak-*` | gatherer, api, profiler |
|
||||
| `db_data` | `/app/db` | `ovpn_profiler.db`, `openvpn_monitor.db`, `ovpmon_backup.db` (settings of the Backup and Restore page), migration backups `*.db.bak-*` | gatherer, api, profiler |
|
||||
| `ovp_backups` | `/app/backups` | local backup packages of the Backup and Restore page (`OVPMON_BACKUP_LOCAL_ROOT=/app/backups`) | profiler |
|
||||
|
||||
`ovp_backups` is not one of the five data volumes: `deploy/docker/backup.sh` and `update.sh` do not copy it (packages are not put inside copies of the volumes). Back it up separately or use a remote destination. See [Backup and Restore](../../Profiler_Management/Backup_Restore.md).
|
||||
|
||||
Variant B, profiler image: besides `APP_PROFILER` it holds `/opt/core` (`migrations.py`, `migrate.py`, `db.py` of `APP_CORE`, standard library only; `OVPMON_CORE_DIR=/opt/core`), added at build time through the build context `core` (`additional_contexts` in `docker-compose.yml`, docker compose 2.17+). The restore of a backup package uses it to migrate the monitoring database of the package.
|
||||
|
||||
Not stored in volumes (lost when the container is recreated): the container file system, `profiler.log` and `openvpn_gatherer.log` (written into the working directory), supervisor state. Application logs go to `docker logs`.
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ Paths and owners, the environment file, the root helper configuration and securi
|
||||
| Profiler log | `<prefix>/APP_PROFILER/profiler.log` | `ovpmon:ovpmon` 640 |
|
||||
| Shipped settings file | `<prefix>/APP_CORE/config.ini`, `<prefix>/APP_PROFILER/config.ini` | `root:root`; the environment file overrides it |
|
||||
| **Databases** | `/var/lib/ovpmon/openvpn_monitor.db`, `ovpn_profiler.db`, migration copies `*.db.bak-*` | `ovpmon:ovpmon` |
|
||||
| **Local backup packages** (Backup and Restore page), `ovpmon_backup.db` | `/var/lib/ovpmon/backups/` (created by the service, folders 700, files 600; root set by `OVPMON_BACKUP_LOCAL_ROOT`), `/var/lib/ovpmon/ovpmon_backup.db` | `ovpmon:ovpmon` |
|
||||
| Staging of `server.conf` | `/var/lib/ovpmon/staging/` | `ovpmon:ovpmon` 750 |
|
||||
| Service environment | `/etc/ovpmon/env` | `root:root` 600 |
|
||||
| Helper configuration | `/etc/ovpmon/helper.conf` | `root:root` 644 |
|
||||
|
||||
@@ -13,6 +13,7 @@ Each component reads `config.ini` (shipped in `APP_CORE/` and `APP_PROFILER/`);
|
||||
| `OVPMON_PROFILER_DB_PATH` | profiler database |
|
||||
| `OVPMON_OPENVPN_MONITOR_LOG_PATH` | path of `openvpn-status.log` |
|
||||
| `OVPMON_LOGGING_LEVEL` | `INFO` / `DEBUG` |
|
||||
| `OVPMON_BACKUP_LOCAL_ROOT` | root of the local backup destinations (default `/var/lib/ovpmon/backups`; containers: `/app/backups`); other backup variables: [Backup and Restore](../Profiler_Management/Backup_Restore.md) |
|
||||
|
||||
## JWT signing key rule
|
||||
|
||||
|
||||
@@ -31,6 +31,8 @@ VPN clients --udp/1194--> OpenVPN
|
||||
| PKI | CA, server and client keys and certificates, CRL, `ta.key`, `dh.pem` (**secret, back it up**) |
|
||||
| Client profiles | generated `.ovpn` files |
|
||||
| `server.conf` | generated by the profiler from the settings in the UI |
|
||||
| Backup settings (SQLite `ovpmon_backup.db`, next to the profiler DB) | backup destinations (secrets encrypted), passphrase, history; not part of a backup package |
|
||||
| Local backup packages | `/var/lib/ovpmon/backups` (system services) or volume `ovp_backups` at `/app/backups` (containers); see [Backup and Restore](../Profiler_Management/Backup_Restore.md) |
|
||||
|
||||
Exact locations per installation method: [Containers: volumes](../Deployment/Containers/Reference.md), [System services: layout](../Deployment/System_Services/Reference.md). Schema changes on update are handled by [database migrations](Database_Migrations.md).
|
||||
|
||||
|
||||
@@ -63,6 +63,18 @@ This includes:
|
||||
- **Request**: Add `Authorization: Bearer <token>`.
|
||||
- **Response**: On `401 Unauthorized`, clear token and redirect to `/login`.
|
||||
|
||||
## Backups
|
||||
|
||||
The Backup and Restore function ([guide](../Profiler_Management/Backup_Restore.md)) makes a package of the application data. What matters for security:
|
||||
|
||||
- **What a package holds:** the CA private key and all issued keys (`pki/`), the monitoring database (administrator password hashes, 2FA secrets), the profiler database and the issued client profiles. Whoever can read a package can impersonate the VPN server and its clients. The JWT signing key and the environment file are **not** in it.
|
||||
- **Encryption:** with a passphrase (at least 8 characters) the package is encrypted with AES-256-GCM in 1 MiB blocks; the key comes from scrypt (N=2^15) with a random salt; the header is authenticated, so truncation and tampering are detected. **Remote destinations (S3, SFTP, FTP) refuse to work without a passphrase.** A local folder works without it and the page warns. The passphrase is never stored in a package; without it an encrypted package cannot be opened.
|
||||
- **Secrets of the function:** destination secrets (keys, passwords, SFTP private key) and the package passphrase are stored in `ovpmon_backup.db`, encrypted (Fernet) with a key derived (HKDF-SHA256) from the JWT signing key. The API returns `********` instead of a value and never logs one; error messages carry no secrets. If the signing key changes they cannot be read any more and must be entered again. `ovpmon_backup.db` (mode 600) is not part of a package and is never replaced by a restore.
|
||||
- **SFTP:** the SSH host key is pinned by its SHA-256 fingerprint. The first Test shows the fingerprint and the administrator confirms it; until then nothing is sent to the server (not even the password) and every operation is refused. Unknown keys are never accepted automatically, and a changed key breaks the connection before credentials are sent. **FTP:** explicit TLS and certificate verification are on by default; plain FTP and an unchecked certificate are explicit, warned choices. S3: TLS by default.
|
||||
- **Local storage:** the backup root (`/var/lib/ovpmon/backups`, containers `/app/backups`) and its folders are mode 700, packages 600, owner `ovpmon`; folder names are validated, links and paths outside the root are refused. In containers the volume `ovp_backups` is not covered by `deploy/docker/backup.sh`.
|
||||
- **Restore as a trust boundary:** all routes need the JWT (any administrator can start a restore, and a restore replaces the administrator accounts). The package is unpacked into a temporary directory with an allowlist of names (no absolute paths, `..`, links, devices; size and entry limits), checked against the SHA-256 sums of its manifest and migrated there; the running system is touched only after all that and after a safety copy of the current state. The sums are inside the package: they detect damage, not forgery. **Authenticity comes from encryption** (a forged encrypted package fails the GCM check), so an unencrypted package from a place others can write to must not be restored. During a restore requests that change the PKI, profiles, settings or the OpenVPN process return `409`.
|
||||
- **Limits:** the passphrase and destination secrets are only as safe as the JWT signing key and the file permissions of the server; a stolen package with its passphrase, or a stolen `.env` with `ovpmon_backup.db`, opens the CA key.
|
||||
|
||||
## Verification Plan
|
||||
|
||||
### Automated Tests
|
||||
|
||||
@@ -94,3 +94,59 @@ Control the OpenVPN system service.
|
||||
### `GET /server/process/stats`
|
||||
Get telemetry for the OpenVPN process.
|
||||
- **Response**: `{ "status": "running", "cpu_percent": 1.2, "memory_mb": 45.0 }`
|
||||
|
||||
---
|
||||
|
||||
## 4. Backup and Restore
|
||||
|
||||
Guide: [Backup and Restore](Backup_Restore.md). All routes need the JWT. Errors: `400` invalid request, `409` another job is running (or a restore is running), `502` the destination could not be reached. Messages never contain secrets.
|
||||
|
||||
While a restore runs, `POST /profiles`, `DELETE /profiles/{id}`, `PUT /profiles/{id}/note`, `PUT /config/*`, `POST /system/init`, `DELETE /system/pki`, `POST /server/configure` and `POST /server/process/{action}` return `409` (`"A backup restore is running"`).
|
||||
|
||||
| Method | Path | Purpose |
|
||||
|---|---|---|
|
||||
| GET, PUT | `/backup/settings` | encryption flag and passphrase, server name, default retention, local root, the implemented destination types with their fields |
|
||||
| GET, POST | `/backup/destinations` | list, create (`201`) |
|
||||
| PUT, DELETE | `/backup/destinations/{id}` | update, delete |
|
||||
| POST | `/backup/destinations/{id}/test` | check connection, write and delete (SFTP: shows the host key when it is not trusted) |
|
||||
| POST | `/backup/destinations/{id}/trust-host-key` | SFTP: pin the host key the administrator saw |
|
||||
| GET | `/backup/destinations/{id}/packages` | check the source and list the packages, newest first |
|
||||
| POST | `/backup/run` | start a backup (`202`) |
|
||||
| POST | `/backup/restore` | start a restore (`202`) |
|
||||
| GET | `/backup/status` | the current or last job |
|
||||
| GET | `/backup/history` | last runs (`limit`, default 20) |
|
||||
|
||||
### `GET /backup/settings`, `PUT /backup/settings`
|
||||
- **GET response**: `{"encryption_enabled": true, "default_retention": 14, "server_name": "vpn-main", "effective_server_name": "vpn-main", "server_name_source": "setting", "local_root": "/app/backups", "types": [{"id": "local", "label": "...", "remote": false, "pins_host_key": false, "fields": [...]}, ...]}`. The passphrase is never returned. `server_name` is the configured name (`""` when none); `effective_server_name` is the name used in package names and `server_name_source` says where it comes from: `setting`, `public_ip` (the address of the VPN settings) or `hostname`. A field of `fields` has `name`, `label`, `kind` (`text`, `number`, `bool`, `secret`, `secret_multiline`), `required`, `default`, optional `hint` and `warning` + `warn_if` (the warning applies while the value equals `warn_if`).
|
||||
- **PUT body**: `{"passphrase": "..."}` (at least 8 characters) sets or changes it; `{"clear_passphrase": true}` removes it (`400` while an enabled remote destination exists); `{"default_retention": 14}`; `{"server_name": "vpn-main"}` (`^[A-Za-z0-9][A-Za-z0-9.-]{0,62}$`, else `400`; `""` clears it).
|
||||
|
||||
### Destinations
|
||||
- **Body (POST, PUT)**: `{"name": "offsite", "type": "s3", "enabled": true, "retention_count": 14, "params": {...}, "secrets": {...}}`. `type` must be an implemented one (`local`, `s3`, `sftp`, `ftp`), otherwise `400`.
|
||||
- `local`: `params: {"folder": "daily"}`, no secrets.
|
||||
- `s3`: `params: {"endpoint": "s3.example.com", "secure": true, "region": "", "bucket": "name", "prefix": "ovpmon/"}`, `secrets: {"access_key": "...", "secret_key": "..."}`.
|
||||
- `sftp`: `params: {"host": "files.example.com", "port": 22, "username": "backup", "directory": "ovpmon/daily"}`, `secrets: {"password": "..."}` **or** `{"private_key": "<key text>", "key_passphrase": "..."}` (not both). `params` also carries `host_key` and `host_key_type` once a key is trusted; they are set only by `trust-host-key` (ignored in the body, kept on `PUT` while `host` and `port` stay the same, cleared when one of them changes).
|
||||
- `ftp`: `params: {"host": "ftp.example.com", "port": 21, "username": "backup", "directory": "ovpmon/daily", "tls": true, "verify_cert": true, "passive": true}`, `secrets: {"password": "..."}`.
|
||||
- `directory` (SFTP, FTP): relative, letters, digits, `.`, `_`, `-`, no `..`, at most 4 levels.
|
||||
- **Response**: the destination with `secrets` masked (`"********"` for each secret that is set), `last_status`, `last_message`, `last_at`. On `PUT`, a secret that is missing, empty or `"********"` keeps the stored value.
|
||||
- **Test response**: `{"ok": true, "message": "..."}` (`ok: false` carries the reason). For an SFTP destination whose host key is not trusted (or changed): `{"ok": false, "message": "...", "needs_trust": true, "fingerprint": "SHA256:...", "key_type": "ssh-ed25519", "key_changed": false}`.
|
||||
|
||||
### `POST /backup/destinations/{id}/trust-host-key`
|
||||
- **Body**: `{"fingerprint": "SHA256:..."}`: the one shown by Test. The server connects again (no credentials are sent) and pins the key only if it shows exactly that fingerprint; otherwise `400` ("run Test again"). Allowed for `sftp` destinations only (`400` otherwise); `409` while a job runs; `502` when the server cannot be reached.
|
||||
- **Response**: the updated destination (`params.host_key` set).
|
||||
- Until a key is trusted, SFTP backup, listing, restore and delete are refused (`502`, "The host key of the server is not trusted yet"); on a mismatch the connection is refused.
|
||||
|
||||
### `GET /backup/destinations/{id}/packages`
|
||||
- **Response**: `{"packages": [{"name": "ovpmon-backup_vpn-main_20261007T101500Z.ovpbak.enc", "server_name": "vpn-main", "created_at": "2026-10-07T10:15:00Z", "size": 123456, "encrypted": true}]}`, newest first (time, then the `-2`, `-3` suffix). `created_at` is UTC and comes from the file name. `502` when the source cannot be read.
|
||||
|
||||
### `POST /backup/run`
|
||||
- **Body (optional)**: `{"destination_ids": [1, 2]}`; without it all enabled destinations are used.
|
||||
- **Response `400`**: nothing selected, a disabled destination, or a remote destination without a passphrase.
|
||||
|
||||
### `POST /backup/restore`
|
||||
- **Body**: `{"destination_id": 1, "package": "<name from the listing>", "passphrase": "..."}`. The name is checked against the pattern and must be in the destination's listing; paths are never accepted. The passphrase is required for `.enc` packages.
|
||||
- **Response `409`**: a job or an initialization of the PKI is running.
|
||||
|
||||
### `GET /backup/status`
|
||||
- **Response**: `{"kind": "backup|restore|null", "state": "idle|running|done|partial|error", "stages": [{"name": "upload", "state": "pending|running|done|error"}], "results": [{"destination_id": 1, "name": "...", "state": "pending|running|ok|error|skipped", "message": "..."}], "warnings": [], "message": "...", "relogin": false, "started_at": "...", "finished_at": null}`.
|
||||
- Backup stages: `package`, `encrypt` (only with a passphrase), `upload`. Restore stages: `download`, `decrypt`, `verify`, `prepare`, `safety_backup`, `stop_openvpn`, `replace`, `finalize`. `partial`: stored in some destinations only. `relogin` is true after a successful restore. The state is kept in memory (single Profiler process); the history is kept in `ovpmon_backup.db`.
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
# Backup and Restore
|
||||
|
||||
Page **Management > Backup and Restore** in the web UI (API: [Profiler API, section 4](API_Reference.md)). It makes a package of the application data, sends it to one or more destinations and restores from it, also **on another server** and from containers to system services and back.
|
||||
|
||||
It is not the same as `deploy/docker/backup.sh` and `deploy/native/backup.sh`: those copy whole volumes or directories before an update and run from the command line. This function works on the level of the application data from the UI, whatever the installation method.
|
||||
|
||||
> Status: destinations **Local folder**, **S3**, **SFTP** and **FTP/FTPS** work. **SMB is coming in a later pass.** There is no schedule yet: a backup is started by hand.
|
||||
|
||||
## What is in a package
|
||||
|
||||
| In the package | Notes |
|
||||
|---|---|
|
||||
| monitoring database | statistics, administrator accounts, 2FA (consistent online copy, no downtime) |
|
||||
| profiler database | profiles, notes, server and PKI settings (consistent online copy) |
|
||||
| `pki/` | CA, server and client keys and certificates, CRL, `ta.key`, `dh.pem`. **Secret.** |
|
||||
| client `.ovpn` files | the issued profiles |
|
||||
| `manifest.json` | format version, time (UTC, milliseconds), server name, host name, container or host, schema versions of both databases, SHA-256 of every file |
|
||||
|
||||
**Not in the package, on purpose:** `server.conf` (generated again from the settings), the JWT signing key and the environment file (each server has its own), the TLS certificate of the web interface, logs, and the backup destinations with their secrets (see [Moving to another server](#moving-to-another-server)).
|
||||
|
||||
A package is a `tar.gz` named `ovpmon-backup_<server-name>_<YYYYMMDDTHHMMSS>Z.ovpbak`, with `.enc` added when it is encrypted. The time is UTC, to the second, for example `ovpmon-backup_vpn-main_20261007T101500Z.ovpbak.enc`. If a destination already holds a package of the same second, `-2`, `-3` ... is added after the `Z`; an existing file is never overwritten. Only files with such a name are listed, restored and rotated; everything else in a destination is ignored. Packages of the first pass (the host name in place of the server name) stay listed and restorable.
|
||||
|
||||
### Server name
|
||||
|
||||
The **Server name** field is in the Backup panel of the page (letters, digits, `.` and `-`, up to 63 characters, starting with a letter or digit; API: `server_name` of `PUT /backup/settings`). The page shows the name that will really be used. If no name is set, the **public address** from the VPN settings is used, and if there is none, the **host name** (in a container this is a random identifier, so set a name). The name is stored in `ovpmon_backup.db`, not in the package and not in the profiler database: after a move to another server it is set again.
|
||||
|
||||
## Encryption
|
||||
|
||||
A package holds the private key of the CA and the password hashes. Set a **passphrase** on the page (at least 8 characters): packages are then encrypted with AES-256-GCM, the key is derived from the passphrase with scrypt.
|
||||
|
||||
- Remote destinations (S3, SFTP, FTP and later SMB) **refuse to work without a passphrase** (the backup is rejected with an error).
|
||||
- A local folder works without it; the page shows a warning. Folders are created with mode 700 and files with 600.
|
||||
- The passphrase is stored on the server encrypted with a key derived from the JWT signing key, and never shown again. If the signing key is changed, enter the passphrase and the destination secrets again.
|
||||
- Changing the passphrase does not touch old packages: each one keeps the passphrase it was made with. At restore the passphrase is typed in by hand. **Without it an encrypted package cannot be opened.**
|
||||
|
||||
## Destinations
|
||||
|
||||
A destination is a named entry: type, parameters, secrets, enabled flag, number of copies to keep (default 14). **Backup now** sends the package to all ticked destinations; each result is shown separately, and a failure of one destination does not stop the others. Secrets are never returned by the API (the page shows them as `********`); leave a secret field empty when editing to keep it. Use **Test** to check the connection, writing and deleting.
|
||||
|
||||
| Type | Parameters | Notes |
|
||||
|---|---|---|
|
||||
| Local folder | folder | a sub folder inside the backup root; paths outside the root and symbolic links are refused |
|
||||
| S3 | endpoint (`host[:port]`, without `https://`), TLS on/off, region (optional), bucket, prefix (optional), access key, secret key | AWS S3 or a compatible store (Python library `minio`). The bucket must exist; it is never created. The key needs to list, write, read and delete in the bucket or prefix |
|
||||
| SFTP | host, port (22), user, directory, **password or private key** (+ passphrase of the key) | Python library `paramiko`; see [SFTP](#sftp-and-the-host-key) |
|
||||
| FTP / FTPS | host, port (21), user, directory, TLS (explicit FTPS, **on**), verify the certificate (**on**), passive mode (**on**), password | Python library `ftplib`; see [FTP](#ftp-and-ftps) |
|
||||
|
||||
Both SFTP and FTP: the **directory** is relative to the login directory of the user and checked like the local folder (letters, digits, `.`, `_`, `-`, no `..`, at most 4 levels; it is created if missing); a package is first written as `.<name>.part` and renamed when complete, so a broken transfer never leaves a package-looking file; only files with our package name are listed; connection timeout 15 s, a transfer waits up to 120 s for data; errors are shown as text without secrets. Secrets (password, private key, passphrase) are encrypted at rest and shown as `********`.
|
||||
|
||||
### SFTP and the host key
|
||||
|
||||
The server is identified by the **SHA-256 fingerprint of its SSH host key**, which is pinned:
|
||||
|
||||
1. Add the destination and press **Test**. The server is not trusted yet, so the page shows the key type and fingerprint and a **Trust** button (nothing was sent to the server, not even the password). Compare the fingerprint with the one you know (`ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` on the server).
|
||||
2. **Trust** saves the fingerprint in the destination (`POST /backup/destinations/{id}/trust-host-key`; the server checks that it still shows the same key).
|
||||
3. From now on every connection must present exactly that key. **Backup, listing, restore and delete are refused while no key is trusted**, and on a mismatch the connection is dropped before any credentials are sent. If the key changed (server reinstalled), **Test** shows the new fingerprint with a warning and offers to trust it again.
|
||||
|
||||
Unknown keys are never added automatically. Changing the host or the port clears the trusted key. Authentication by key: paste the private key text (RSA, ECDSA or Ed25519 in OpenSSH or PEM format) and, if the key is encrypted, its passphrase. Use a key that is allowed to write only into the backup directory.
|
||||
|
||||
### FTP and FTPS
|
||||
|
||||
- **TLS** (explicit FTPS, `AUTH TLS`) is on by default, and so is the **verification of the server certificate**. A server with a self-signed certificate needs the verification switched off explicitly; the page warns about that.
|
||||
- **Without TLS** the password and the packages travel in clear text; the page warns about that and the destination list shows a badge. Use plain FTP only inside a trusted network.
|
||||
- **Passive mode** is on by default (needed behind NAT and in containers).
|
||||
- The server should support `MLSD` or `NLST` (list), `SIZE` and `RNFR/RNTO` (rename).
|
||||
|
||||
The **backup root** of local destinations is `/var/lib/ovpmon/backups` in system-service installs and `/app/backups` in containers (volume `ovp_backups`). Change it with `OVPMON_BACKUP_LOCAL_ROOT`.
|
||||
|
||||
**Rotation.** After a successful upload the oldest packages beyond "copies to keep" are deleted. Only packages of our name pattern **with the same server name** in the same folder are considered, so servers with different names that share a folder do not delete each other's packages (servers with the **same** name in one folder do rotate each other: give every server its own name). Packages with another name stay: those made before the name was changed, and the first-pass packages named by host name.
|
||||
|
||||
## Make a backup
|
||||
|
||||
1. Add a destination and press **Test**.
|
||||
2. For a remote destination set the passphrase first.
|
||||
3. Tick the destinations and press **Backup now**. The progress and the result of every destination appear below; the history keeps the last runs.
|
||||
|
||||
Only one backup or restore runs at a time (a second start is rejected with `409`).
|
||||
|
||||
## Restore
|
||||
|
||||
1. **Source**: pick a destination. The page checks it (connection, read access) and finds the packages.
|
||||
2. **Package**: the list shows the server name, the time in UTC and in the local time of your browser, the size and whether the package is encrypted, newest first.
|
||||
3. Type the passphrase if the package is encrypted.
|
||||
4. Press the red **Restore** button and confirm. The confirmation lists what is replaced.
|
||||
|
||||
What the server does:
|
||||
|
||||
1. Downloads the package, decrypts it, checks `manifest.json` and the SHA-256 of every file.
|
||||
2. Unpacks it safely: only the expected top-level names are accepted; absolute paths, `..`, links, devices and oversized content are rejected.
|
||||
3. Refuses a package with an unknown format or a **newer database schema** than this release knows. A package with an **older** schema is accepted and migrated (see below).
|
||||
4. Checks the databases and migrates them **on the unpacked copies**, before anything is changed.
|
||||
5. Saves the **current state** as a safety copy in `<backup root>/pre-restore/` (the last 5 are kept, encrypted if a passphrase is set). **If this fails, the restore does not start.**
|
||||
6. Stops OpenVPN if it runs, replaces the databases (atomic file replace), the PKI and the client profiles. If any replacement fails, everything is put back.
|
||||
7. Generates `server.conf` and publishes the CRL like **Apply Configuration** on the VPN page, then starts OpenVPN again if it was running.
|
||||
|
||||
While a restore runs, requests that change the PKI, profiles, settings or the OpenVPN process return `409`. When it is done, the page offers to log in again: the accounts now come from the package. Clients are disconnected during the restart of OpenVPN.
|
||||
|
||||
**To undo a restore**, restore the package from `pre-restore` (add a Local destination with the folder `pre-restore` and pick the package there).
|
||||
|
||||
### Migration of the monitoring database
|
||||
|
||||
The migrations of the monitoring database live in `APP_CORE`. The profiler runs its own migrations in-process. For the monitoring database it calls `migrate.py` on the unpacked copy, so the database is already migrated when it is put in place; a package with an older schema (also one from an older release) is therefore restored in every installation method. The code is found next to `APP_PROFILER` (system services, all-in-one container `/app/APP_CORE`) or in the directory set by `OVPMON_CORE_DIR` (the profiler image of the one-container-per-component variant: `/opt/core`, which holds `migrations.py`, `migrate.py` and `db.py` of `APP_CORE`; they use only the Python standard library). The profiler image gets them at build time through the build context `core` (`additional_contexts` in `docker-compose.yml`, **docker compose 2.17 or newer**; the all-in-one and system-service installs need nothing extra).
|
||||
|
||||
An image built before this change has no such directory. Then a package is accepted only if its monitoring schema version equals the one of the running installation, and otherwise the restore is refused with a clear message and nothing is changed: rebuild the profiler image.
|
||||
|
||||
## Moving to another server
|
||||
|
||||
1. Install the application on the new server (any method), log in once with the initial administrator.
|
||||
2. Add a destination that points to the same storage (S3 bucket with the same keys, the same SFTP or FTP directory, or a copy of the local folder; an SFTP host key is trusted again on the new server). **Destination settings and secrets do not travel inside the package**: enter them again on the new server. Copy the packages into the new server's backup root if you use a local destination.
|
||||
3. Set up the same passphrase (only needed for new backups) and restore: pick the source and the package, type the package passphrase.
|
||||
4. Log in again with the account of the old server.
|
||||
5. Set the **server name** of the new server on the Backup and Restore page (it is not part of the package). Open **VPN** and check the server address (`remote`/public IP): it comes from the package and points to the old server unless you change it. Apply the configuration if you change it; client profiles already issued keep the old address and have to be reissued.
|
||||
|
||||
The package format does not depend on the installation method: containers (variants A and B) and system services (Alpine, Debian, Ubuntu) are interchangeable. Release rule: the new server must run the same or a newer release than the one that made the package.
|
||||
|
||||
## Settings (environment)
|
||||
|
||||
| Variable | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `OVPMON_BACKUP_LOCAL_ROOT` | `/var/lib/ovpmon/backups` (containers: `/app/backups`) | root of the local destinations |
|
||||
| `OVPMON_BACKUP_WORK_DIR` | `<root>/.work` | temporary files of a job; needs room for about two copies of the data |
|
||||
| `OVPMON_BACKUP_MAX_UNPACKED_BYTES` | 20 GiB | size cap of an unpacked package |
|
||||
| `OVPMON_CORE_DIR` | `APP_CORE` next to `APP_PROFILER` (profiler image: `/opt/core`) | where `migrate.py`, `migrations.py` and `db.py` of the monitoring component are |
|
||||
|
||||
Settings, destinations and history are in their own SQLite file `ovpmon_backup.db` next to the profiler database. A restore replaces the two application databases but never this file.
|
||||
@@ -11,6 +11,7 @@ Three levels: **general information** about the project, **installation methods*
|
||||
| install with Docker | [Containers](Deployment/Containers/README.md) |
|
||||
| install on Alpine, Debian or Ubuntu without containers | [System services](Deployment/System_Services/README.md) |
|
||||
| update, back up, restore or roll back | containers: [Operations](Deployment/Containers/Operations.md) · system services: [Operations](Deployment/System_Services/Operations.md) |
|
||||
| back up to a folder, S3, SFTP or FTP, restore, move to another server | [Backup and Restore](Profiler_Management/Backup_Restore.md) |
|
||||
| change settings (environment, secrets, ports) | [General: Configuration](General/Configuration.md) |
|
||||
| fix a problem | containers: [Troubleshooting](Deployment/Containers/Troubleshooting.md) · system services: [Troubleshooting](Deployment/System_Services/Troubleshooting.md) |
|
||||
| set up NAT, TLS, the web UI build | [Firewall](Deployment/System_Services/Firewall.md) · [Nginx](Deployment/System_Services/Nginx_Configuration.md) · [Web UI](Deployment/System_Services/Web_UI.md) |
|
||||
|
||||
@@ -15,6 +15,17 @@ The frontend is a Single Page Application (SPA) built with **Vue 3** and **Vite*
|
||||
- **Real-Time Data**: Polls the Monitoring API (`APP_CORE`) for live statistics.
|
||||
- **Authentication**: JWT-based auth flow with support for 2FA.
|
||||
|
||||
## Pages
|
||||
|
||||
| Route | View | Purpose |
|
||||
|---|---|---|
|
||||
| `/` | `Analytics.vue` | traffic charts |
|
||||
| `/clients`, `/certificates` | `Clients.vue`, `Certificates.vue` | connected clients, issued profiles |
|
||||
| `/config/pki`, `/config/vpn` | `PKIConfig.vue`, `VPNConfig.vue` | PKI and server settings |
|
||||
| `/server` | `ServerManagement.vue` | OpenVPN process control |
|
||||
| `/backup` | `BackupRestore.vue` | **Backup and Restore** (MANAGEMENT section): destinations table with an add/edit modal (the form is built from the `fields` of `GET /backup/settings`: text, number, switch, password and multi-line secret fields; a field may carry a warning, for example plain FTP or a disabled certificate check; types with a pinned host key (SFTP) show it, and **Test** opens a confirmation with the fingerprint and a Trust button), backup panel (encryption status, **server name** field with the name actually used, destination checkboxes, progress per destination, history), restore panel (source, package list with the server name and the time in UTC and in the browser's local time, passphrase, red Restore button with a confirmation). It polls `GET /backup/status` every 2 s while a job runs. See [Backup and Restore](../Profiler_Management/Backup_Restore.md) |
|
||||
| `/account` | `Account.vue` | password, username, 2FA |
|
||||
|
||||
## Configuration
|
||||
Run-time configuration is loaded from `/public/config.json`. This allows the Vue app to be built once and deployed to any environment.
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ Optional: NAT, MSS clamping and TTL for the VPN clients on system-service hosts:
|
||||
| General information | [Overview](DOCS/General/Overview.md) · [Configuration](DOCS/General/Configuration.md) · [Security architecture](DOCS/General/Security_Architecture.md) · [Database migrations](DOCS/General/Database_Migrations.md) |
|
||||
| Installation methods | [Choose a method](DOCS/Deployment/README.md) · [First steps](DOCS/Deployment/First_Steps.md) |
|
||||
| Details per method | [Containers](DOCS/Deployment/Containers/README.md) (operations, reference, troubleshooting) · [System services](DOCS/Deployment/System_Services/README.md) (operations, reference, web UI, firewall, nginx, troubleshooting) |
|
||||
| Backup and restore | [Backup and Restore](DOCS/Profiler_Management/Backup_Restore.md) (UI and API; destinations: local, S3, SFTP, FTP; encryption, moving to another server) |
|
||||
| APIs | [Monitoring](DOCS/Core_Monitoring/API_Reference.md) · [Profiler](DOCS/Profiler_Management/API_Reference.md) · [UI](DOCS/UI/Architecture.md) |
|
||||
| Changes | [Changes and results](DOCS/Changes/README.md) |
|
||||
| Code review | [DOCS/code_review/](DOCS/code_review/2026-10-05_1607Z_Codebase_Analysis.md) (state of the code, risks, recommendations; time-stamped) |
|
||||
|
||||
@@ -55,14 +55,15 @@ RUN rm -f /etc/nginx/http.d/default.conf \
|
||||
COPY deploy/allinone/supervisord.conf /etc/supervisord.conf
|
||||
COPY deploy/allinone/entrypoint.sh /usr/local/bin/ovpmon-entrypoint.sh
|
||||
|
||||
# Mount points of the five named volumes
|
||||
# Mount points of the five data volumes and of the backup packages volume (ovp_backups)
|
||||
RUN chmod +x /usr/local/bin/ovpmon-entrypoint.sh \
|
||||
&& mkdir -p /app/db /app/easy-rsa /app/client-config /etc/openvpn /var/log/openvpn
|
||||
&& 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)
|
||||
ENV OVPMON_PROFILER_DB_PATH=/app/db/ovpn_profiler.db \
|
||||
OVPMON_OPENVPN_MONITOR_DB_PATH=/app/db/openvpn_monitor.db \
|
||||
OVPMON_OPENVPN_MONITOR_LOG_PATH=/var/log/openvpn/openvpn-status.log
|
||||
OVPMON_OPENVPN_MONITOR_LOG_PATH=/var/log/openvpn/openvpn-status.log \
|
||||
OVPMON_BACKUP_LOCAL_ROOT=/app/backups
|
||||
|
||||
EXPOSE 80
|
||||
EXPOSE 1194/udp
|
||||
|
||||
@@ -1 +1 @@
|
||||
39d777d3a2df602f7ce737dd7fe333c29695557053b85cba7f3b3d8c367ec20b
|
||||
796072800fd2abd0a674c02ef1c626b796e587b263818d13f1159561c7a7d724
|
||||
+1
-1
@@ -1 +1 @@
|
||||
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-DQu6UtRL.js";import{S as O}from"./vendor-ui-jlFFG6nm.js";import{a as te,_ as re}from"./ConfirmModal-likdDJzi.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
|
||||
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
|
||||
+1
-1
@@ -1 +1 @@
|
||||
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-DQu6UtRL.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
|
||||
import{r as _,a as U,o as G,u as Z,b as q,c as r,d as t,t as i,e as I,f as J,g as f,w as z,v as K,h as Q,F as E,i as j,j as Y,k as d,n as $}from"./index-BsVv6gaD.js";import{C as H}from"./vendor-charts-Bcjh2pZL.js";import"./vendor-ui-jlFFG6nm.js";const tt={class:"kpi-grid mb-4"},et={class:"stat-item"},st={class:"stat-content"},at={class:"stat-item"},ot={class:"stat-content"},lt={class:"stat-item"},nt={class:"stat-content"},it={class:"card mb-4"},rt={class:"card-header d-flex justify-content-between align-items-center flex-wrap"},dt={class:"chart-header-controls"},ct={class:"d-flex align-items-center"},ut={class:"toggle-wrapper me-2"},mt={class:"toggle-switch"},ft={class:"card-body"},pt={class:"chart-container"},vt={class:"row"},ht={class:"col-lg-7"},_t={class:"card"},gt={class:"card-body p-0"},bt={class:"table-responsive"},xt={class:"table"},yt={key:0},Ct={key:1},kt={class:"user-select-all fw-bold",style:{color:"var(--text-heading)"}},wt={class:"font-monospace text-muted"},St={class:"d-flex align-items-center"},Rt={class:"progress flex-grow-1",style:{height:"6px"}},Tt={class:"ms-2 small text-muted w-25 text-end"},At={class:"col-lg-5"},Dt={class:"card mb-4"},Mt={class:"card-body p-3",style:{"min-height":"120px","max-height":"200px","overflow-y":"auto"}},Et={key:0,class:"text-muted text-center py-3 mb-0"},Nt={key:1,class:"text-muted text-center py-3 mb-0"},Lt={key:2,class:"list-group list-group-flush"},Bt={class:"fw-bold small"},Ut={class:"text-muted",style:{"font-size":"0.75rem"}},It={class:"badge status-warning text-dark"},zt={class:"card"},jt={class:"card-body d-flex align-items-center justify-content-around p-4",style:{"min-height":"200px"}},Ht={class:"pie-container",style:{width:"140px",height:"140px",flex:"0 0 auto"}},Ot={class:"ms-3 flex-grow-1"},Vt={class:"mb-3"},Ft={class:"h5 mb-0",style:{color:"var(--text-heading)"}},Pt={class:"h5 mb-0",style:{color:"var(--text-heading)"}},Wt=96,Jt={__name:"Analytics",setup(Xt){const{fetchAnalytics:O,fetchCertificates:V}=Y(),{formatBytes:C,parseServerDate:F}=J(),{config:P}=Z(),w=_(null),S=_(null);let g=null,b=null;const p=U({analytics:!0,certs:!0}),x=_("24h"),y=_(!1),o=U({concurrentUsers:"-",totalTraffic:0,expiringCerts:"-",totalReceived:0,totalSent:0,totalReceivedString:"-",totalSentString:"-"}),R=_([]),T=_([]);let N=null;const A=async()=>{p.analytics=!0;try{const a=await O(x.value);a.success&&W(a.data)}catch(a){console.error(a)}finally{p.analytics=!1}},L=async()=>{p.certs=!0;try{const a=await V();if(a.success&&Array.isArray(a.data)){const e=a.data.filter(s=>!s.is_revoked&&!s.is_expired&&s.days_remaining!==null&&s.days_remaining<=45);o.expiringCerts=e.length,T.value=e.sort((s,n)=>(s.days_remaining||0)-(n.days_remaining||0))}}catch(a){console.error(a)}finally{p.certs=!1}},W=a=>{o.concurrentUsers=a.max_concurrent_24h||0;const e=a.traffic_distribution||{rx:0,tx:0};o.totalReceived=Number(e.rx||0),o.totalSent=Number(e.tx||0),o.totalTraffic=o.totalReceived+o.totalSent,o.totalReceivedString=C(o.totalReceived),o.totalSentString=C(o.totalSent),R.value=(a.top_clients_24h||[]).map(s=>({name:s.common_name,total:Number(s.total_traffic||0),percent:o.totalTraffic>0?(Number(s.total_traffic)/o.totalTraffic*100).toFixed(1):0})),N=a.global_history_24h||[],D(),B()},D=()=>{if(!w.value)return;g&&g.destroy();const a=X(N,Wt),e=[],s=[],n=[];a.forEach(c=>{const m=F(c.timestamp);let u="";x.value.includes("h")||x.value==="1d"?u=m.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):u=m.toLocaleDateString([],{month:"short",day:"numeric"})+" "+m.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),e.push(u),y.value?(s.push(c.rx_rate_mbps||0),n.push(c.tx_rate_mbps||0)):(s.push(c.bytes_received/(1024*1024)),n.push(c.bytes_sent/(1024*1024)))});const l=document.documentElement.getAttribute("data-theme")==="dark",v=l?"rgba(240, 246, 252, 0.1)":"rgba(0,0,0,0.05)",h=l?"#8b949e":"#6c757d",k=w.value.getContext("2d");g=new H(k,{type:"line",data:{labels:e,datasets:[{label:y.value?"RX Mbps":"Received (MB)",data:s,borderColor:"#1652B8",backgroundColor:"rgba(22, 82, 184, 0.15)",borderWidth:2,fill:!0,tension:.3,pointRadius:3,pointHoverRadius:4},{label:y.value?"TX Mbps":"Sent (MB)",data:n,borderColor:"#EC7C31",backgroundColor:"rgba(236, 124, 49, 0.15)",borderWidth:2,fill:!0,tension:.3,pointRadius:3,pointHoverRadius:4}]},options:{responsive:!0,maintainAspectRatio:!1,interaction:{mode:"index",intersect:!1},plugins:{legend:{labels:{color:h}}},scales:{x:{ticks:{color:h,maxTicksLimit:8},grid:{color:v}},y:{beginAtZero:!0,ticks:{color:h},grid:{color:v}}}}})},B=()=>{if(!S.value)return;b&&b.destroy();const a=S.value.getContext("2d"),s=document.documentElement.getAttribute("data-theme")==="dark"?"#161b22":"#ffffff";b=new H(a,{type:"doughnut",data:{labels:["Received","Sent"],datasets:[{data:[o.totalReceived,o.totalSent],backgroundColor:["#1652B8","#EC7C31"],borderColor:s,borderWidth:2,hoverOffset:4}]},options:{responsive:!0,maintainAspectRatio:!1,cutout:"70%",plugins:{legend:{display:!1}}}})},X=(a,e)=>{if(!a||a.lLine truncated
|
||||
@@ -0,0 +1,15 @@
|
||||
import{r as v,a as 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
-1
@@ -1 +1 @@
|
||||
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-DQu6UtRL.js";import{_ as J,a as ce}from"./ConfirmModal-likdDJzi.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
|
||||
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{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};
|
||||
@@ -1 +0,0 @@
|
||||
import{M as B}from"./vendor-ui-jlFFG6nm.js";import{r as o,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 _,T as z,t as p,m as y}from"./index-DQu6UtRL.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,t=b,s=o(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",()=>{t("opened")}),s.value.addEventListener("hidden.bs.modal",()=>{t("closed"),t("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,[_(n.$slots,"header",{},()=>[e("h5",N,p(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,[_(n.$slots,"body")]),n.$slots.footer?(u(),k("div",V,[_(n.$slots,"footer")])):w("",!0)])],2)],8,T)]))}},A={class:"text-main"},j={__name:"ConfirmModal",emits:["confirm"],setup(d,{expose:f,emit:b}){const v=b,t=o(null),s=o(""),a=o(""),i=o("Confirm"),c=o("btn-action-danger"),r=o(!0),n=o(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,t.value.show()},h=()=>{t.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:t},{body:y(()=>[e("p",A,p(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},p(i.value),3)]),_:1},8,["title"]))}};export{q as _,j as a};
|
||||
+1
-1
@@ -1 +1 @@
|
||||
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-DQu6UtRL.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
|
||||
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
|
||||
+1
-1
@@ -1 +1 @@
|
||||
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-DQu6UtRL.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};
|
||||
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};
|
||||
+1
-1
@@ -1 +1 @@
|
||||
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-DQu6UtRL.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
|
||||
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
|
||||
@@ -0,0 +1,7 @@
|
||||
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
|
||||
@@ -1,7 +0,0 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Analytics-CE9OWhfn.js","assets/vendor-charts-Bcjh2pZL.js","assets/vendor-ui-jlFFG6nm.js","assets/Certificates-DL4-OpRZ.js","assets/ConfirmModal-likdDJzi.js","assets/PKIConfig-CJEinDsL.js","assets/VPNConfig-cSWblOqw.js","assets/ServerManagement-DWxVTYxH.js","assets/Account-B9jhwMBa.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=[],mn=()=>{},Gu=()=>!1,Ni=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,Ne=(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"),ki=e=>{const t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},um=/-\w/g,zt=ki(e=>e.replace(um,t=>t.slice(1).toUpperCase())),fm=/\B([A-Z])/g,qn=ki(e=>e.replace(fm,"-$1").toLowerCase()),Ii=ki(e=>e.charAt(0).toUpperCase()+e.slice(1)),No=ki(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[ko(s,o)+" =>"]=r,n),{})}:zs(t)?{[`Set(${t.size})`]:[...t.values()].map(n=>ko(n))}:Zt(t)?ko(t):$e(t)&&!oe(t)&&!Yu(t)?String(t):t,ko=(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 Nt=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}};Nt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);S.reduceDescriptors(Nt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(s){this[n]=s}}});S.freezeMethods(Nt);function qo(e,t){const n=this||Mr,s=t||n,r=Nt.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 Nt?{...e}:e;function ps(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=ps({},e);let{data:n,withXSRFToken:s,xsrfHeaderName:r,xsrfCookieName:o,headers:l,auth:c}=t;if(t.headers=l=Nt.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 Nd={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=Nt.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),Nd.getAdapter(e.adapter||Mr.adapter,e)(e).then(function(s){return Wo(e),s.data=qo.call(e,e.transformResponse,s),s.headers=Nt.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=Nt.from(s.response.headers))),Promise.reject(s)})}const kd="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"+kd+"] 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 ds=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=ps(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=Nt.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=ps(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){ds.prototype[t]=function(n,s){return this.request(ps(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(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 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 ds(e),n=fd(ds.prototype.request,t);return S.extend(n,ds.prototype,t,{allOwnKeys:!0}),S.extend(n,t,null,{allOwnKeys:!0}),n.create=function(r){return Ld(ps(e,r))},n}const Ke=Ld(Mr);Ke.Axios=ds;Ke.CanceledError=Js;Ke.CancelToken=gv;Ke.isCancel=Sd;Ke.VERSION=kd;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=ps;Ke.AxiosH
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
|
||||
@@ -6,10 +6,10 @@
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>OpenVPN Controller</title>
|
||||
<script type="module" crossorigin src="/assets/index-DQu6UtRL.js"></script>
|
||||
<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-Mq5XawTO.css">
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-b8NXKHGm.css">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
@@ -6,8 +6,10 @@
|
||||
# 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
|
||||
# container names (ovp-*): run only ONE variant per host. Both use the same five volumes with the
|
||||
# container names (ovp-*): run only ONE variant per host. Both use the same five data volumes with the
|
||||
# same in-container paths, so backups are identical and data of one variant can be used by the other.
|
||||
# The sixth volume ovp_backups (local packages of the Backup and Restore page) is not a data volume:
|
||||
# deploy/docker backup.sh and update.sh do not copy it.
|
||||
|
||||
services:
|
||||
ovpmon:
|
||||
@@ -33,12 +35,14 @@ services:
|
||||
- ovp_pki:/app/easy-rsa
|
||||
- ovp_client_config:/app/client-config
|
||||
- db_data:/app/db
|
||||
- ovp_backups:/app/backups
|
||||
environment:
|
||||
OVPMON_API_SECRET_KEY: ${JWT_SECRET:?JWT_SECRET must be set in .env (openssl rand -hex 32)}
|
||||
OVPMON_API_PORT: 5001
|
||||
OVPMON_PROFILER_DB_PATH: /app/db/ovpn_profiler.db
|
||||
OVPMON_OPENVPN_MONITOR_DB_PATH: /app/db/openvpn_monitor.db
|
||||
OVPMON_OPENVPN_MONITOR_LOG_PATH: /var/log/openvpn/openvpn-status.log
|
||||
OVPMON_BACKUP_LOCAL_ROOT: /app/backups
|
||||
OVPMON_LOGGING_LEVEL: INFO
|
||||
# Initial admin: used only while the users table is empty (remove after first start)
|
||||
OVPMON_INITIAL_ADMIN_USER: ${OVPMON_INITIAL_ADMIN_USER:-}
|
||||
@@ -62,3 +66,4 @@ volumes:
|
||||
ovp_pki:
|
||||
ovp_client_config:
|
||||
db_data:
|
||||
ovp_backups:
|
||||
+9
-1
@@ -91,7 +91,11 @@ services:
|
||||
start_period: 30s
|
||||
|
||||
app-profiler:
|
||||
build: ./APP_PROFILER
|
||||
build:
|
||||
context: ./APP_PROFILER
|
||||
# Migration code of the monitoring database for the restore (docker compose 2.17 or newer)
|
||||
additional_contexts:
|
||||
core: ./APP_CORE
|
||||
container_name: ovp-profiler
|
||||
restart: unless-stopped
|
||||
cap_add:
|
||||
@@ -111,11 +115,14 @@ services:
|
||||
- db_data:/app/db
|
||||
- ovp_client_config:/app/client-config
|
||||
- ovp_pki:/app/easy-rsa
|
||||
# Local backup packages (Backup and Restore page); not part of deploy/docker backup.sh
|
||||
- ovp_backups:/app/backups
|
||||
networks:
|
||||
- ovp-net
|
||||
environment:
|
||||
<<: *jwt-secret
|
||||
OVPMON_PROFILER_DB_PATH: /app/db/ovpn_profiler.db
|
||||
OVPMON_BACKUP_LOCAL_ROOT: /app/backups
|
||||
OVPMON_CORS_ORIGINS: ${OVPMON_CORS_ORIGINS:-}
|
||||
healthcheck:
|
||||
# GET / of the FastAPI app must answer 200
|
||||
@@ -135,3 +142,4 @@ volumes:
|
||||
ovp_pki:
|
||||
ovp_client_config:
|
||||
db_data:
|
||||
ovp_backups:
|
||||
Reference in new issue
Block a user