diff --git a/.gitignore b/.gitignore index af04b45..5da1b0a 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,6 @@ deploy/native/ui-dist.tar.gz # Python caches (tests and compile steps create them inside the tree) __pycache__/ *.pyc + +# local development environment +venv/ diff --git a/APP_CORE/README.md b/APP_CORE/README.md index ac4e050..8a3ace0 100644 --- a/APP_CORE/README.md +++ b/APP_CORE/README.md @@ -13,6 +13,7 @@ The **Core Monitoring** module provides the backend logic for collecting, extrac - A background service/daemon. - Parses OpenVPN server logs (`status.log`). - Aggregates bandwidth usage into time-series tables (`usage_history`, `stats_hourly`, etc.). + - Several simultaneous sessions of one user (`duplicate-cn`) are one record: traffic, speed and history are summed per common name; a session is identified by `Client ID` (see `DOCS/Core_Monitoring/Data_Architecture.md`). ## Configuration diff --git a/APP_CORE/migrations.py b/APP_CORE/migrations.py index 4741fe0..5b31503 100644 --- a/APP_CORE/migrations.py +++ b/APP_CORE/migrations.py @@ -459,8 +459,17 @@ def _m001_baseline(conn): _ensure_column('users', 'is_2fa_enabled', 'INTEGER DEFAULT 0') +def _m002_session_id(conn): + """active_sessions.session_id: the Client ID of the session from the OpenVPN v2 status + (part of the gatherer's session key). NULL is allowed: rows of an old snapshot and a + status without the Client ID column.""" + if not any(row[1] == "session_id" for row in conn.execute("PRAGMA table_info(active_sessions)")): + conn.execute("ALTER TABLE active_sessions ADD COLUMN session_id TEXT") + + MIGRATIONS = [ Migration(1, "baseline", _m001_baseline), + Migration(2, "session_id", _m002_session_id), ] # No separate "fresh" schema: the baseline migration creates everything on a new database diff --git a/APP_CORE/openvpn_api_v3.py b/APP_CORE/openvpn_api_v3.py index 77f7edd..57f2cb3 100644 --- a/APP_CORE/openvpn_api_v3.py +++ b/APP_CORE/openvpn_api_v3.py @@ -29,6 +29,29 @@ app = Flask(__name__) # Cross-origin access is off by default (the UI is same-origin behind Nginx); allow extra origins via OVPMON_CORS_ORIGINS (comma-separated) CORS(app, resources={r"/api/*": {"origins": [o.strip() for o in os.getenv("OVPMON_CORS_ORIGINS", "").split(",") if o.strip()]}}, supports_credentials=True) +# Length of one bucket of the aggregate tables, seconds. The aggregates hold only bytes, so for periods +# longer than a day the speed is the bucket average: bytes * 8 / 1e6 / bucket duration. +BUCKET_SECONDS = { + 'stats_5min': 300, + 'stats_15min': 900, + 'stats_hourly': 3600, + 'stats_6h': 21600, + 'stats_daily': 86400, +} + + +def avg_rate_sql(table, bytes_expr, ts_expr): + """SQL expression of the average speed (Mbps) of a bucket of an aggregate table. + + The current (incomplete) bucket lasts min(bucket length, time since its start), at least 1 second; + timestamps of the aggregates are UTC. `table` is taken only from BUCKET_SECONDS (never user input), + the other arguments are fixed column expressions of the caller. + """ + seconds = BUCKET_SECONDS[table] + return (f"({bytes_expr}) * 8.0 / 1000000.0 / " + f"MAX(1, MIN({seconds}, CAST(strftime('%s', 'now') AS INTEGER) - CAST(strftime('%s', {ts_expr}) AS INTEGER)))") + + class OpenVPNAPI: def get_config_value(self, section, key, fallback=None): try: @@ -169,15 +192,20 @@ class OpenVPNAPI: c.total_bytes_received, c.total_bytes_sent, -- Пиковая скорость Download за последние 2 минуты - (SELECT MAX(uh.bytes_received_rate_mbps) - FROM usage_history uh - WHERE uh.client_id = c.id - AND uh.timestamp >= datetime('now', '-30 seconds')) as current_recv_rate, + -- (скорость пользователя = сумма по его сессиям на одной отметке времени) + (SELECT MAX(s.rate) FROM ( + SELECT SUM(uh.bytes_received_rate_mbps) as rate + FROM usage_history uh + WHERE uh.client_id = c.id + AND uh.timestamp >= datetime('now', '-30 seconds') + GROUP BY uh.timestamp) s) as current_recv_rate, -- Пиковая скорость Upload за последние 2 минуты - (SELECT MAX(uh.bytes_sent_rate_mbps) - FROM usage_history uh - WHERE uh.client_id = c.id - AND uh.timestamp >= datetime('now', '-30 seconds')) as current_sent_rate, + (SELECT MAX(s.rate) FROM ( + SELECT SUM(uh.bytes_sent_rate_mbps) as rate + FROM usage_history uh + WHERE uh.client_id = c.id + AND uh.timestamp >= datetime('now', '-30 seconds') + GROUP BY uh.timestamp) s) as current_sent_rate, strftime('%Y-%m-%d %H:%M:%S', c.updated_at) as last_updated FROM clients c ORDER BY c.status DESC, c.common_name @@ -288,17 +316,27 @@ class OpenVPNAPI: points_count = 96 if is_high_res: + # Внутренний запрос: сумма по сессиям на одной отметке времени + # (старые строки хранят по записи на сессию), внешний: MAX скорости в интервале query = f''' SELECT - datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch') as timestamp, - SUM(uh.bytes_received) as bytes_received, - SUM(uh.bytes_sent) as bytes_sent, - MAX(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps, - MAX(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps - FROM usage_history uh - JOIN clients c ON uh.client_id = c.id - WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ? - GROUP BY datetime((strftime('%s', uh.timestamp) / {interval}) * {interval}, 'unixepoch') + datetime((strftime('%s', u.timestamp) / {interval}) * {interval}, 'unixepoch') as timestamp, + SUM(u.bytes_received) as bytes_received, + SUM(u.bytes_sent) as bytes_sent, + MAX(u.bytes_received_rate_mbps) as bytes_received_rate_mbps, + MAX(u.bytes_sent_rate_mbps) as bytes_sent_rate_mbps + FROM ( + SELECT uh.timestamp as timestamp, + SUM(uh.bytes_received) as bytes_received, + SUM(uh.bytes_sent) as bytes_sent, + SUM(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps, + SUM(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps + FROM usage_history uh + JOIN clients c ON uh.client_id = c.id + WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ? + GROUP BY uh.timestamp + ) u + GROUP BY datetime((strftime('%s', u.timestamp) / {interval}) * {interval}, 'unixepoch') ORDER BY timestamp ASC ''' elif is_aggregated: @@ -307,8 +345,8 @@ class OpenVPNAPI: t.timestamp, t.bytes_received, t.bytes_sent, - 0 as bytes_received_rate_mbps, - 0 as bytes_sent_rate_mbps + {avg_rate_sql(target_table, 't.bytes_received', 't.timestamp')} as bytes_received_rate_mbps, + {avg_rate_sql(target_table, 't.bytes_sent', 't.timestamp')} as bytes_sent_rate_mbps FROM {target_table} t JOIN clients c ON t.client_id = c.id WHERE c.common_name = ? AND t.timestamp BETWEEN ? AND ? @@ -318,13 +356,14 @@ class OpenVPNAPI: query = f''' SELECT uh.timestamp, - uh.bytes_received, - uh.bytes_sent, - uh.bytes_received_rate_mbps, - uh.bytes_sent_rate_mbps + SUM(uh.bytes_received) as bytes_received, + SUM(uh.bytes_sent) as bytes_sent, + SUM(uh.bytes_received_rate_mbps) as bytes_received_rate_mbps, + SUM(uh.bytes_sent_rate_mbps) as bytes_sent_rate_mbps FROM usage_history uh JOIN clients c ON uh.client_id = c.id WHERE c.common_name = ? AND uh.timestamp BETWEEN ? AND ? + GROUP BY uh.timestamp ORDER BY uh.timestamp ASC ''' @@ -461,7 +500,8 @@ class OpenVPNAPI: if target_table == 'usage_history': rate_cols = "SUM(bytes_received_rate_mbps) as total_rx_rate, SUM(bytes_sent_rate_mbps) as total_tx_rate," else: - rate_cols = "0 as total_rx_rate, 0 as total_tx_rate," + rate_cols = (f"{avg_rate_sql(target_table, 'SUM(bytes_received)', 'timestamp')} as total_rx_rate, " + f"{avg_rate_sql(target_table, 'SUM(bytes_sent)', 'timestamp')} as total_tx_rate,") # Aggregation Query # Group by interval_seconds diff --git a/APP_CORE/openvpn_gatherer_v3.py b/APP_CORE/openvpn_gatherer_v3.py index 8f780b4..ce15450 100644 --- a/APP_CORE/openvpn_gatherer_v3.py +++ b/APP_CORE/openvpn_gatherer_v3.py @@ -135,7 +135,7 @@ class OpenVPNDataGatherer: self.ts_aggregator = TimeSeriesAggregator(self.db_manager.get_connection) # In-Memory Cache для отслеживания сессий: - # (CN, RealAddress, connected_since_ts) -> { + # (CN, Client ID или RealAddress, connected_since_ts) -> { # 'bytes_received', 'bytes_sent': счётчики на прошлом тике, # 'last_seen': строка времени, 'connected_since': строка UTC (начало сессии), # 'missing_ticks': сколько тиков подряд сессии нет в статусе (льготный период)} @@ -183,7 +183,7 @@ class OpenVPNDataGatherer: conn = self.db_manager.get_connection() try: rows = conn.execute( - 'SELECT common_name, real_address, bytes_received, bytes_sent, connected_since ' + 'SELECT common_name, real_address, bytes_received, bytes_sent, connected_since, session_id ' 'FROM active_sessions' ).fetchall() finally: @@ -192,10 +192,11 @@ class OpenVPNDataGatherer: self.logger.warning(f"Could not load active_sessions snapshot: {e}") return - for name, real_addr, rx, tx, since in rows: + for name, real_addr, rx, tx, since, session_id in rows: try: since_ts = calendar.timegm(time.strptime(str(since)[:19].replace('T', ' '), TS_FORMAT)) - self.baseline[(name, real_addr, since_ts)] = (int(rx), int(tx), self.started_at) + # Тот же ключ, что у сборщика; строки снимка без session_id совпадают по адресу + self.baseline[(name, session_id or real_addr, since_ts)] = (int(rx), int(tx), self.started_at) except (ValueError, TypeError): # Старый формат (локальное время первого наблюдения) - совпасть с ключом не может continue @@ -382,7 +383,14 @@ class OpenVPNDataGatherer: status_time = None clients = [] + # Индекс колонки Client ID в строках CLIENT_LIST (None = в статусе колонки нет) + client_id_idx = None for line in lines: + if line.startswith('HEADER,CLIENT_LIST,'): + # В строке заголовка первым идёт слово HEADER, в строках данных его нет: сдвиг на 1 + header = [h.strip() for h in line.split(',')] + client_id_idx = header.index('Client ID') - 1 if 'Client ID' in header else None + continue if line.startswith('TIME,'): try: status_time = int(line.split(',')[2]) @@ -417,9 +425,19 @@ class OpenVPNDataGatherer: if since_ts is not None and since_ts <= 0: since_ts = None + # Client ID не меняется при float (смене адреса): идентификатор сессии; + # нет колонки или не число - session_id None (ключ сессии с real_address) + session_id = None + if client_id_idx is not None and client_id_idx < len(parts): + try: + session_id = str(int(parts[client_id_idx].strip())) + except ValueError: + session_id = None + client = { 'common_name': parts[1].strip(), 'real_address': parts[2].strip(), + 'session_id': session_id, 'bytes_received': int(parts[5].strip()), 'bytes_sent': int(parts[6].strip()), 'connected_since_ts': since_ts, @@ -454,11 +472,11 @@ class OpenVPNDataGatherer: Прирост для сессии, которой нет в кэше (правила: DOCS/Changes/2026-10-05_Gatherer_Reliability_PLAN.md, 2.2). Возвращает (inc_recv, inc_sent). """ - name, real_addr, since_ts = key + name, sess_id, since_ts = key if since_ts is None: # Нестандартный статус: время начала сессии неизвестно, запасная эвристика по размеру счётчиков - self.logger.warning(f"No connected_since time_t for {name} ({real_addr}): using 10 MB heuristic") + self.logger.warning(f"No connected_since time_t for {name} ({sess_id}): using 10 MB heuristic") threshold = 10 * 1024 * 1024 if curr_recv < threshold and curr_sent < threshold: return curr_recv, curr_sent @@ -476,7 +494,7 @@ class OpenVPNDataGatherer: # Сессия старше демона, снимка нет: базовая линия, трафик до этого момента потерян self.logger.warning( - f"Session of {name} ({real_addr}) started before the gatherer and has no snapshot: " + f"Session of {name} ({sess_id}) started before the gatherer and has no snapshot: " f"baseline set, {curr_recv} B received / {curr_sent} B sent before this moment are not counted" ) return 0, 0 @@ -501,7 +519,8 @@ class OpenVPNDataGatherer: db_clients = {row[1]: {'id': row[0], 'status': row[2]} for row in cursor.fetchall()} # Структура для агрегации инкрементов по Common Name перед записью в БД - # cn -> { 'inc_rx': 0, 'inc_tx': 0, 'curr_rx': 0, 'curr_tx': 0, 'real_address': '...'} + # cn -> { 'inc_recv': 0, 'inc_tx': 0, 'max_rx': 0 (сумма текущих счётчиков сессий), + # 'max_tx': 0, 'real_address': '...' (сессия с самым поздним началом)} cn_updates = {} # Новое состояние кэша сессий (применяется после commit) и активные CN @@ -516,9 +535,9 @@ class OpenVPNDataGatherer: curr_sent = client['bytes_sent'] since_ts = client.get('connected_since_ts') - # Уникальный ключ сессии: один и тот же CN/адрес может переподключиться - # (новый connected_since) - это уже новая сессия - session_key = (name, real_addr, since_ts) + # Уникальный ключ сессии: Client ID не меняется при float (смене адреса); + # без Client ID - адрес. Переподключение (новый connected_since) - новая сессия + session_key = (name, client.get('session_id') or real_addr, since_ts) active_cns.add(name) # --- ЛОГИКА РАСЧЕТА ДЕЛЬТЫ (In-Memory) --- @@ -560,17 +579,20 @@ class OpenVPNDataGatherer: if name not in cn_updates: cn_updates[name] = { 'inc_recv': 0, 'inc_tx': 0, - 'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД сохраним текущие счетчики самой большой сессии (примерно) - 'real_address': real_addr # Берем последний адрес + 'max_rx': 0, 'max_tx': 0, # Для last_bytes в БД: сумма текущих счётчиков всех сессий CN + 'real_address': real_addr, + 'addr_since': since_ts or 0 # Начало сессии, чей адрес сохранён } cn_updates[name]['inc_recv'] += inc_recv cn_updates[name]['inc_tx'] += inc_sent - # Сохраняем "текущее" значение как максимальное из сессий, чтобы в БД last_bytes было хоть что-то осмысленное - # (хотя при in-memory подходе поле last_bytes в БД теряет смысл для логики, но нужно для UI) - cn_updates[name]['max_rx'] = max(cn_updates[name]['max_rx'], curr_recv) - cn_updates[name]['max_tx'] = max(cn_updates[name]['max_tx'], curr_sent) - cn_updates[name]['real_address'] = real_addr + # last_bytes в БД = сумма текущих счётчиков всех сессий CN (нужно для UI) + cn_updates[name]['max_rx'] += curr_recv + cn_updates[name]['max_tx'] += curr_sent + # real_address = адрес сессии с самым поздним началом + if (since_ts or 0) >= cn_updates[name]['addr_since']: + cn_updates[name]['addr_since'] = since_ts or 0 + cn_updates[name]['real_address'] = real_addr # 3. Льготный период для сессий, которых нет в текущем статусе: # запись остаётся в кэше, пока missing_ticks < session_grace_ticks @@ -657,8 +679,8 @@ class OpenVPNDataGatherer: if sess_data: cursor.execute(''' INSERT INTO active_sessions - (client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen) - VALUES (?, ?, ?, ?, ?, ?, ?) + (client_id, common_name, real_address, bytes_received, bytes_sent, connected_since, last_seen, session_id) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) ''', ( client['db_id'], client['common_name'], @@ -666,7 +688,8 @@ class OpenVPNDataGatherer: client['bytes_received'], client['bytes_sent'], sess_data['connected_since'], - sess_data['last_seen'] + sess_data['last_seen'], + client.get('session_id') )) conn.commit() @@ -690,6 +713,19 @@ class OpenVPNDataGatherer: return active_clients + @staticmethod + def merge_sessions_by_cn(sessions): + """Сворачивает список сессий в список по CN: одна запись на пользователя за тик (сумма приростов).""" + merged = {} + for s in sessions: + m = merged.setdefault(s['common_name'], { + 'common_name': s['common_name'], 'db_id': s.get('db_id'), + 'bytes_received_inc': 0, 'bytes_sent_inc': 0 + }) + m['bytes_received_inc'] += s.get('bytes_received_inc', 0) + m['bytes_sent_inc'] += s.get('bytes_sent_inc', 0) + return list(merged.values()) + def calculate_rates(self, clients, time_diff): """Расчет скорости в Mbps""" if time_diff <= 0: @@ -745,9 +781,15 @@ class OpenVPNDataGatherer: # Рваное чтение / нет файла: тик пропускаем целиком, БД и кэш не трогаем. # last_check_time тоже не меняем: скорость следующего тика считается за весь интервал self.invalid_ticks += 1 - level = logging.ERROR if self.invalid_ticks >= self.invalid_max else logging.WARNING - self.logger.log(level, f"Skipping tick ({self.invalid_ticks} in a row): {reading.reason}") + # В журнал: 1-й тик, порог status_invalid_max (ERROR), далее раз в 60 тиков. + # Иначе на свежей установке без запущенного OpenVPN сообщение шло бы каждые 10 с + n = self.invalid_ticks + if n == 1 or n == self.invalid_max or n % 60 == 0: + level = logging.ERROR if n >= self.invalid_max else logging.WARNING + self.logger.log(level, f"Skipping tick ({n} in a row): {reading.reason}") else: + if self.invalid_ticks: + self.logger.info(f"Status file is readable again after {self.invalid_ticks} skipped ticks") self.invalid_ticks = 0 if reading.stale: self.logger.warning(reading.reason) @@ -761,8 +803,9 @@ class OpenVPNDataGatherer: if self.last_check_time: time_diff = (current_time - self.last_check_time).total_seconds() - # 4. Считаем скорости - clients_rated = self.calculate_rates(clients_with_updates, time_diff) + # 4. Сворачиваем сессии в записи по CN и считаем скорости (сумма по сессиям) + clients_rated = self.calculate_rates( + self.merge_sessions_by_cn(clients_with_updates), time_diff) # 5. Сохраняем RAW историю (для графиков реального времени) self.store_usage_history(clients_rated) diff --git a/APP_CORE/test_aggregated_speed.py b/APP_CORE/test_aggregated_speed.py new file mode 100644 index 0000000..ea03bbf --- /dev/null +++ b/APP_CORE/test_aggregated_speed.py @@ -0,0 +1,45 @@ +import importlib +import sqlite3 +from datetime import datetime, timedelta + +import pytest + +MB = 1_000_000 +FMT = '%Y-%m-%d %H:%M:%S' + + +@pytest.fixture +def api(tmp_path, monkeypatch): + """OpenVPNAPI on a temporary migrated database (the module creates a global instance on import).""" + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("OVPMON_OPENVPN_MONITOR_DB_PATH", str(tmp_path / "api.db")) + monkeypatch.delenv("OVPMON_AUTO_MIGRATE", raising=False) + module = importlib.import_module("openvpn_api_v3") + return module.OpenVPNAPI() + + +def test_aggregated_history_speed_is_bucket_average(api): + now = datetime.utcnow() + full = (now - timedelta(hours=5)).replace(minute=0, second=0, microsecond=0) # complete hourly bucket + current = now - timedelta(seconds=1800) # bucket started 30 minutes ago: lasts 1800 s, not 3600 s + conn = sqlite3.connect(api.db_manager.db_path) + conn.execute("INSERT INTO clients (common_name) VALUES ('alice')") + cid = conn.execute("SELECT id FROM clients WHERE common_name='alice'").fetchone()[0] + for ts in (full, current): + conn.execute("INSERT INTO stats_hourly (timestamp, client_id, bytes_received, bytes_sent) VALUES (?,?,?,?)", + (ts.strftime(FMT), cid, 450 * MB, 90 * MB)) + conn.commit() + conn.close() + + res = api.get_client_history('alice', now - timedelta(days=7), now, resolution='hourly') + full_row, current_row = res['data'] + # 450 MB over 3600 s = 1.0 Mbps (rx), 90 MB over 3600 s = 0.2 Mbps (tx) + assert full_row['bytes_received_rate_mbps'] == pytest.approx(1.0) + assert full_row['bytes_sent_rate_mbps'] == pytest.approx(0.2) + # the same volume over 1800 s: twice as fast + assert current_row['bytes_received_rate_mbps'] == pytest.approx(2.0, rel=0.01) + assert current_row['bytes_sent_rate_mbps'] == pytest.approx(0.4, rel=0.01) + + # Analytics 7d reads the same table: the sum of clients per timestamp, speed is non-zero + history = api.get_analytics_data('7d')['global_history_24h'] + assert max(p['total_rx_rate'] for p in history) == pytest.approx(2.0, rel=0.01) diff --git a/APP_CORE/test_gatherer.py b/APP_CORE/test_gatherer.py index 6d21e88..34950c4 100644 --- a/APP_CORE/test_gatherer.py +++ b/APP_CORE/test_gatherer.py @@ -3,6 +3,7 @@ import logging import signal import sqlite3 import time +from datetime import datetime, timedelta import pytest @@ -17,11 +18,11 @@ HEADER = ("HEADER,CLIENT_LIST,Common Name,Real Address,Virtual Address,Virtual I def write_status(path, now, clients, complete=True): - """Synthetic OpenVPN status file v2. clients: (cn, real_address, rx, tx, connected_since_ts).""" + """Synthetic OpenVPN status file v2. clients: (cn, real_address, rx, tx, connected_since_ts[, client_id]).""" lines = ["TITLE,OpenVPN 2.6.8 x86_64-pc-linux-gnu", f"TIME,Mon Jan 1 00:00:00 2027,{int(now)}", HEADER] - for cn, real, rx, tx, since in clients: + for cn, real, rx, tx, since, *cid in clients: lines.append(f"CLIENT_LIST,{cn},{real},10.8.0.2,,{rx},{tx},Mon Jan 1 00:00:00 2027,{since}," - f"UNDEF,1,0,AES-256-GCM") + f"UNDEF,{cid[0] if cid else 1},0,AES-256-GCM") lines += ["HEADER,ROUTING_TABLE,Virtual Address,Common Name,Real Address,Last Ref,Last Ref (time_t)", "GLOBAL_STATS,Max bcast/mcast queue length,0"] if complete: @@ -167,6 +168,24 @@ def test_torn_read_skips_the_tick(env): assert env.history_sum() == (3000, 2) +def test_missing_status_file_logs_sparingly_and_reports_recovery(env, caplog): + g = env.gatherer() + caplog.set_level(logging.INFO) + for _ in range(125): # no status file at all (OpenVPN not started yet) + g.run_monitoring_cycle() + skipped = [r for r in caplog.records if "Skipping tick" in r.getMessage()] + # tick 1, the threshold (6, ERROR), then every 60th + assert [r.getMessage().split("(")[1].split(" ")[0] for r in skipped] == ["1", "6", "60", "120"] + assert [r.levelno for r in skipped] == [logging.WARNING, logging.ERROR, logging.ERROR, logging.ERROR] + assert g.invalid_ticks == 125 + + caplog.clear() + env.tick(g, [("alice", "1.1.1.1:1000", 1000, 100, T0 + 5)]) + again = [r for r in caplog.records if "readable again" in r.getMessage()] + assert len(again) == 1 and again[0].levelno == logging.INFO and "125" in again[0].getMessage() + assert g.invalid_ticks == 0 + + def test_session_missing_for_a_tick_and_beyond_grace(env): g = env.gatherer() since = T0 + 5 @@ -196,6 +215,47 @@ def test_session_missing_for_a_tick_and_beyond_grace(env): assert len(g.session_cache) == 1 +def test_two_sessions_of_one_cn_are_one_record(env): + g = env.gatherer() + s1, s2 = T0 + 5, T0 + 8 + + def tick(rx1, rx2): + # скорость считается за 10 с (реальные часы теста не управляются) + g.last_check_time = datetime.now() - timedelta(seconds=10) + env.tick(g, [("alice", "1.1.1.1:1000", rx1, rx1 // 10, s1, 1), + ("alice", "2.2.2.2:2000", rx2, rx2 // 10, s2, 2)]) + + tick(1000, 500) + tick(3000, 1500) + # Итоги = сумма обеих сессий; одна строка истории на тик, скорость = сумма сессий + assert env.totals("alice") == (4500, 450) + rows = env.query("SELECT bytes_received, bytes_received_rate_mbps FROM usage_history ORDER BY id") + assert [r[0] for r in rows] == [1500, 3000] + assert rows[1][1] == pytest.approx(3000 * 8 / 10 / 1_000_000, rel=0.01) + assert env.query("SELECT bytes_received FROM stats_5min") == [(4500,)] + + # Одна сессия отключилась: статус Active, итог растёт только приростом оставшейся + env.tick(g, [("alice", "1.1.1.1:1000", 4000, 400, s1, 1)]) + assert env.totals("alice") == (5500, 550) + assert env.query("SELECT status FROM clients") == [("Active",)] + + +def test_float_keeps_the_session_by_client_id(env): + since = T0 + 5 + g = env.gatherer() + env.tick(g, [("alice", "1.1.1.1:1000", 1000, 100, since, 7)]) + # float: другой адрес, тот же Client ID и начало - прирост = разница счётчиков + env.tick(g, [("alice", "2.2.2.2:2000", 3000, 300, since, 7)]) + assert env.totals("alice") == (3000, 300) + assert env.query("SELECT real_address, session_id FROM active_sessions") == [("2.2.2.2:2000", "7")] + + # Перезапуск демона: базовая линия из снимка по Client ID, адрес снова другой + env.clock.t += 100 + g2 = env.gatherer() + env.tick(g2, [("alice", "3.3.3.3:3000", 9000, 900, since, 7)]) + assert env.totals("alice") == (9000, 900) + + def test_loop_survives_exceptions_and_stops_on_signal(env): g = env.gatherer() g.stop_event = FakeEvent() diff --git a/APP_CORE/test_migrations.py b/APP_CORE/test_migrations.py index 24091e0..f1235e3 100644 --- a/APP_CORE/test_migrations.py +++ b/APP_CORE/test_migrations.py @@ -151,8 +151,9 @@ def test_old_schema_is_migrated_without_data_loss(tmp_path, schema): # Missing tables and columns are there, existing rows get the defaults assert {"active_sessions", "users", "login_attempts"} <= table_names(db) assert query(db, "SELECT totp_secret, is_2fa_enabled FROM users") == [(None, 0)] + assert query(db, "SELECT session_id FROM active_sessions") in ([], [(None,)]) # migration 2: column exists, NULL # Stamped, and the backup is the untouched pre-migration copy - assert query(db, "SELECT version, name FROM schema_migrations") == [(1, "baseline")] + assert query(db, "SELECT version, name FROM schema_migrations") == [(1, "baseline"), (2, "session_id")] backups = glob.glob(db + ".bak-*") assert backups == [report.backup] assert [query(backups[0], q) for q in DATA_QUERIES] == before @@ -204,7 +205,7 @@ def test_fresh_database_gets_full_schema_without_backup(tmp_path): assert glob.glob(db + ".bak-*") == [] assert {"clients", "usage_history", "active_sessions", "users", "login_attempts", "stats_5min", "stats_daily", "schema_migrations"} <= table_names(db) - assert query(db, "SELECT version FROM schema_migrations") == [(1,)] + assert query(db, "SELECT version FROM schema_migrations") == [(1,), (2,)] def test_auto_migrate_off_refuses_while_pending(tmp_path, monkeypatch): @@ -242,5 +243,5 @@ def test_simultaneous_start_makes_one_backup(tmp_path): assert errors == [] assert len(glob.glob(db + ".bak-*")) == 1 - assert sorted(len(r.applied) for r in reports) == [0, 1] - assert query(db, "SELECT version FROM schema_migrations") == [(1,)] + assert sorted(len(r.applied) for r in reports) == [0, len(migrations.MIGRATIONS)] + assert query(db, "SELECT version FROM schema_migrations") == [(1,), (2,)] diff --git a/APP_PROFILER/Dockerfile b/APP_PROFILER/Dockerfile index 289ae24..e0a4a54 100644 --- a/APP_PROFILER/Dockerfile +++ b/APP_PROFILER/Dockerfile @@ -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 . . diff --git a/APP_PROFILER/main.py b/APP_PROFILER/main.py index 07575bd..d6d0cc2 100644 --- a/APP_PROFILER/main.py +++ b/APP_PROFILER/main.py @@ -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(): diff --git a/APP_PROFILER/requirements.txt b/APP_PROFILER/requirements.txt index b57a99d..fb93612 100644 --- a/APP_PROFILER/requirements.txt +++ b/APP_PROFILER/requirements.txt @@ -6,3 +6,6 @@ python-multipart jinja2 pyjwt requests +cryptography +minio +paramiko diff --git a/APP_PROFILER/routers/backup.py b/APP_PROFILER/routers/backup.py new file mode 100644 index 0000000..df496ac --- /dev/null +++ b/APP_PROFILER/routers/backup.py @@ -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) diff --git a/APP_PROFILER/routers/profiles.py b/APP_PROFILER/routers/profiles.py index 1b108cf..ef3ee10 100644 --- a/APP_PROFILER/routers/profiles.py +++ b/APP_PROFILER/routers/profiles.py @@ -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: diff --git a/APP_PROFILER/routers/server.py b/APP_PROFILER/routers/server.py index e7d2fe8..260d91f 100644 --- a/APP_PROFILER/routers/server.py +++ b/APP_PROFILER/routers/server.py @@ -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) diff --git a/APP_PROFILER/routers/server_process.py b/APP_PROFILER/routers/server_process.py index 27d20b0..dc2c9ad 100644 --- a/APP_PROFILER/routers/server_process.py +++ b/APP_PROFILER/routers/server_process.py @@ -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. diff --git a/APP_PROFILER/routers/system.py b/APP_PROFILER/routers/system.py index 0732210..d6e6734 100644 --- a/APP_PROFILER/routers/system.py +++ b/APP_PROFILER/routers/system.py @@ -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") diff --git a/APP_PROFILER/services/backup/__init__.py b/APP_PROFILER/services/backup/__init__.py new file mode 100644 index 0000000..81f28ef --- /dev/null +++ b/APP_PROFILER/services/backup/__init__.py @@ -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).""" diff --git a/APP_PROFILER/services/backup/crypto.py b/APP_PROFILER/services/backup/crypto.py new file mode 100644 index 0000000..18129a3 --- /dev/null +++ b/APP_PROFILER/services/backup/crypto.py @@ -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 diff --git a/APP_PROFILER/services/backup/destinations.py b/APP_PROFILER/services/backup/destinations.py new file mode 100644 index 0000000..2d040f1 --- /dev/null +++ b/APP_PROFILER/services/backup/destinations.py @@ -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) diff --git a/APP_PROFILER/services/backup/engine.py b/APP_PROFILER/services/backup/engine.py new file mode 100644 index 0000000..98c973e --- /dev/null +++ b/APP_PROFILER/services/backup/engine.py @@ -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- 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-, new ones come from .restore-new-.""" + 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) diff --git a/APP_PROFILER/services/backup/package.py b/APP_PROFILER/services/backup/package.py new file mode 100644 index 0000000..c9b32fc --- /dev/null +++ b/APP_PROFILER/services/backup/package.py @@ -0,0 +1,335 @@ +"""Backup package: naming, building (snapshots), reading and safe extraction. + +A package is a tar.gz named ovpmon-backup__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[A-Za-z0-9][A-Za-z0-9.-]{0,62})_(?P\d{8}T\d{6}Z)(?:-(?P\d{1,3}))?" + r"\.ovpbak(?P\.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 diff --git a/APP_PROFILER/services/backup/store.py b/APP_PROFILER/services/backup/store.py new file mode 100644 index 0000000..694a763 --- /dev/null +++ b/APP_PROFILER/services/backup/store.py @@ -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] diff --git a/APP_PROFILER/services/pki.py b/APP_PROFILER/services/pki.py index 561cb3d..6762499 100644 --- a/APP_PROFILER/services/pki.py +++ b/APP_PROFILER/services/pki.py @@ -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: diff --git a/APP_PROFILER/templates/client.ovpn.j2 b/APP_PROFILER/templates/client.ovpn.j2 index a3cf6b4..9ffef05 100644 --- a/APP_PROFILER/templates/client.ovpn.j2 +++ b/APP_PROFILER/templates/client.ovpn.j2 @@ -1,25 +1,19 @@ client dev tun -windows-driver wintun proto {{ protocol }} remote {{ remote_ip }} {{ port }} resolv-retry infinite nobind +{% if protocol == 'udp' %} +explicit-exit-notify +{% endif %} {% if tun_mtu %} tun-mtu {{ tun_mtu }} {% endif %} -user nobody -group nobody persist-key persist-tun -{% if protocol == 'tcp' %} -tls-client -{% else %} -#tls-client -{% endif %} - mute-replay-warnings remote-cert-tls server diff --git a/APP_PROFILER/templates/server.conf.j2 b/APP_PROFILER/templates/server.conf.j2 index 3effa7a..7a83f7e 100644 --- a/APP_PROFILER/templates/server.conf.j2 +++ b/APP_PROFILER/templates/server.conf.j2 @@ -1,9 +1,6 @@ dev tun proto {{ protocol }} -{% if protocol == 'tcp' %} -tls-server -{% else %} -# explicit-exit-notify 1 +{% if protocol != 'tcp' %} explicit-exit-notify 1 {% endif %} port {{ port }} @@ -28,7 +25,6 @@ server {{ vpn_network }} {{ vpn_netmask }} ifconfig-pool-persist /etc/openvpn/ipp.txt -log /var/log/openvpn/openvpn.log log-append /var/log/openvpn/openvpn.log verb 3 diff --git a/APP_PROFILER/test_backup.py b/APP_PROFILER/test_backup.py new file mode 100644 index 0000000..d8e71de --- /dev/null +++ b/APP_PROFILER/test_backup.py @@ -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" diff --git a/APP_PROFILER/test_client_template.py b/APP_PROFILER/test_client_template.py new file mode 100644 index 0000000..405b936 --- /dev/null +++ b/APP_PROFILER/test_client_template.py @@ -0,0 +1,17 @@ +"""One test for the client profile template (templates/client.ovpn.j2), tcp and udp.""" +import pytest + +from services.generator import env + + +@pytest.mark.parametrize("protocol", ["tcp", "udp"]) +def test_client_template(protocol): + text = env.get_template("client.ovpn.j2").render( + protocol=protocol, remote_ip="203.0.113.1", port=1194, ca_cert="CA", + client_cert="CERT", client_key="KEY", tls_auth="TA", tun_mtu=None) + lines = [x.strip() for x in text.splitlines()] + assert f"proto {protocol}" in lines and "client" in lines + # directives that OpenVPN 2.7 rejects or that are redundant/harmful on user devices + for gone in ("windows-driver", "tls-client", "#tls-client", "user", "group"): + assert not any(x.split(" ")[0] == gone for x in lines) + assert ("explicit-exit-notify" in lines) == (protocol == "udp") diff --git a/APP_PROFILER/utils/guards.py b/APP_PROFILER/utils/guards.py new file mode 100644 index 0000000..c375c4a --- /dev/null +++ b/APP_PROFILER/utils/guards.py @@ -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) diff --git a/APP_UI/.dockerignore b/APP_UI/.dockerignore new file mode 100644 index 0000000..bbedb18 --- /dev/null +++ b/APP_UI/.dockerignore @@ -0,0 +1,6 @@ +node_modules +dist +.vscode +.git +*.bak +*.log diff --git a/APP_UI/Dockerfile b/APP_UI/Dockerfile index a52aedb..a2929c9 100644 --- a/APP_UI/Dockerfile +++ b/APP_UI/Dockerfile @@ -2,14 +2,22 @@ FROM node:20-alpine AS build-stage WORKDIR /app COPY package*.json ./ -RUN npm install +RUN npm ci COPY . . RUN npm run build # Stage 2: Serve -FROM nginx:alpine +# nginx runs as the unprivileged user "nginx" (uid 101) and listens on 8080 (OVP_UI_PORT); docker-compose publishes +# it as the host port (OVPMON_HTTP_PORT, default 80). The image entrypoint renders the template into +# /etc/nginx/conf.d. Behind another proxy or Kubernetes: target port 8080. +FROM nginxinc/nginx-unprivileged:alpine COPY --from=build-stage /app/dist /usr/share/nginx/html COPY default.conf.template /etc/nginx/templates/default.conf.template -EXPOSE 80 +# Validates OVP_CSP_CONNECT_EXTRA before the template is rendered (20-envsubst-on-templates.sh) +COPY check-csp-connect-extra.sh /docker-entrypoint.d/15-check-csp-connect-extra.sh +# envsubst replaces only variables that are defined, so the defaults must exist. +# OVP_CSP_CONNECT_EXTRA: extra connect-src origins of the CSP, separated by spaces (empty: same origin only) +ENV OVP_UI_PORT=8080 \ + OVP_CSP_CONNECT_EXTRA="" +EXPOSE 8080 CMD ["nginx", "-g", "daemon off;"] - diff --git a/APP_UI/README.md b/APP_UI/README.md index c67f1f4..0d56f8e 100644 --- a/APP_UI/README.md +++ b/APP_UI/README.md @@ -1,25 +1,37 @@ -# OpenVPN Dashboard UI (`APP_UI`) +# OpenVPN Controller UI (`APP_UI`) A Single Page Application (SPA) built with **Vue 3** and **Vite**. It serves as the unified dashboard for monitoring and management. ## Project Structure -- `src/views/`: Page components (Dashboard, Login, Profiles, etc.). -- `src/components/`: Reusable widgets (Charts, Sidebar). -- `src/stores/`: Pinia state management (Auth, Client Data). +- `src/views/`: Pages (Analytics, Clients, Certificates, PKI and VPN configuration, Server Process, Backup and Restore, Account, Login). +- `src/components/`: Reusable widgets (`BaseModal`, `ConfirmModal`, `StatusBadge`, toasts, dialogs). +- `src/composables/`: Shared logic: `useApi` (axios clients: monitoring API, profiler API, `/api/auth`), `useTrafficChart` (charts), `useTheme`, `useToast`, `useFormatters`, `usePkiStatus`. +- `src/utils/`: Helpers without Vue (CIDR parsing). +- `default.conf.template`: nginx configuration of the container image (security headers, one CSP, gzip, cache, API proxy). +- `Dockerfile`: build and `nginxinc/nginx-unprivileged:alpine` image (user `nginx`, port 8080); `check-csp-connect-extra.sh`: validation of `OVP_CSP_CONNECT_EXTRA`, runs at container start. ## Configuration -Runtime configuration is loaded from `/config.json` (in `public/`) to allow environment-independent builds. +Runtime configuration is loaded from `/config.json` (in `public/`) to allow environment-independent builds. With the container nginx the CSP allows requests to the page origin only (`connect-src 'self'`): keep the API paths proxied (`/api/v1`, `/profiles-api`). To call an API on another origin, set `OVPMON_CSP_CONNECT_EXTRA` (origins separated by spaces; see [Containers reference](../DOCS/Deployment/Containers/Reference.md)). The `app-ui` container listens on 8080 (`OVP_UI_PORT`) as the unprivileged user `nginx`; compose publishes it as `OVPMON_HTTP_PORT` (default 80). ## Development ```bash -npm install -npm run dev -# Access at http://localhost:5173 +npm ci # exact versions from package-lock.json (npm install after changing package.json) +npm run dev # http://localhost:5173 +npm run build +npm test # Vitest: formatters, CIDR parsing, 401 handling +npm run lint # ESLint (minimal Vue rules) ``` +Node 20.19 or newer is required (Vite 7). + +## Notes + +- The session token is kept in `localStorage` (accepted risk, see `DOCS/General/Security_Architecture.md`). +- Confirmations use `ConfirmModal`, notices use toasts (`useToast`); the native `confirm()` and SweetAlert2 are not used. +- After changing the UI sources, refresh the committed build for system-service installs: `deploy/native/build-ui.sh --publish` (`deploy/native/check-ui.sh` shows whether it is stale). + ## Documentation See `DOCS/UI/Architecture.md` for detailed architecture notes. - diff --git a/APP_UI/check-csp-connect-extra.sh b/APP_UI/check-csp-connect-extra.sh new file mode 100755 index 0000000..ea16e09 --- /dev/null +++ b/APP_UI/check-csp-connect-extra.sh @@ -0,0 +1,51 @@ +#!/bin/sh +# Validates OVP_CSP_CONNECT_EXTRA: extra origins for the connect-src directive of the Content-Security-Policy +# (compose: OVPMON_CSP_CONNECT_EXTRA). The value ends up in a response header, so only origins are accepted: +# empty, or https://host[:port] and http://host[:port] separated by spaces (host: letters, digits, dots, hyphens; +# no path, quotes, ; or commas). Anything else could inject another CSP directive. +# +# Runs as /docker-entrypoint.d/15-check-csp-connect-extra.sh in the app-ui image (before the template is +# rendered by 20-envsubst-on-templates.sh) and from the all-in-one entrypoint. Exit code 1 stops the container. +# The same rule is in deploy/docker/lib.sh and deploy/native/lib.sh (csp_extra_problem): keep them in step. +set -eu + +csp_extra_problem() { + local _t _rest _host _port + [ -n "$1" ] || return 0 + case "$1" in + *[!A-Za-z0-9.:/\ -]*) + printf 'contains characters that are not allowed (only letters, digits, . - : / and spaces; no quotes, ; or commas)'; return 1 ;; + " "*|*" ") + printf 'starts or ends with a space'; return 1 ;; + esac + set -f + for _t in $1; do + case "$_t" in + https://*) _rest=${_t#https://} ;; + http://*) _rest=${_t#http://} ;; + *) set +f; printf "'%s' is not an origin (use https://host[:port] or http://host[:port])" "$_t"; return 1 ;; + esac + _host=${_rest%%:*} + _port="" + case "$_rest" in *:*) _port=${_rest#*:} ;; esac + case "$_host" in + ""|*[!A-Za-z0-9.-]*) set +f; printf "'%s' has an invalid host (letters, digits, dots and hyphens; no path)" "$_t"; return 1 ;; + esac + if [ -n "$_port" ]; then + case "$_port" in + *[!0-9]*) set +f; printf "'%s' has an invalid port (digits only, no path)" "$_t"; return 1 ;; + esac + if [ "${#_port}" -gt 5 ] || [ "$_port" -lt 1 ] || [ "$_port" -gt 65535 ]; then + set +f; printf "'%s' has a port out of range" "$_t"; return 1 + fi + fi + case "$_rest" in *:) set +f; printf "'%s' has an empty port" "$_t"; return 1 ;; esac + done + set +f + return 0 +} + +if ! _reason=$(csp_extra_problem "${OVP_CSP_CONNECT_EXTRA:-}"); then + echo "check-csp-connect-extra: OVPMON_CSP_CONNECT_EXTRA is invalid: $_reason. Use origins https://host[:port] or http://host[:port] separated by spaces, or leave it empty" >&2 + exit 1 +fi diff --git a/APP_UI/default.conf.template b/APP_UI/default.conf.template index 196e76d..2e57caf 100644 --- a/APP_UI/default.conf.template +++ b/APP_UI/default.conf.template @@ -1,21 +1,58 @@ server { - listen 80; + listen ${OVP_UI_PORT}; server_name localhost; + server_tokens off; root /usr/share/nginx/html; index index.html; + # Security headers. add_header in a location replaces the ones inherited from the server block, + # so the /assets/ location below repeats them. CSP: the bundle is served from this origin only; + # style-src 'unsafe-inline' is needed by Bootstrap and Chart.js (inline style attributes). + # connect-src is 'self' plus OVP_CSP_CONNECT_EXTRA (origins separated by spaces, empty by default): set it + # only when config.json points the UI to an API on another origin (the defaults /api/v1 and /profiles-api are + # proxied below, same origin). The value is validated by the deploy scripts and by the all-in-one entrypoint. + # One policy ($csp) for both places. + set $csp "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' ${OVP_CSP_CONNECT_EXTRA}; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header Referrer-Policy "no-referrer" always; + add_header Content-Security-Policy $csp always; + + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_types text/plain text/css text/javascript application/javascript application/json image/svg+xml; + location / { try_files $uri $uri/ /index.html; } + # Hashed build files never change under the same name + location /assets/ { + try_files $uri =404; + add_header Cache-Control "public, max-age=31536000, immutable"; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header Referrer-Policy "no-referrer" always; + add_header Content-Security-Policy $csp always; + } + + # The entry page and the runtime configuration must be revalidated after an update + # (expires -1 sends "Cache-Control: no-cache" and keeps the server-level headers) + location = /index.html { + expires -1; + } + location = /config.json { + expires -1; + } + # Модуль 1: Мониторинг (Flask, порт 5001) location /api/ { proxy_pass http://${OVP_API_HOST}:${OVP_API_PORT}; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_pass_header Authorization; } # Модуль 2: Управление профилями (FastAPI, порт 8000) @@ -34,4 +71,4 @@ server { location = /50x.html { root /usr/share/nginx/html; } -} \ No newline at end of file +} diff --git a/APP_UI/eslint.config.js b/APP_UI/eslint.config.js new file mode 100644 index 0000000..58bb0af --- /dev/null +++ b/APP_UI/eslint.config.js @@ -0,0 +1,26 @@ +import js from '@eslint/js'; +import pluginVue from 'eslint-plugin-vue'; +import globals from 'globals'; + +// Minimal rules: recommended JS + essential Vue (real errors only, no style rules) +export default [ + { ignores: ['dist/**', 'node_modules/**'] }, + js.configs.recommended, + ...pluginVue.configs['flat/essential'], + { + files: ['**/*.{js,vue}'], + languageOptions: { + globals: { ...globals.browser } + }, + rules: { + 'vue/multi-word-component-names': 'off', // views are named after their route + 'no-unused-vars': ['warn', { args: 'none', caughtErrors: 'none' }] + } + }, + { + files: ['**/*.test.js', 'eslint.config.js', 'vite.config.js'], + languageOptions: { + globals: { ...globals.node } + } + } +]; diff --git a/APP_UI/index.html b/APP_UI/index.html index 67f4601..3b79efb 100644 --- a/APP_UI/index.html +++ b/APP_UI/index.html @@ -3,7 +3,7 @@ - + OpenVPN Controller diff --git a/APP_UI/package-lock.json b/APP_UI/package-lock.json index b65b590..a734b9d 100644 --- a/APP_UI/package-lock.json +++ b/APP_UI/package-lock.json @@ -13,14 +13,17 @@ "bootstrap": "^5.3.8", "chart.js": "^4.5.1", "qrcode.vue": "^3.6.0", - "sass": "^1.97.2", - "sweetalert2": "^11.26.17", "vue": "^3.5.24", "vue-router": "^4.6.4" }, "devDependencies": { + "@eslint/js": "^10.0.1", "@vitejs/plugin-vue": "^6.0.1", - "vite": "^7.2.4" + "eslint": "^10.12.0", + "eslint-plugin-vue": "^10.11.1", + "globals": "^17.13.0", + "vite": "^7.2.4", + "vitest": "^3.2.4" } }, "node_modules/@babel/helper-string-parser": { @@ -69,6 +72,30 @@ "node": ">=6.9.0" } }, + "node_modules/@cacheable/memory": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz", + "integrity": "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cacheable/utils": "^2.5.0", + "@keyv/bigmap": "^1.3.1", + "hookified": "^1.15.1", + "keyv": "^5.6.0" + } + }, + "node_modules/@cacheable/utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz", + "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hashery": "^1.5.1", + "keyv": "^5.6.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.27.2", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz", @@ -511,6 +538,134 @@ "node": ">=18" } }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", + "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.23.5", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz", + "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^3.0.5", + "debug": "^4.3.1", + "minimatch": "^10.2.4" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz", + "integrity": "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/core": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz", + "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/js": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz", + "integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "eslint": "^10.0.0" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/@eslint/object-schema": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", + "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz", + "integrity": "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1", + "levn": "^0.4.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, "node_modules/@fortawesome/fontawesome-free": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-free/-/fontawesome-free-7.1.0.tgz", @@ -520,12 +675,102 @@ "node": ">=6" } }, + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.5.5", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", "license": "MIT" }, + "node_modules/@keyv/bigmap": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", + "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hashery": "^1.4.0", + "hookified": "^1.15.0" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "keyv": "^5.6.0" + } + }, + "node_modules/@keyv/serialize": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", + "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==", + "dev": true, + "license": "MIT" + }, "node_modules/@kurkle/color": { "version": "0.3.4", "resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz", @@ -536,9 +781,11 @@ "version": "2.5.1", "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.5.1.tgz", "integrity": "sha512-dfUnCxiN9H4ap84DvD2ubjw+3vUNpstxa0TneY/Paat8a3R4uQZDLSvWjmznAY/DoahqTHl9V46HF/Zs3F29pg==", + "dev": true, "hasInstallScript": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "detect-libc": "^1.0.3", "is-glob": "^4.0.3", @@ -575,11 +822,13 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "android" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -595,11 +844,13 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "darwin" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -615,11 +866,13 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "darwin" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -635,11 +888,13 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "freebsd" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -655,11 +910,13 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -675,11 +932,13 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -695,11 +954,13 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -715,11 +976,13 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -735,11 +998,13 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -755,11 +1020,13 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -775,11 +1042,13 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "win32" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -795,11 +1064,13 @@ "cpu": [ "ia32" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "win32" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -815,11 +1086,13 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ "win32" ], + "peer": true, "engines": { "node": ">= 10.0.0" }, @@ -1196,6 +1469,31 @@ "win32" ] }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/esrecurse": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", + "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", @@ -1203,6 +1501,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, "node_modules/@vitejs/plugin-vue": { "version": "6.0.3", "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.3.tgz", @@ -1220,6 +1525,131 @@ "vue": "^3.2.25" } }, + "node_modules/@vitest/expect": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.7.tgz", + "integrity": "sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.7.tgz", + "integrity": "sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "3.2.7", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.17" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.7.tgz", + "integrity": "sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.7.tgz", + "integrity": "sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "3.2.7", + "pathe": "^2.0.3", + "strip-literal": "^3.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.7.tgz", + "integrity": "sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "magic-string": "^0.30.17", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.7.tgz", + "integrity": "sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyspy": "^4.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.7.tgz", + "integrity": "sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "3.2.7", + "loupe": "^3.1.4", + "tinyrainbow": "^2.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/@vue/compiler-core": { "version": "3.5.26", "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.5.26.tgz", @@ -1326,6 +1756,56 @@ "integrity": "sha512-7Z6/y3uFI5PRoKeorTOSXKcDj0MSasfNNltcslbFrPpcw6aXRUALq4IfJlaTRspiWIUOEZbrpM+iQGmCOiWe4A==", "license": "MIT" }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", @@ -1343,6 +1823,23 @@ "proxy-from-env": "^1.1.0" } }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/boolbase": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", + "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", + "dev": true, + "license": "ISC" + }, "node_modules/bootstrap": { "version": "5.3.8", "resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-5.3.8.tgz", @@ -1362,12 +1859,27 @@ "@popperjs/core": "^2.11.8" } }, + "node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, "node_modules/braces": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "fill-range": "^7.1.1" }, @@ -1375,6 +1887,30 @@ "node": ">=8" } }, + "node_modules/cac": { + "version": "6.7.14", + "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", + "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cacheable": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz", + "integrity": "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@cacheable/memory": "^2.2.0", + "@cacheable/utils": "^2.5.0", + "hookified": "^1.15.0", + "keyv": "^5.6.0", + "qified": "^0.10.1" + } + }, "node_modules/call-bind-apply-helpers": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", @@ -1388,6 +1924,23 @@ "node": ">= 0.4" } }, + "node_modules/chai": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz", + "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==", + "dev": true, + "license": "MIT", + "dependencies": { + "assertion-error": "^2.0.1", + "check-error": "^2.1.1", + "deep-eql": "^5.0.1", + "loupe": "^3.1.0", + "pathval": "^2.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/chart.js": { "version": "4.5.1", "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz", @@ -1400,11 +1953,24 @@ "pnpm": ">=8" } }, + "node_modules/check-error": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz", + "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 16" + } + }, "node_modules/chokidar": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "readdirp": "^4.0.1" }, @@ -1427,12 +1993,75 @@ "node": ">= 0.8" } }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-eql": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz", + "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, "node_modules/delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -1446,8 +2075,10 @@ "version": "1.0.3", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz", "integrity": "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg==", + "dev": true, "license": "Apache-2.0", "optional": true, + "peer": true, "bin": { "detect-libc": "bin/detect-libc.js" }, @@ -1499,6 +2130,13 @@ "node": ">= 0.4" } }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, "node_modules/es-object-atoms": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", @@ -1568,12 +2206,243 @@ "@esbuild/win32-x64": "0.27.2" } }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "10.12.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.12.0.tgz", + "integrity": "sha512-npHjrHb2o4ehH3mE+YuxABR+0gyb0aVWCIolgJDArwCiHEIsonBm3ZKjel5b0U5+a+MbEvIyRCGCzD3eKKK2NA==", + "dev": true, + "license": "MIT", + "workspaces": [ + "packages/*" + ], + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.2", + "@eslint/config-array": "^0.23.5", + "@eslint/config-helpers": "^0.7.0", + "@eslint/core": "^1.2.1", + "@eslint/plugin-kit": "^0.7.3", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^9.1.2", + "eslint-visitor-keys": "^5.0.1", + "espree": "^11.2.0", + "esquery": "^1.7.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "11.1.5 || >11.1.6 <12", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "minimatch": "^10.2.5", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-vue": { + "version": "10.11.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-10.11.1.tgz", + "integrity": "sha512-pasVXhl7wUmIvhujoqs/m0mJ9r59QW1IR9XXYKGR0FETzSM+Hhlf4qKIYgWiDDP+9YKv4YfbwskD7LqIdVcgQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "natural-compare": "^1.4.0", + "nth-check": "^2.1.1", + "postcss-selector-parser": "^7.1.4", + "semver": "^7.8.5", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "peerDependencies": { + "@stylistic/eslint-plugin": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0", + "@typescript-eslint/parser": "^7.0.0 || ^8.0.0", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "vue-eslint-parser": "^10.3.0" + }, + "peerDependenciesMeta": { + "@stylistic/eslint-plugin": { + "optional": true + }, + "@typescript-eslint/parser": { + "optional": true + } + } + }, + "node_modules/eslint-scope": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz", + "integrity": "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@types/esrecurse": "^4.3.1", + "@types/estree": "^1.0.8", + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", + "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.16.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^5.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, "node_modules/estree-walker": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", "license": "MIT" }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, "node_modules/fdir": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", @@ -1592,12 +2461,24 @@ } } }, + "node_modules/file-entry-cache": { + "version": "11.1.5", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz", + "integrity": "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^6.1.23" + } + }, "node_modules/fill-range": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "to-regex-range": "^5.0.1" }, @@ -1605,6 +2486,42 @@ "node": ">=8" } }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "6.1.23", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz", + "integrity": "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "cacheable": "^2.5.0", + "flatted": "^3.4.2", + "hookified": "^1.15.0" + } + }, + "node_modules/flatted": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", + "dev": true, + "license": "ISC" + }, "node_modules/follow-redirects": { "version": "1.15.11", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", @@ -1702,6 +2619,32 @@ "node": ">= 0.4" } }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "17.13.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.13.0.tgz", + "integrity": "sha512-RwMTC61u7hrG3ZJMkZQOK4JLJrKS8QtoTii63EmWvFXHqycY9FObBJQCbsLxSO8kjKhWE5kV1GC+Vb1g3RI0Zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -1741,6 +2684,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/hashery": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz", + "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "hookified": "^1.15.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/hasown": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", @@ -1753,18 +2709,48 @@ "node": ">= 0.4" } }, + "node_modules/hookified": { + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz", + "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==", + "dev": true, + "license": "MIT" + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, "node_modules/immutable": { "version": "5.1.4", "resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.4.tgz", "integrity": "sha512-p6u1bG3YSnINT5RQmx/yRZBpenIl30kVxkTLDyHLIMk0gict704Q9n+thfDI7lTRm9vXdDYutVzXhzcThxTnXA==", - "license": "MIT" + "dev": true, + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, "license": "MIT", - "optional": true, "engines": { "node": ">=0.10.0" } @@ -1773,8 +2759,8 @@ "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, "license": "MIT", - "optional": true, "dependencies": { "is-extglob": "^2.1.1" }, @@ -1786,12 +2772,89 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=0.12.0" } }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/keyv": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", + "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@keyv/serialize": "^1.1.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/loupe": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz", + "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==", + "dev": true, + "license": "MIT" + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -1814,8 +2877,10 @@ "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" @@ -1828,8 +2893,10 @@ "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=8.6" }, @@ -1858,6 +2925,29 @@ "node": ">= 0.6" } }, + "node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, "node_modules/nanoid": { "version": "3.3.11", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", @@ -1876,12 +2966,121 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, "node_modules/node-addon-api": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", + "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true + }, + "node_modules/nth-check": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/pathval": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz", + "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.16" + } }, "node_modules/picocolors": { "version": "1.1.1", @@ -1895,7 +3094,6 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -1931,12 +3129,66 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/postcss-selector-parser": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz", + "integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, "node_modules/proxy-from-env": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", "license": "MIT" }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/qified": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz", + "integrity": "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hookified": "^2.1.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/qified/node_modules/hookified": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/hookified/-/hookified-2.2.0.tgz", + "integrity": "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==", + "dev": true, + "license": "MIT" + }, "node_modules/qrcode.vue": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/qrcode.vue/-/qrcode.vue-3.6.0.tgz", @@ -1950,7 +3202,10 @@ "version": "4.1.2", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 14.18.0" }, @@ -2008,7 +3263,9 @@ "version": "1.97.2", "resolved": "https://registry.npmjs.org/sass/-/sass-1.97.2.tgz", "integrity": "sha512-y5LWb0IlbO4e97Zr7c3mlpabcbBtS+ieiZ9iwDooShpFKWXf62zz5pEPdwrLYm+Bxn1fnbwFGzHuCLSA9tBmrw==", + "dev": true, "license": "MIT", + "optional": true, "peer": true, "dependencies": { "chokidar": "^4.0.0", @@ -2025,6 +3282,49 @@ "@parcel/watcher": "^2.4.1" } }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", @@ -2034,16 +3334,47 @@ "node": ">=0.10.0" } }, - "node_modules/sweetalert2": { - "version": "11.26.17", - "resolved": "https://registry.npmjs.org/sweetalert2/-/sweetalert2-11.26.17.tgz", - "integrity": "sha512-kkaySn1IRfwNlf9AkZVqDmBINDWw9NRR6Ij0O5dBRBOD1+mbtZJWxxR9/pA90nce9E5tIIkJ7SWij4rMWXtA1g==", + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, + "node_modules/strip-literal": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz", + "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==", + "dev": true, "license": "MIT", + "dependencies": { + "js-tokens": "^9.0.1" + }, "funding": { - "type": "individual", - "url": "https://github.com/sponsors/limonte" + "url": "https://github.com/sponsors/antfu" } }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz", + "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==", + "dev": true, + "license": "MIT" + }, "node_modules/tinyglobby": { "version": "0.2.15", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", @@ -2061,12 +3392,44 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinypool": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz", + "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.0.0 || >=20.0.0" + } + }, + "node_modules/tinyrainbow": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz", + "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tinyspy": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.6.tgz", + "integrity": "sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "is-number": "^7.0.0" }, @@ -2074,13 +3437,42 @@ "node": ">=8.0" } }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + }, "node_modules/vite": { "version": "7.3.1", "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.27.0", "fdir": "^6.5.0", @@ -2150,12 +3542,107 @@ } } }, + "node_modules/vite-node": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz", + "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==", + "dev": true, + "license": "MIT", + "dependencies": { + "cac": "^6.7.14", + "debug": "^4.4.1", + "es-module-lexer": "^1.7.0", + "pathe": "^2.0.3", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0" + }, + "bin": { + "vite-node": "vite-node.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/vitest": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.7.tgz", + "integrity": "sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/expect": "3.2.7", + "@vitest/mocker": "3.2.7", + "@vitest/pretty-format": "^3.2.7", + "@vitest/runner": "3.2.7", + "@vitest/snapshot": "3.2.7", + "@vitest/spy": "3.2.7", + "@vitest/utils": "3.2.7", + "chai": "^5.2.0", + "debug": "^4.4.1", + "expect-type": "^1.2.1", + "magic-string": "^0.30.17", + "pathe": "^2.0.3", + "picomatch": "^4.0.2", + "std-env": "^3.9.0", + "tinybench": "^2.9.0", + "tinyexec": "^0.3.2", + "tinyglobby": "^0.2.14", + "tinypool": "^1.1.1", + "tinyrainbow": "^2.0.0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0", + "vite-node": "3.2.4", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@types/debug": "^4.1.12", + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "@vitest/browser": "3.2.7", + "@vitest/ui": "3.2.7", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@types/debug": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, "node_modules/vue": { "version": "3.5.26", "resolved": "https://registry.npmjs.org/vue/-/vue-3.5.26.tgz", "integrity": "sha512-SJ/NTccVyAoNUJmkM9KUqPcYlY+u8OVL1X5EW9RIs3ch5H2uERxyyIUI4MRxVCSOiEcupX9xNGde1tL9ZKpimA==", "license": "MIT", - "peer": true, "dependencies": { "@vue/compiler-dom": "3.5.26", "@vue/compiler-sfc": "3.5.26", @@ -2172,6 +3659,31 @@ } } }, + "node_modules/vue-eslint-parser": { + "version": "10.4.1", + "resolved": "https://registry.npmjs.org/vue-eslint-parser/-/vue-eslint-parser-10.4.1.tgz", + "integrity": "sha512-Gk6gRDj0n/fkRa3C3l0bBheoBckUq/Rs0F/TvMWIS6nzzx67amAViMe9CkNgsP2tXyQONvGiHQESHwFtZ3aYDA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "debug": "^4.4.0", + "eslint-scope": "^8.2.0 || ^9.0.0", + "eslint-visitor-keys": "^4.2.0 || ^5.0.0", + "espree": "^10.3.0 || ^11.0.0", + "esquery": "^1.6.0", + "semver": "^7.6.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://github.com/sponsors/mysticatea" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0" + } + }, "node_modules/vue-router": { "version": "4.6.4", "resolved": "https://registry.npmjs.org/vue-router/-/vue-router-4.6.4.tgz", @@ -2186,6 +3698,72 @@ "peerDependencies": { "vue": "^3.5.0" } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } } } } diff --git a/APP_UI/package.json b/APP_UI/package.json index 6d5e61c..f8a4961 100644 --- a/APP_UI/package.json +++ b/APP_UI/package.json @@ -6,7 +6,9 @@ "scripts": { "dev": "vite", "build": "vite build", - "preview": "vite preview" + "preview": "vite preview", + "test": "vitest run", + "lint": "eslint src" }, "dependencies": { "@fortawesome/fontawesome-free": "^7.1.0", @@ -14,13 +16,16 @@ "bootstrap": "^5.3.8", "chart.js": "^4.5.1", "qrcode.vue": "^3.6.0", - "sass": "^1.97.2", - "sweetalert2": "^11.26.17", "vue": "^3.5.24", "vue-router": "^4.6.4" }, "devDependencies": { + "@eslint/js": "^10.0.1", "@vitejs/plugin-vue": "^6.0.1", - "vite": "^7.2.4" + "eslint": "^10.12.0", + "eslint-plugin-vue": "^10.11.1", + "globals": "^17.13.0", + "vite": "^7.2.4", + "vitest": "^3.2.4" } } diff --git a/APP_UI/public/vite.svg b/APP_UI/public/vite.svg deleted file mode 100644 index e7b8dfb..0000000 --- a/APP_UI/public/vite.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/APP_UI/src/App.vue b/APP_UI/src/App.vue index 88b824f..340a152 100644 --- a/APP_UI/src/App.vue +++ b/APP_UI/src/App.vue @@ -13,7 +13,7 @@