3 Commits
Author SHA1 Message Date
asminme f4929c7cac 1.0.5 - opisy usług w przekierowaniach
Wydanie WGTools-Extended / release (push) Successful in 11s
2026-10-30 13:15:39 +01:00
asminme 6e7eaa9282 1.0.4 - ograniczenia IP i edycja przekierowań
Wydanie WGTools-Extended / release (push) Successful in 15s
2026-10-30 05:12:47 +01:00
asminme 3841e93e32 1.0.3 - poprawa wydajności panelu
Wydanie WGTools-Extended / release (push) Successful in 12s
2026-10-30 03:20:21 +01:00
21 changed files with 327 additions and 41 deletions

No files matched your search

+15
View File
@@ -1,5 +1,20 @@
# Changelog
## v1.0.5
- Dodano konfigurowalne opisy usług i potwierdzenie odpowiedzialności przy przekierowaniach.
- Poprawiono wygląd pola ograniczenia adresów IP.
## v1.0.4
- Dodano ograniczanie dostępu do przekierowanych portów według adresów źródłowych IPv4.
- Dodano edycję przekierowań i wybór adresu klienta z listy.
## v1.0.3
- Ograniczono odświeżanie panelu w ukrytych kartach i liczbę odczytów bazy danych.
- Przyspieszono wyszukiwanie historii połączeń oraz zmieniono domyślny interwał odświeżania nowych instalacji na 10 sekund.
## v1.0.2
- Poprawiono wybór marki i przypisywanie uprawnień do sieci.
+2
View File
@@ -26,6 +26,8 @@ Podczas tworzenia lub edycji sieci wybierz sposób nasłuchiwania i interfejs al
W **Ustawienia → Użytkownicy → Uprawnienia** administrator wybiera sieci dostępne dla użytkownika i dozwolone w nich działania. W **Serwer → Grupy publicznych adresów IPv4** można dodatkowo współdzielić adresy między sieciami.
Przy dodawaniu lub edycji przekierowania portu można wybrać klienta z listy i ograniczyć dostęp do wskazanych adresów źródłowych IPv4. Kilka adresów należy oddzielić przecinkami; bez ograniczenia port jest dostępny ze wszystkich adresów.
## Aktualizacja
Pobierz pakiet `.bin` z wydania WGTools-Extended i wgraj go w ustawieniach panelu. Przed aktualizacją program tworzy kopię zapasową i kopię umożliwiającą przywrócenie poprzedniej wersji.
+1 -1
View File
@@ -1 +1 @@
Fixes bugs and improves network configuration, user permissions and branding.
Dodano opisy usług i potwierdzenie odpowiedzialności przy przekierowaniach portów oraz poprawiono wygląd pola adresów IP.
+1 -1
View File
@@ -1 +1 @@
1.0.2
1.0.5
+1
View File
@@ -98,6 +98,7 @@ def init_audit_database() -> None:
details TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_audit_log_created_at ON audit_log(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_connection_lookup ON audit_log(action, object, created_at DESC, id DESC);
CREATE TABLE IF NOT EXISTS audit_wg_connection_state (
interface TEXT NOT NULL,
public_key TEXT NOT NULL,
+2 -1
View File
@@ -76,7 +76,8 @@ def init_database() -> None:
conn.execute("ALTER TABLE user_access ADD COLUMN permissions TEXT NOT NULL DEFAULT '{}'")
def get_user_access(user_id: int) -> dict[str, Any]:
def get_user_access(user_id: int, *, initialize: bool = True) -> dict[str, Any]:
if initialize:
init_database()
with _connect() as conn:
row = conn.execute("SELECT role,interfaces,permissions FROM user_access WHERE user_id=?", (int(user_id),)).fetchone()
+2 -1
View File
@@ -45,6 +45,7 @@ ALLOWED_ACTIONS = {
"extended_ip_groups_set",
"extended_forward_get",
"extended_forward_add",
"extended_forward_update",
"extended_forward_delete",
"route_create",
"route_update",
@@ -87,7 +88,7 @@ def run_helper(action: str, payload: dict[str, Any] | None = None, *, interface:
# helper enough time to finish its transactional rollback/commit path
# instead of killing it mid-update.
timeout = 120
elif action in {"raw_config_apply", "server_settings_apply", "extended_snat_apply", "extended_listen_apply", "extended_forward_add", "extended_forward_delete", "route_create", "route_update", "route_delete", "access_rule_create", "access_rule_update", "access_rule_delete"}:
elif action in {"raw_config_apply", "server_settings_apply", "extended_snat_apply", "extended_listen_apply", "extended_forward_add", "extended_forward_update", "extended_forward_delete", "route_create", "route_update", "route_delete", "access_rule_create", "access_rule_update", "access_rule_delete"}:
timeout = 90
elif action == "migration_backup_create":
timeout = 45
+32 -6
View File
@@ -4,6 +4,7 @@ import sqlite3
import time
import re
import base64
import json
from pathlib import Path
from typing import Any
@@ -12,10 +13,26 @@ from .settings import DATABASE_PATH, ONLINE_THRESHOLD_SECONDS, REFRESH_SECONDS
DEFAULT_BACKUP_RETENTION = 20
def get_service_policy() -> dict[str, Any]:
return json.loads(_get('forward_service_policy', '{"enabled":false,"mode":"list","services":[]}'))
def update_service_policy(enabled: bool, mode: str, services: list[str]) -> dict[str, Any]:
if mode not in {'list', 'custom', 'combo'}:
raise ValueError('Nieprawidłowy tryb usług')
services = list(dict.fromkeys(s.strip() for s in services if s.strip()))
if len(services) > 1000 or any(len(s) > 120 or any(ord(c) < 32 for c in s) or s.casefold() == 'other' for s in services):
raise ValueError('Nieprawidłowa lista usług')
if enabled and mode in {'list', 'combo'} and not services:
raise ValueError('Dodaj co najmniej jedną usługę do listy')
policy = {'enabled': enabled, 'mode': mode, 'services': services}
_set('forward_service_policy', json.dumps(policy, ensure_ascii=True))
return policy
def get_branding() -> dict[str, Any]:
return {"name": _get("brand_name", "WGTools-Extended"),
"color": _get("brand_color", "#8f1f27"),
"logo": _get("brand_logo", "")}
values = _get_many({"brand_name": "WGTools-Extended", "brand_color": "#8f1f27", "brand_logo": ""})
return {"name": values["brand_name"], "color": values["brand_color"], "logo": values["brand_logo"]}
def update_branding(name: str, color: str, logo: str) -> dict[str, Any]:
@@ -68,6 +85,14 @@ def _get(key: str, default: str) -> str:
return str(row["value"]) if row else default
def _get_many(defaults: dict[str, str]) -> dict[str, str]:
init_preferences()
with _connect() as conn:
placeholders = ",".join("?" for _ in defaults)
rows = conn.execute(f"SELECT key,value FROM app_settings WHERE key IN ({placeholders})", tuple(defaults)).fetchall()
return {**defaults, **{str(row["key"]): str(row["value"]) for row in rows}}
def _set(key: str, value: str) -> None:
init_preferences()
with _connect() as conn:
@@ -81,9 +106,10 @@ def _set(key: str, value: str) -> None:
def get_preferences() -> dict[str, Any]:
refresh = int(_get("refresh_seconds", str(REFRESH_SECONDS)))
threshold = int(_get("online_threshold_seconds", str(ONLINE_THRESHOLD_SECONDS)))
retention = int(_get("backup_retention", str(DEFAULT_BACKUP_RETENTION)))
values = _get_many({"refresh_seconds": str(REFRESH_SECONDS), "online_threshold_seconds": str(ONLINE_THRESHOLD_SECONDS), "backup_retention": str(DEFAULT_BACKUP_RETENTION)})
refresh = int(values["refresh_seconds"])
threshold = int(values["online_threshold_seconds"])
retention = int(values["backup_retention"])
return {
"refresh_seconds": max(2, min(refresh, 60)),
"online_threshold_seconds": max(30, min(threshold, 3600)),
+1 -1
View File
@@ -7,7 +7,7 @@ APP_NAME = "WGTools-Extended"
VERSION = Path(__file__).resolve().parents[2].joinpath("VERSION").read_text().strip()
WG_INTERFACE = os.getenv("WGTOOLS_INTERFACE", "wg0")
HELPER_PATH = os.getenv("WGTOOLS_HELPER", "/usr/local/libexec/wgtools-helper")
REFRESH_SECONDS = int(os.getenv("WGTOOLS_REFRESH_SECONDS", "5"))
REFRESH_SECONDS = int(os.getenv("WGTOOLS_REFRESH_SECONDS", "10"))
ONLINE_THRESHOLD_SECONDS = int(os.getenv("WGTOOLS_ONLINE_THRESHOLD_SECONDS", "180"))
DATABASE_PATH = os.getenv("WGTOOLS_DATABASE", "/var/lib/wgtools/wgtools.db")
SESSION_KEY_FILE = os.getenv("WGTOOLS_SESSION_KEY_FILE", "/var/lib/wgtools/session.key")
+72 -10
View File
@@ -30,7 +30,7 @@ from app.core.auth import (
from app.core.audit import init_audit_database, list_audit, merge_wireguard_last_seen, record_wireguard_connections, write_audit
from app.core.helper import HelperError, run_helper
from app.core.settings import APP_NAME, ONLINE_THRESHOLD_SECONDS, REFRESH_SECONDS, SESSION_MAX_AGE_SECONDS, VERSION, WG_INTERFACE
from app.core.preferences import get_preferences, init_preferences, update_preferences, get_branding, update_branding
from app.core.preferences import get_preferences, init_preferences, update_preferences, get_branding, update_branding, get_service_policy, update_service_policy
from app.core.telegram_config import get_telegram_settings, init_telegram_settings, test_telegram_connection, update_telegram_settings
from app.core.mail_config import (
get_mail_settings, init_mail_settings, mask_email, password_recovery_available,
@@ -436,7 +436,7 @@ class NodeSettingsRequest(BaseModel):
class AppSettingsRequest(BaseModel):
refresh_seconds: int = Field(default=5, ge=2, le=60)
refresh_seconds: int = Field(default=10, ge=2, le=60)
online_threshold_seconds: int = Field(default=180, ge=30, le=3600)
backup_retention: int = Field(default=20, ge=1, le=200)
@@ -476,6 +476,20 @@ class ExtendedForwardRequest(BaseModel):
target_ip: str = Field(max_length=15)
target_port: int = Field(ge=1, le=65535)
protocol: str = Field(max_length=4)
restrict_sources: bool = False
allowed_sources: list[str] = Field(default_factory=list, max_length=32)
service: str = Field(default='', max_length=120)
confirmation: str = Field(default='', max_length=200)
class ServicePolicyRequest(BaseModel):
enabled: bool = False
mode: str = 'list'
services: list[str] = Field(default_factory=list, max_length=1000)
class ExtendedForwardUpdateRequest(ExtendedForwardRequest):
id: str = Field(pattern=r"^[0-9a-f]{16}$")
class ExtendedForwardDeleteRequest(BaseModel):
@@ -522,7 +536,7 @@ def is_internal_interface(name: str) -> bool:
def request_interface(request: Request) -> str:
current = getattr(request.state, "current_user", None)
access = get_user_access(int(current["id"])) if current else {"role": "admin", "interfaces": []}
access = getattr(request.state, "access", None) or (get_user_access(int(current["id"])) if current else {"role": "admin", "interfaces": []})
default_iface = (access["interfaces"][0] if access["role"] == "user" and access["interfaces"] else WG_INTERFACE)
value = (request.cookies.get("wgtools_interface") or default_iface).strip()
if access["role"] == "user" and access["interfaces"] and value not in access["interfaces"]:
@@ -580,7 +594,7 @@ def render(request: Request, template: str, page: str, title_key: str) -> HTMLRe
"language": language,
"messages_json": messages_json,
"tr": tr,
"current_user": get_user(int(request.session.get("user_id", 0))) if request.session.get("user_id") else None,
"current_user": getattr(request.state, "current_user", None),
"help_sections": get_help_sections(language) if request.state.access['role'] == 'admin' else [],
},
headers={"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet"},
@@ -649,9 +663,9 @@ async def require_authentication(request: Request, call_next):
if path in PUBLIC_PATHS or path.startswith(PUBLIC_PREFIXES):
return await call_next(request)
users_exist = user_count() > 0
user_id = request.session.get("user_id")
current = get_user(int(user_id)) if user_id else None
users_exist = bool(current) or user_count() > 0
if user_id and not current:
request.session.clear()
if current:
@@ -682,10 +696,10 @@ async def require_authentication(request: Request, call_next):
return RedirectResponse(url=f"{app_url(request, '/login')}?next={next_path}", status_code=303)
request.state.current_user = current
access = get_user_access(int(current["id"]))
access = get_user_access(int(current["id"]), initialize=False)
request.state.access = access
if access["role"] != "admin":
allowed = {"/", "/clients", "/api/interfaces", "/api/snapshot", "/api/metrics/history", "/api/app-settings", "/api/auth/logout", "/api/clients/create", "/api/clients/update", "/api/clients/credentials/rotate", "/api/clients/config", "/api/clients/config/download", "/api/clients/qr", "/api/extended/forwardings", "/api/extended/forwardings/delete"}
allowed = {"/", "/clients", "/api/interfaces", "/api/snapshot", "/api/metrics/history", "/api/app-settings", "/api/auth/logout", "/api/clients/create", "/api/clients/update", "/api/clients/credentials/rotate", "/api/clients/config", "/api/clients/config/download", "/api/clients/qr", "/api/extended/forwardings", "/api/extended/forwardings/update", "/api/extended/forwardings/delete"}
if path not in allowed or (path == "/api/app-settings" and request.method != "GET"):
return JSONResponse(status_code=403, content={"ok": False, "error": "Brak uprawnień"})
if path.startswith("/api/clients/") or path.startswith("/api/extended/forwardings") or path == "/api/snapshot":
@@ -939,6 +953,44 @@ def api_branding(payload: BrandingRequest, request: Request):
return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)})
@app.get('/api/service-policy')
def api_service_policy_get():
return {'ok': True, 'policy': get_service_policy()}
@app.post('/api/service-policy')
def api_service_policy_set(payload: ServicePolicyRequest, request: Request):
try:
policy = update_service_policy(**payload.model_dump())
audit_action(request, 'settings.service_policy_updated', object='forwarding services', result='saved', details=policy)
return {'ok': True, 'policy': policy}
except ValueError as exc:
return JSONResponse(status_code=400, content={'ok': False, 'error': str(exc)})
SERVICE_CONFIRMATION = 'Nie będę używać tego tunelu do złośliwego oprogramowania, nadużyć ani niedozwolonych usług.'
def forward_payload(payload: ExtendedForwardRequest, request: Request) -> dict:
data = payload.model_dump()
policy = get_service_policy()
service = payload.service.strip()
if policy['enabled']:
if not service or any(ord(c) < 32 for c in service):
raise ValueError('Podaj nazwę usługi')
if policy['mode'] == 'list' and service not in policy['services']:
raise ValueError('Wybierz usługę z listy')
if payload.confirmation != SERVICE_CONFIRMATION:
raise ValueError('Wpisz dokładnie wymagane potwierdzenie odpowiedzialności')
data['service'] = service
data['responsibility'] = {'text': SERVICE_CONFIRMATION, 'user': audit_username(request), 'time': int(time.time())}
else:
data['service'] = ''
data['responsibility'] = None
data.pop('confirmation', None)
return data
@app.get("/api/update/check")
def api_update_check(request: Request):
try:
@@ -1754,7 +1806,7 @@ def api_extended_groups_set(payload: ExtendedIPGroupRequest, request: Request):
@app.get("/api/extended/forwardings")
def api_extended_forward_get(request: Request):
try:
return run_helper("extended_forward_get", interface=request_interface(request))
return {**run_helper("extended_forward_get", interface=request_interface(request)), 'service_policy': get_service_policy()}
except HelperError as exc:
return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)})
@@ -1762,10 +1814,20 @@ def api_extended_forward_get(request: Request):
@app.post("/api/extended/forwardings")
def api_extended_forward_add(payload: ExtendedForwardRequest, request: Request):
try:
result = run_helper("extended_forward_add", payload.model_dump(), interface=request_interface(request))
result = run_helper("extended_forward_add", forward_payload(payload, request), interface=request_interface(request))
audit_action(request, "network.forward_added", object=request_interface(request), result="saved", details=payload.model_dump())
return result
except HelperError as exc:
except (HelperError, ValueError) as exc:
return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)})
@app.post("/api/extended/forwardings/update")
def api_extended_forward_update(payload: ExtendedForwardUpdateRequest, request: Request):
try:
result = run_helper("extended_forward_update", forward_payload(payload, request), interface=request_interface(request))
audit_action(request, "network.forward_updated", object=request_interface(request), result="saved", details=payload.model_dump())
return result
except (HelperError, ValueError) as exc:
return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)})
+38 -9
View File
@@ -11,7 +11,7 @@
return nativeFetch(input, init);
};
const page = document.body.dataset.page;
const refreshSeconds = Number(document.body.dataset.refresh || '5');
const refreshSeconds = Number(document.body.dataset.refresh || '10');
const threshold = Number(document.body.dataset.onlineThreshold || '180');
let snapshot = null;
let interfacesData = {interfaces:[], suggested:null};
@@ -1083,7 +1083,7 @@
const loadGroups=async()=>{
try{const r=await fetch(appUrl('/api/extended/ip-groups'));const d=await r.json();if(!r.ok)throw new Error(d.error);
$('extended-groups-list').innerHTML=Object.entries(d.groups||{}).filter(([name])=>!name.startsWith('_wgext_network_')).map(([name,g])=>`<div class="group-row"><div><b>${esc(name)}</b><p>${esc((g.addresses||[]).join(', '))}</p><p>Sieci: ${esc((g.interfaces||[]).join(', '))}</p></div><div class="action-row"><button class="btn small" type="button" data-ext-group-edit="${esc(name)}">Edytuj</button><button class="btn small danger" type="button" data-ext-group-delete="${esc(name)}">Usuń</button></div></div>`).join('')||'<p>Brak grup adresów.</p>';
$('extended-groups-list').insertAdjacentHTML('beforeend',`<h3>Przegląd przekierowań</h3>`+(d.forwards||[]).map(f=>`<p>${esc(f.interface)}: ${esc(f.public_ip)}:${Number(f.public_port)} / ${esc(f.protocol)} → ${esc(f.target_ip)}:${Number(f.target_port)}</p>`).join(''));
$('extended-groups-list').insertAdjacentHTML('beforeend',`<h3>Przegląd przekierowań</h3>`+(d.forwards||[]).map(f=>`<p>${esc(f.interface)}: ${esc(f.public_ip)}:${Number(f.public_port)} / ${esc(f.protocol)} → ${esc(f.target_ip)}:${Number(f.target_port)}${f.service?' · Usługa: '+esc(f.service):''}${f.responsibility?' · Potwierdził: '+esc(f.responsibility.user)+' ('+esc(new Date(f.responsibility.time*1000).toLocaleString('pl-PL'))+')':''}</p>`).join(''));
return d.groups||{};
}catch(err){operationStatus('extended-group-status',err.message,'error');return {};}
};
@@ -1093,9 +1093,24 @@
loadGroups();
}
if(page==='clients' && $('extended-forward-form')){
const loadForwards=async()=>{const r=await fetch(appUrl('/api/extended/forwardings'));const d=await r.json();if(!r.ok)throw new Error(d.error);$('extended-forward-public').innerHTML=(d.addresses||[]).map(ip=>`<option value="${esc(ip)}">${esc(ip)}</option>`).join('');$('extended-forward-list').innerHTML=(d.forwards||[]).map(f=>`<div class="group-row"><span>${esc(f.public_ip)}:${Number(f.public_port)} / ${esc(f.protocol)} → ${esc(f.target_ip)}:${Number(f.target_port)}</span><button class="btn small danger" type="button" data-ext-forward-delete="${esc(f.id)}">Usuń</button></div>`).join('')||'<p>Brak przekierowań.</p>';};
$('extended-forward-form').addEventListener('submit',async e=>{e.preventDefault();try{const r=await fetch(appUrl('/api/extended/forwardings'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({public_ip:$('extended-forward-public').value,public_port:Number($('extended-forward-public-port').value),target_ip:$('extended-forward-target').value.trim(),target_port:Number($('extended-forward-target-port').value),protocol:$('extended-forward-protocol').value})});const d=await r.json();if(!r.ok)throw new Error(d.error);await loadForwards();operationStatus('extended-forward-status','Dodano przekierowanie.','success');}catch(err){operationStatus('extended-forward-status',err.message,'error');}});
$('extended-forward-list').addEventListener('click',async e=>{const b=e.target.closest('[data-ext-forward-delete]');if(!b||!confirm('Usunąć przekierowanie?'))return;try{const r=await fetch(appUrl('/api/extended/forwardings/delete'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:b.dataset.extForwardDelete})});const d=await r.json();if(!r.ok)throw new Error(d.error);await loadForwards();}catch(err){operationStatus('extended-forward-status',err.message,'error');}});
let forwards=[], editing='';
let servicePolicy={enabled:false,mode:'list',services:[]};
const syncService=()=>{
const on=servicePolicy.enabled, mode=servicePolicy.mode, selected=$('forward-service-select').value;
$('forward-service-section').hidden=!on;
$('forward-service-select-wrap').hidden=!on||mode==='custom';
$('forward-service-custom-wrap').hidden=!on||(mode!=='custom'&&selected!=='__other__');
$('forward-service-select').required=on&&mode!=='custom';
$('forward-service-custom').required=on&&(mode==='custom'||selected==='__other__');
$('forward-service-confirmation').required=on;
};
$('forward-service-select').addEventListener('change',syncService);
const reset=()=>{editing='';$('extended-forward-form').reset();$('extended-forward-restrict').checked=false;syncSources();$('extended-forward-submit').textContent='Dodaj przekierowanie';$('extended-forward-cancel').hidden=true;syncService();};
const syncSources=()=>{const enabled=$('extended-forward-restrict').checked;$('extended-forward-sources-wrap').hidden=!enabled;$('extended-forward-sources').required=enabled;};
const loadForwards=async()=>{const r=await fetch(appUrl('/api/extended/forwardings'));const d=await r.json();if(!r.ok)throw new Error(d.error);forwards=d.forwards||[];servicePolicy=d.service_policy||servicePolicy;const sel=$('forward-service-select');sel.innerHTML='<option value="">Wybierz usługę</option>'+servicePolicy.services.map(x=>`<option value="${esc(x)}">${esc(x)}</option>`).join('')+(servicePolicy.mode==='combo'?'<option value="__other__">Inna</option>':'');syncService();const current=$('extended-forward-public').value;$('extended-forward-public').innerHTML=(d.addresses||[]).map(ip=>`<option value="${esc(ip)}">${esc(ip)}</option>`).join('');if((d.addresses||[]).includes(current))$('extended-forward-public').value=current;$('extended-forward-list').innerHTML=forwards.map(f=>`<div class="group-row"><div><span>${esc(f.public_ip)}:${Number(f.public_port)} / ${esc(f.protocol)} → ${esc(f.target_ip)}:${Number(f.target_port)}</span><p>${f.allowed_sources?.length?'Dozwolone adresy: '+esc(f.allowed_sources.join(', ')):'Dostęp ze wszystkich adresów'}</p></div><div class="action-row"><button class="btn small" type="button" data-ext-forward-edit="${esc(f.id)}">Edytuj</button><button class="btn small danger" type="button" data-ext-forward-delete="${esc(f.id)}">Usuń</button></div></div>`).join('')||'<p>Brak przekierowań.</p>';};
$('extended-forward-restrict').addEventListener('change',syncSources);$('extended-forward-cancel').addEventListener('click',reset);
$('extended-forward-form').addEventListener('submit',async e=>{e.preventDefault();const restricted=$('extended-forward-restrict').checked;const payload={public_ip:$('extended-forward-public').value,public_port:Number($('extended-forward-public-port').value),target_ip:$('extended-forward-target').value,target_port:Number($('extended-forward-target-port').value),protocol:$('extended-forward-protocol').value,service:servicePolicy.enabled?(servicePolicy.mode==='custom'||$('forward-service-select').value==='__other__' ? $('forward-service-custom').value : $('forward-service-select').value):'',confirmation:servicePolicy.enabled?$('forward-service-confirmation').value:'',restrict_sources:restricted,allowed_sources:restricted?$('extended-forward-sources').value.split(',').map(x=>x.trim()).filter(Boolean):[]};if(editing)payload.id=editing;const button=$('extended-forward-submit');button.disabled=true;try{const r=await fetch(appUrl(editing?'/api/extended/forwardings/update':'/api/extended/forwardings'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw new Error(d.error);reset();await loadForwards();operationStatus('extended-forward-status','Zapisano przekierowanie.','success');}catch(err){operationStatus('extended-forward-status',err.message,'error');}finally{button.disabled=false;}});
$('extended-forward-list').addEventListener('click',async e=>{const edit=e.target.closest('[data-ext-forward-edit]'),del=e.target.closest('[data-ext-forward-delete]');if(edit){const f=forwards.find(x=>x.id===edit.dataset.extForwardEdit);if(!f)return;editing=f.id;$('extended-forward-public').value=f.public_ip;$('extended-forward-public-port').value=f.public_port;$('extended-forward-target').value=f.target_ip;$('extended-forward-target-port').value=f.target_port;$('extended-forward-protocol').value=f.protocol;const custom=servicePolicy.mode==='custom'||!servicePolicy.services.includes(f.service);$('forward-service-select').value=custom?'__other__':(f.service||'');$('forward-service-custom').value=custom?(f.service||''):'';$('forward-service-confirmation').value='';syncService();$('extended-forward-restrict').checked=Boolean(f.allowed_sources?.length);$('extended-forward-sources').value=(f.allowed_sources||[]).join(', ');syncSources();$('extended-forward-submit').textContent='Zapisz zmiany';$('extended-forward-cancel').hidden=false;operationStatus('extended-forward-status','Edytujesz przekierowanie.','working');$('extended-forward-form').scrollIntoView({behavior:'smooth',block:'center'});return;}if(!del||!confirm('Usunąć przekierowanie?'))return;try{const r=await fetch(appUrl('/api/extended/forwardings/delete'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:del.dataset.extForwardDelete})});const d=await r.json();if(!r.ok)throw new Error(d.error);if(editing===del.dataset.extForwardDelete)reset();await loadForwards();}catch(err){operationStatus('extended-forward-status',err.message,'error');}});
loadForwards().catch(err=>operationStatus('extended-forward-status',err.message,'error'));
}
if(page==='server' && $('extended-listen-form')){
@@ -1154,6 +1169,8 @@
}
function renderClients(d){
const peers=d.peers||[]; const body=$('client-body'); const add=$('add-client-button'); const manage=$('manage-groups-button');
const targets=$('extended-forward-target');if(targets){const selected=targets.value;const valid=peers.map(p=>({ip:String(p.vpn_address||'').split('/')[0],name:p.name||'Klient'})).filter(p=>/^\d{1,3}(?:\.\d{1,3}){3}$/.test(p.ip));targets.innerHTML='<option value="">Wybierz klienta</option>'+valid.map(p=>`<option value="${esc(p.ip)}">${esc(p.name)} · ${esc(p.ip)}</option>`).join('');if(valid.some(p=>p.ip===selected))targets.value=selected;}
if(add)add.disabled=!d.wireguard?.config_exists; if(manage)manage.disabled=!d.wireguard?.config_exists; syncClientQuickSearchClear();
if(!peers.length){body.innerHTML=`<tr><td colspan="9" class="empty">${esc(t('clients.no_peers','No peers found'))}</td></tr>`;return;}
const visible=peers.map((p,index)=>({p,index})).filter(item=>clientMatchesQuickSearch(item.p));
@@ -2036,6 +2053,12 @@
}
function bindUserManagement(){
if($('service-policy-form')){
const sync=()=>{$('service-policy-options').hidden=!$('service-policy-enabled').checked;$('service-policy-list-wrap').hidden=$('service-policy-mode').value==='custom';};
$('service-policy-enabled').addEventListener('change',sync);$('service-policy-mode').addEventListener('change',sync);
fetch(appUrl('/api/service-policy')).then(r=>r.json()).then(d=>{if(!d.ok)throw new Error(d.error);$('service-policy-enabled').checked=d.policy.enabled;$('service-policy-mode').value=d.policy.mode;$('service-policy-list').value=d.policy.services.join('\n');sync();}).catch(e=>operationStatus('service-policy-status',e.message,'error'));
$('service-policy-form').addEventListener('submit',async e=>{e.preventDefault();try{const r=await fetch(appUrl('/api/service-policy'),{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({enabled:$('service-policy-enabled').checked,mode:$('service-policy-mode').value,services:$('service-policy-list').value.split(/\r?\n/).map(x=>x.trim()).filter(Boolean)})});const d=await r.json();if(!r.ok)throw new Error(d.error);operationStatus('service-policy-status','Zapisano ustawienia usług.','success');}catch(err){operationStatus('service-policy-status',err.message,'error');}});
}
$('branding-form')?.addEventListener('submit', async e=>{
e.preventDefault();
try {
@@ -2095,6 +2118,7 @@
auditAutoRefreshTimer=setInterval(()=>{
const modal=$('audit-modal');
if(!modal||modal.hidden){stopAuditAutoRefresh();return;}
if(document.hidden)return;
loadAudit({showLoading:false});
},interval);
}
@@ -2993,14 +3017,19 @@
if(page==='dashboard'){
loadMetricsHistory();
if(document.body.dataset.role==='admin')loadDashboardDiagnostics();
historyTimer=setInterval(loadMetricsHistory,60*1000);
if(document.body.dataset.role==='admin')dashboardDiagnosticsTimer=setInterval(loadDashboardDiagnostics,60*1000);
historyTimer=setInterval(()=>{if(!document.hidden)loadMetricsHistory();},60*1000);
if(document.body.dataset.role==='admin')dashboardDiagnosticsTimer=setInterval(()=>{if(!document.hidden)loadDashboardDiagnostics();},60*1000);
}
if(page==='server'){
loadServerDiagnostics();
serverDiagnosticsTimer=setInterval(loadServerDiagnostics,60*1000);
serverDiagnosticsTimer=setInterval(()=>{if(!document.hidden)loadServerDiagnostics();},60*1000);
}
if(page!=='settings'){
let refreshing=false;
const refreshVisible=async()=>{if(document.hidden||refreshing)return;refreshing=true;try{await fetchSnapshot(false);}finally{refreshing=false;}};
timer=setInterval(refreshVisible,Math.max(2,refreshSeconds)*1000);
document.addEventListener('visibilitychange',()=>{if(!document.hidden)refreshVisible();});
}
if(page!=='settings') timer=setInterval(()=>fetchSnapshot(false),Math.max(2,refreshSeconds)*1000);
}
boot();
})();
+14 -2
View File
@@ -17,11 +17,23 @@
<div class="setup-grid">
<label><span>Publiczny adres IPv4</span><select id="extended-forward-public" required></select></label>
<label><span>Port publiczny</span><input id="extended-forward-public-port" type="number" min="1" max="65535" required></label>
<label><span>Adres IPv4 klienta</span><input id="extended-forward-target" placeholder="10.0.2.2" maxlength="15" required></label>
<label><span>Klient i jego adres IPv4</span><select id="extended-forward-target" required><option value="">Wybierz klienta</option></select></label>
<label><span>Port klienta</span><input id="extended-forward-target-port" type="number" min="1" max="65535" required></label>
<label><span>Protokół</span><select id="extended-forward-protocol"><option value="tcp">TCP</option><option value="udp">UDP</option><option value="both">TCP i UDP</option></select></label>
</div>
<button class="btn primary" type="submit">Dodaj przekierowanie</button>
<label class="check-label"><input id="extended-forward-restrict" type="checkbox"><span>Ogranicz dostęp do wybranych adresów IP</span></label>
<label id="extended-forward-sources-wrap" class="field-block" hidden><span>Dozwolone adresy IPv4, oddzielone przecinkami</span><input id="extended-forward-sources" placeholder="89.144.32.110, 89.144.32.172"><small>Pozostałe adresy nie uzyskają dostępu do tego przekierowania.</small></label>
<div id="forward-service-section" hidden>
<div class="inline-note warn-note"><b>Co udostępniasz publicznie?</b><p>Opisz oprogramowanie lub serwer gry, który udostępniasz. Nie wpisuj „test” ani przypadkowych znaków. Może to spowodować wyłączenie tunelu lub zablokowanie konta.</p></div>
<div class="setup-grid section-space-small">
<label id="forward-service-select-wrap"><span>Opis usługi (wymagane)</span><select id="forward-service-select"></select><small>Wybierz usługę z listy lub, jeśli dostępna, opcję „Inna”.</small></label>
<label id="forward-service-custom-wrap"><span>Nazwa usługi (wymagane)</span><input id="forward-service-custom" maxlength="120" placeholder="Np. serwer gry"></label>
</div>
<div class="inline-note warn-note"><b>Korzystaj odpowiedzialnie</b><p>{{ branding.name or 'Panel' }}: usług nie wolno używać do złośliwego oprogramowania, phishingu, spamu, nieuprawnionego dostępu ani innych zabronionych działań. Niektóre programy są zabronione niezależnie od intencji, także w celach edukacyjnych lub badawczych.</p><p>Naruszenia skutkują trwałym zawieszeniem konta i utratą prawa do zwrotu. Aby kontynuować, wpisz dokładnie:</p><strong>Nie będę używać tego tunelu do złośliwego oprogramowania, nadużyć ani niedozwolonych usług.</strong></div>
<label class="field-block"><span>Potwierdzenie odpowiedzialności (wymagane)</span><input id="forward-service-confirmation" maxlength="200" autocomplete="off"></label>
</div>
<button class="btn primary" type="submit" id="extended-forward-submit">Dodaj przekierowanie</button>
<button class="btn" type="button" id="extended-forward-cancel" hidden>Anuluj edycję</button>
<div id="extended-forward-status" class="operation-status" hidden></div>
</form>
<div id="extended-forward-list" class="settings-form-pad"></div>
+11
View File
@@ -33,6 +33,17 @@
</div>
<div class="settings-tab-panel" data-settings-tab-panel="general">
<section class="card">
<div class="card-head"><h2>Usługi w przekierowaniach portów</h2></div>
<form id="service-policy-form" class="settings-form-pad">
<label class="check-label"><input id="service-policy-enabled" type="checkbox"><span>Chcę zbierać informacje o usługach</span></label>
<div id="service-policy-options" hidden>
<div class="setup-grid section-space-small"><label><span>Sposób określania usługi</span><select id="service-policy-mode"><option value="list">Tylko lista usług</option><option value="custom">Użytkownik wpisuje usługę</option><option value="combo">Lista usług i własna nazwa</option></select></label></div>
<label class="field-block" id="service-policy-list-wrap"><span>Lista usług — każda w osobnym wierszu</span><textarea id="service-policy-list" class="controlled-textarea" rows="8" placeholder="teamspeak3&#10;udp-generic&#10;wireguard"></textarea></label>
</div>
<div class="settings-save-row"><button class="btn primary" type="submit">Zapisz ustawienia usług</button></div><div id="service-policy-status" class="operation-status" hidden></div>
</form>
</section>
<div class="two-col">
<section class="card">
<div class="card-head"><h2 data-i18n="settings.appearance">{{ tr('settings.appearance') }}</h2></div>
+1 -1
View File
@@ -78,7 +78,7 @@ if [[ ! -f /etc/wgtools/wgtools.env ]]; then
WGTOOLS_INTERFACE=$WG_INTERFACE
WGTOOLS_PORT=$WEB_PORT
WGTOOLS_HELPER=/usr/local/libexec/wgtools-helper
WGTOOLS_REFRESH_SECONDS=5
WGTOOLS_REFRESH_SECONDS=10
WGTOOLS_ONLINE_THRESHOLD_SECONDS=180
WGTOOLS_DATABASE=/var/lib/wgtools/wgtools.db
WGTOOLS_SESSION_KEY_FILE=/var/lib/wgtools/session.key
+51 -6
View File
@@ -31,6 +31,7 @@ ALLOWED_ACTIONS.update({"extended_snat_get", "extended_snat_apply"})
ALLOWED_ACTIONS.add("extended_host_ips")
ALLOWED_ACTIONS.update({"extended_listen_get", "extended_listen_apply"})
ALLOWED_ACTIONS.update({"extended_ip_groups_get", "extended_ip_groups_set", "extended_forward_get", "extended_forward_add", "extended_forward_delete"})
ALLOWED_ACTIONS.add("extended_forward_update")
ALLOWED_ACTIONS.update({"update_file_schedule", "update_file_apply"})
ALLOWED_IFACE_RE = re.compile(r"^[A-Za-z0-9_.-]{1,15}$")
INTERNAL_INTERFACE_PREFIXES = ("wgrly", "wgnode")
@@ -4449,6 +4450,10 @@ def _extended_forwards(iface: str) -> list[dict[str, Any]]:
raise ValueError()
if row["protocol"] not in {"tcp", "udp", "both"} or not ALLOWED_IFACE_RE.fullmatch(row["device"]) or row["device"].startswith('-'):
raise ValueError()
sources = row.get("allowed_sources", [])
if not isinstance(sources, list) or len(sources) > 32:
raise ValueError()
row["allowed_sources"] = sorted({str(ipaddress.IPv4Address(value)) for value in sources})
except (KeyError, ValueError, TypeError) as exc:
raise ValueError(f"Nieprawidłowy wpis przekierowania w {iface}") from exc
result.append(row)
@@ -4500,6 +4505,9 @@ def extended_forward_get(iface: str) -> dict[str, Any]:
def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str, Any]:
complexity = sum((len(row.get('allowed_sources', [])) or 1) * (2 if row['protocol'] == 'both' else 1) for row in rows)
if complexity > 100:
raise ValueError("Zbyt wiele adresów źródłowych w przekierowaniach tej sieci")
prefix, section, suffix = _interface_section_parts(read_config_text(iface))
marker = f"wgext-forward-{iface}"
section = [line for line in section if not (line.strip().startswith("# WGEXT-FORWARD ") or (re.match(r"\s*Post(?:Up|Down)\s*=", line, re.I) and f"--comment {marker}-" in line))]
@@ -4510,9 +4518,19 @@ def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str
for proto in (["tcp", "udp"] if row["protocol"] == "both" else [row["protocol"]]):
tag = f"{marker}-{row['id']}-{proto}"
nat = f"-i {row['device']} -d {row['public_ip']} -p {proto} --dport {row['public_port']} -m comment --comment {tag}-nat -j DNAT --to-destination {row['target_ip']}:{row['target_port']}"
forward = f"-i {row['device']} -o {iface} -d {row['target_ip']} -p {proto} --dport {row['target_port']} -m comment --comment {tag}-in -j ACCEPT"
forward_match = f"-i {row['device']} -o {iface} -d {row['target_ip']} -p {proto} --dport {row['target_port']} -m conntrack --ctorigdst {row['public_ip']} --ctorigdstport {row['public_port']}"
reply = f"-i {iface} -o {row['device']} -s {row['target_ip']} -p {proto} --sport {row['target_port']} -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment {tag}-out -j ACCEPT"
for table, chain, rule in [(' -t nat', 'PREROUTING', nat), ('', 'FORWARD', forward), ('', 'FORWARD', reply)]:
rules = [(' -t nat', 'PREROUTING', nat), ('', 'FORWARD', reply)]
sources = row.get('allowed_sources', [])
if sources:
# Match the original public tuple even for connections created
# before an edit changed the destination client.
deny_match = f"-i {row['device']} -o {iface} -p {proto} -m conntrack --ctorigdst {row['public_ip']} --ctorigdstport {row['public_port']}"
rules.append(('', 'FORWARD', f"{deny_match} -m comment --comment {tag}-deny -j DROP"))
for index, source in enumerate(sources or ['']):
source_match = f" -s {source}" if source else ''
rules.append(('', 'FORWARD', f"{forward_match}{source_match} -m comment --comment {tag}-in{index} -j ACCEPT"))
for table, chain, rule in rules:
up.append(f"iptables -w{table} -I {chain} 1 {rule}")
down.append(f"iptables -w{table} -D {chain} {rule} 2>/dev/null || true")
if up:
@@ -4521,7 +4539,7 @@ def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str
return raw_config_apply(iface, {"content": "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"})
def extended_forward_add(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
def extended_forward_add(iface: str, payload: dict[str, Any], *, update_id: str = '') -> dict[str, Any]:
require_valid_iface(iface)
try:
public_ip = str(ipaddress.IPv4Address(payload.get("public_ip")))
@@ -4530,6 +4548,15 @@ def extended_forward_add(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
except (ValueError, TypeError) as exc:
raise ValueError("Nieprawidłowy adres lub port") from exc
protocol = str(payload.get("protocol") or "")
sources = payload.get('allowed_sources') or []
if not isinstance(sources, list) or len(sources) > 32:
raise ValueError("Można podać maksymalnie 32 adresy źródłowe")
try:
sources = sorted({str(ipaddress.IPv4Address(value)) for value in sources})
except (ValueError, TypeError) as exc:
raise ValueError("Podaj poprawne adresy źródłowe IPv4") from exc
if bool(payload.get('restrict_sources')) != bool(sources):
raise ValueError("Podaj co najmniej jeden adres IPv4 albo wyłącz ograniczenie")
if protocol not in {"tcp", "udp", "both"} or not (1 <= public_port <= 65535 and 1 <= target_port <= 65535):
raise ValueError("Nieprawidłowy protokół lub port")
if public_ip not in _extended_allowed(_extended_groups(), iface):
@@ -4549,14 +4576,26 @@ def extended_forward_add(iface: str, payload: dict[str, Any]) -> dict[str, Any]:
if "udp" in protocols and (other_cfg.get("interface") or {}).get("listen_port") == public_port:
raise ValueError("Ten port UDP jest używany przez WireGuard")
for row in _extended_forwards(other):
if other == iface and row['id'] == update_id:
continue
existing = {"tcp", "udp"} if row["protocol"] == "both" else {row["protocol"]}
if row["public_ip"] == public_ip and row["public_port"] == public_port and protocols & existing:
raise ValueError("Ten adres, port i protokół są już używane przez inne przekierowanie")
rows = _extended_forwards(iface)
if len(rows) >= 20:
if update_id and not any(row['id'] == update_id for row in rows):
raise ValueError("Nie znaleziono przekierowania")
if not update_id and len(rows) >= 20:
raise ValueError("Osiągnięto limit przekierowań w tej sieci")
row = {"id": secrets.token_hex(8), "public_ip": public_ip, "public_port": public_port, "target_ip": target_ip, "target_port": target_port, "protocol": protocol, "device": device}
result = _extended_write_forwards(iface, [*rows, row])
row = {"id": update_id or secrets.token_hex(8), "public_ip": public_ip, "public_port": public_port, "target_ip": target_ip, "target_port": target_port, "protocol": protocol, "device": device, "allowed_sources": sources}
if payload.get('service') and isinstance(payload.get('responsibility'), dict):
row['service'] = str(payload['service'])[:120]
row['responsibility'] = payload['responsibility']
elif update_id:
previous = next(item for item in rows if item['id'] == update_id)
for key in ('service', 'responsibility'):
if key in previous:
row[key] = previous[key]
result = _extended_write_forwards(iface, [*(item for item in rows if item['id'] != update_id), row])
return {**result, "forward": row}
@@ -6734,6 +6773,12 @@ def main() -> int:
elif action == "extended_forward_add":
payload = read_json_stdin()
result = locked_call(lambda: extended_forward_add(iface, payload))
elif action == "extended_forward_update":
payload = read_json_stdin()
identifier = str(payload.get('id') or '')
if not re.fullmatch(r'[0-9a-f]{16}', identifier):
raise ValueError("Nieprawidłowy identyfikator przekierowania")
result = locked_call(lambda: extended_forward_add(iface, payload, update_id=identifier))
elif action == "extended_forward_delete":
payload = read_json_stdin()
result = locked_call(lambda: extended_forward_delete(iface, payload))
+1
View File
@@ -51,6 +51,7 @@ def test_user_is_restricted_to_assigned_interface(tmp_path):
assert c.post('/api/clients/create', json={'name':'bad','type':'site_to_site','remote_networks':['10.1.0.0/16']}).status_code == 403
set_user_access(user['id'], 'user', ['wg1'], {'wg1':['add']})
assert c.post('/api/extended/forwardings', json={'public_ip':'192.0.2.1','public_port':1234,'target_ip':'10.0.0.2','target_port':1234,'protocol':'tcp'}).status_code == 403
assert c.post('/api/extended/forwardings/update', json={'id':'0123456789abcdef','public_ip':'192.0.2.1','public_port':1234,'target_ip':'10.0.0.2','target_port':1234,'protocol':'tcp'}).status_code == 403
assert c.post('/api/clients/update', json={'name':'peer','public_key':'x'*44}).status_code == 403
c.post('/api/auth/logout')
assert c.post('/api/auth/login', json={'username':'admin','password':'password123'}).status_code == 200
+27
View File
@@ -55,6 +55,33 @@ def test_rejects_foreign_target_and_wireguard_port(network):
m['extended_forward_add']('wg1', {**forward,'target_ip':'10.0.1.2','public_port':51822,'protocol':'udp'})
def test_forward_restricts_sources_and_can_be_edited(network):
m, configs = network
m['extended_ip_groups_set']({'name':'shared','addresses':['192.0.2.10'],'interfaces':['wg1']})
payload = {'public_ip':'192.0.2.10','public_port':25565,'target_ip':'10.0.1.2','target_port':25565,'protocol':'both',
'restrict_sources': True, 'allowed_sources':['89.144.32.110','89.144.32.172']}
row = m['extended_forward_add']('wg1', payload)['forward']
config = configs['wg1']
assert '--ctorigdst 192.0.2.10 --ctorigdstport 25565' in config
assert '-s 89.144.32.110' in config and '-s 89.144.32.172' in config
post_up = next(line for line in config.splitlines() if line.startswith('PostUp ='))
assert post_up.index('-tcp-deny -j DROP') < post_up.index('-tcp-in0 -j ACCEPT')
assert post_up.index('-udp-deny -j DROP') < post_up.index('-udp-in0 -j ACCEPT')
updated = m['extended_forward_add']('wg1', {**payload, 'restrict_sources':False, 'allowed_sources':[]}, update_id=row['id'])['forward']
assert updated['id'] == row['id']
assert len(m['extended_forward_get']('wg1')['forwards']) == 1
assert '-tcp-deny -j DROP' not in configs['wg1']
def test_forward_rejects_invalid_and_empty_source_lists(network):
m, _ = network
m['extended_ip_groups_set']({'name':'shared','addresses':['192.0.2.10'],'interfaces':['wg1']})
payload = {'public_ip':'192.0.2.10','public_port':1234,'target_ip':'10.0.1.2','target_port':1234,'protocol':'tcp','restrict_sources': True}
for sources in ([], ['192.0.2.1/24'], ['1.2.3.4;id']):
with pytest.raises(ValueError):
m['extended_forward_add']('wg1', {**payload, 'allowed_sources': sources})
def test_wireguard_dump_accepts_disabled_keepalive(network, monkeypatch):
m, _ = network
gl = m['wg_dump'].__globals__
+1 -1
View File
@@ -36,7 +36,7 @@ class HelpTranslationTests(unittest.TestCase):
def test_unknown_language_defaults_to_english(self):
self.assertEqual(get_help_sections('non-existent-language'), HELP['en'])
def test_version(self):
self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.2')
self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.5')
if __name__ == '__main__':
unittest.main()
+28
View File
@@ -0,0 +1,28 @@
from app.core import audit, preferences
def test_settings_are_loaded_in_batches(tmp_path, monkeypatch):
monkeypatch.setattr(preferences, 'DATABASE_PATH', str(tmp_path / 'settings.db'))
original = preferences._connect
connections = []
def connect():
connections.append(1)
return original()
monkeypatch.setattr(preferences, '_connect', connect)
assert preferences.get_preferences()['refresh_seconds'] == max(2, min(preferences.REFRESH_SECONDS, 60))
assert len(connections) == 2
connections.clear()
assert preferences.get_branding()['name'] == 'WGTools-Extended'
assert len(connections) == 2
def test_historical_connection_lookup_uses_index(tmp_path, monkeypatch):
monkeypatch.setattr(audit, 'DATABASE_PATH', str(tmp_path / 'audit.db'))
audit.init_audit_database()
with audit._connection() as conn:
plan = conn.execute(
"EXPLAIN QUERY PLAN SELECT created_at,details FROM audit_log "
"WHERE action='wireguard.client_connected' AND object=? "
"ORDER BY created_at DESC,id DESC LIMIT 1", ('wg0 · klient',)
).fetchall()
assert any('idx_audit_connection_lookup' in str(row[3]) for row in plan)
+1 -1
View File
@@ -15,7 +15,7 @@ LANGS = ('en', 'ru', 'de', 'fr', 'it', 'es', 'pl')
class CandidateTests(unittest.TestCase):
def test_versions_and_locale_fallback_contract(self):
self.assertEqual((ROOT / 'VERSION').read_text().strip(), '1.0.2')
self.assertEqual((ROOT / 'VERSION').read_text().strip(), '1.0.5')
en = json.loads((ROOT/'app/locales/en.json').read_text())
self.assertGreaterEqual(len(en), 1098)
for lang in LANGS:
+25
View File
@@ -0,0 +1,25 @@
import pytest
from app.core import preferences
from app import main
def test_service_policy_and_validation(tmp_path, monkeypatch):
monkeypatch.setattr(preferences, 'DATABASE_PATH', str(tmp_path / 'settings.db'))
monkeypatch.setattr(main, 'audit_username', lambda request: 'jan')
assert not preferences.get_service_policy()['enabled']
with pytest.raises(ValueError):
preferences.update_service_policy(True, 'list', [])
preferences.update_service_policy(True, 'list', ['WireGuard', 'WireGuard'])
request = main.ExtendedForwardRequest(public_ip='192.0.2.1', public_port=80, target_ip='10.0.0.2', target_port=80, protocol='tcp', service='WireGuard')
with pytest.raises(ValueError):
main.forward_payload(request, None)
request.confirmation = main.SERVICE_CONFIRMATION
result = main.forward_payload(request, None)
assert result['responsibility']['user'] == 'jan'
request.service = 'inny'
with pytest.raises(ValueError):
main.forward_payload(request, None)
preferences.update_service_policy(True, 'combo', ['WireGuard'])
assert main.forward_payload(request, None)['service'] == 'inny'
preferences.update_service_policy(True, 'custom', [])
assert main.forward_payload(request, None)['service'] == 'inny'