Archived
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3841e93e32 |
No files matched your search
@@ -1,5 +1,10 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 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
|
## v1.0.2
|
||||||
|
|
||||||
- Poprawiono wybór marki i przypisywanie uprawnień do sieci.
|
- Poprawiono wybór marki i przypisywanie uprawnień do sieci.
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
Fixes bugs and improves network configuration, user permissions and branding.
|
Improves panel performance and reduces unnecessary background refreshes.
|
||||||
@@ -98,6 +98,7 @@ def init_audit_database() -> None:
|
|||||||
details TEXT NOT NULL DEFAULT ''
|
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_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 (
|
CREATE TABLE IF NOT EXISTS audit_wg_connection_state (
|
||||||
interface TEXT NOT NULL,
|
interface TEXT NOT NULL,
|
||||||
public_key TEXT NOT NULL,
|
public_key TEXT NOT NULL,
|
||||||
|
|||||||
+3
-2
@@ -76,8 +76,9 @@ def init_database() -> None:
|
|||||||
conn.execute("ALTER TABLE user_access ADD COLUMN permissions TEXT NOT NULL DEFAULT '{}'")
|
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]:
|
||||||
init_database()
|
if initialize:
|
||||||
|
init_database()
|
||||||
with _connect() as conn:
|
with _connect() as conn:
|
||||||
row = conn.execute("SELECT role,interfaces,permissions FROM user_access WHERE user_id=?", (int(user_id),)).fetchone()
|
row = conn.execute("SELECT role,interfaces,permissions FROM user_access WHERE user_id=?", (int(user_id),)).fetchone()
|
||||||
if row is None:
|
if row is None:
|
||||||
|
|||||||
+14
-6
@@ -13,9 +13,8 @@ DEFAULT_BACKUP_RETENTION = 20
|
|||||||
|
|
||||||
|
|
||||||
def get_branding() -> dict[str, Any]:
|
def get_branding() -> dict[str, Any]:
|
||||||
return {"name": _get("brand_name", "WGTools-Extended"),
|
values = _get_many({"brand_name": "WGTools-Extended", "brand_color": "#8f1f27", "brand_logo": ""})
|
||||||
"color": _get("brand_color", "#8f1f27"),
|
return {"name": values["brand_name"], "color": values["brand_color"], "logo": values["brand_logo"]}
|
||||||
"logo": _get("brand_logo", "")}
|
|
||||||
|
|
||||||
|
|
||||||
def update_branding(name: str, color: str, logo: str) -> dict[str, Any]:
|
def update_branding(name: str, color: str, logo: str) -> dict[str, Any]:
|
||||||
@@ -68,6 +67,14 @@ def _get(key: str, default: str) -> str:
|
|||||||
return str(row["value"]) if row else default
|
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:
|
def _set(key: str, value: str) -> None:
|
||||||
init_preferences()
|
init_preferences()
|
||||||
with _connect() as conn:
|
with _connect() as conn:
|
||||||
@@ -81,9 +88,10 @@ def _set(key: str, value: str) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def get_preferences() -> dict[str, Any]:
|
def get_preferences() -> dict[str, Any]:
|
||||||
refresh = int(_get("refresh_seconds", str(REFRESH_SECONDS)))
|
values = _get_many({"refresh_seconds": str(REFRESH_SECONDS), "online_threshold_seconds": str(ONLINE_THRESHOLD_SECONDS), "backup_retention": str(DEFAULT_BACKUP_RETENTION)})
|
||||||
threshold = int(_get("online_threshold_seconds", str(ONLINE_THRESHOLD_SECONDS)))
|
refresh = int(values["refresh_seconds"])
|
||||||
retention = int(_get("backup_retention", str(DEFAULT_BACKUP_RETENTION)))
|
threshold = int(values["online_threshold_seconds"])
|
||||||
|
retention = int(values["backup_retention"])
|
||||||
return {
|
return {
|
||||||
"refresh_seconds": max(2, min(refresh, 60)),
|
"refresh_seconds": max(2, min(refresh, 60)),
|
||||||
"online_threshold_seconds": max(30, min(threshold, 3600)),
|
"online_threshold_seconds": max(30, min(threshold, 3600)),
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ APP_NAME = "WGTools-Extended"
|
|||||||
VERSION = Path(__file__).resolve().parents[2].joinpath("VERSION").read_text().strip()
|
VERSION = Path(__file__).resolve().parents[2].joinpath("VERSION").read_text().strip()
|
||||||
WG_INTERFACE = os.getenv("WGTOOLS_INTERFACE", "wg0")
|
WG_INTERFACE = os.getenv("WGTOOLS_INTERFACE", "wg0")
|
||||||
HELPER_PATH = os.getenv("WGTOOLS_HELPER", "/usr/local/libexec/wgtools-helper")
|
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"))
|
ONLINE_THRESHOLD_SECONDS = int(os.getenv("WGTOOLS_ONLINE_THRESHOLD_SECONDS", "180"))
|
||||||
DATABASE_PATH = os.getenv("WGTOOLS_DATABASE", "/var/lib/wgtools/wgtools.db")
|
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")
|
SESSION_KEY_FILE = os.getenv("WGTOOLS_SESSION_KEY_FILE", "/var/lib/wgtools/session.key")
|
||||||
|
|||||||
+5
-5
@@ -436,7 +436,7 @@ class NodeSettingsRequest(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class AppSettingsRequest(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)
|
online_threshold_seconds: int = Field(default=180, ge=30, le=3600)
|
||||||
backup_retention: int = Field(default=20, ge=1, le=200)
|
backup_retention: int = Field(default=20, ge=1, le=200)
|
||||||
|
|
||||||
@@ -522,7 +522,7 @@ def is_internal_interface(name: str) -> bool:
|
|||||||
|
|
||||||
def request_interface(request: Request) -> str:
|
def request_interface(request: Request) -> str:
|
||||||
current = getattr(request.state, "current_user", None)
|
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)
|
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()
|
value = (request.cookies.get("wgtools_interface") or default_iface).strip()
|
||||||
if access["role"] == "user" and access["interfaces"] and value not in access["interfaces"]:
|
if access["role"] == "user" and access["interfaces"] and value not in access["interfaces"]:
|
||||||
@@ -580,7 +580,7 @@ def render(request: Request, template: str, page: str, title_key: str) -> HTMLRe
|
|||||||
"language": language,
|
"language": language,
|
||||||
"messages_json": messages_json,
|
"messages_json": messages_json,
|
||||||
"tr": tr,
|
"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 [],
|
"help_sections": get_help_sections(language) if request.state.access['role'] == 'admin' else [],
|
||||||
},
|
},
|
||||||
headers={"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet"},
|
headers={"X-Robots-Tag": "noindex, nofollow, noarchive, nosnippet"},
|
||||||
@@ -649,9 +649,9 @@ async def require_authentication(request: Request, call_next):
|
|||||||
if path in PUBLIC_PATHS or path.startswith(PUBLIC_PREFIXES):
|
if path in PUBLIC_PATHS or path.startswith(PUBLIC_PREFIXES):
|
||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
users_exist = user_count() > 0
|
|
||||||
user_id = request.session.get("user_id")
|
user_id = request.session.get("user_id")
|
||||||
current = get_user(int(user_id)) if user_id else None
|
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:
|
if user_id and not current:
|
||||||
request.session.clear()
|
request.session.clear()
|
||||||
if current:
|
if current:
|
||||||
@@ -682,7 +682,7 @@ async def require_authentication(request: Request, call_next):
|
|||||||
return RedirectResponse(url=f"{app_url(request, '/login')}?next={next_path}", status_code=303)
|
return RedirectResponse(url=f"{app_url(request, '/login')}?next={next_path}", status_code=303)
|
||||||
|
|
||||||
request.state.current_user = current
|
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
|
request.state.access = access
|
||||||
if access["role"] != "admin":
|
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/delete"}
|
||||||
|
|||||||
+11
-5
@@ -11,7 +11,7 @@
|
|||||||
return nativeFetch(input, init);
|
return nativeFetch(input, init);
|
||||||
};
|
};
|
||||||
const page = document.body.dataset.page;
|
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');
|
const threshold = Number(document.body.dataset.onlineThreshold || '180');
|
||||||
let snapshot = null;
|
let snapshot = null;
|
||||||
let interfacesData = {interfaces:[], suggested:null};
|
let interfacesData = {interfaces:[], suggested:null};
|
||||||
@@ -2095,6 +2095,7 @@
|
|||||||
auditAutoRefreshTimer=setInterval(()=>{
|
auditAutoRefreshTimer=setInterval(()=>{
|
||||||
const modal=$('audit-modal');
|
const modal=$('audit-modal');
|
||||||
if(!modal||modal.hidden){stopAuditAutoRefresh();return;}
|
if(!modal||modal.hidden){stopAuditAutoRefresh();return;}
|
||||||
|
if(document.hidden)return;
|
||||||
loadAudit({showLoading:false});
|
loadAudit({showLoading:false});
|
||||||
},interval);
|
},interval);
|
||||||
}
|
}
|
||||||
@@ -2993,14 +2994,19 @@
|
|||||||
if(page==='dashboard'){
|
if(page==='dashboard'){
|
||||||
loadMetricsHistory();
|
loadMetricsHistory();
|
||||||
if(document.body.dataset.role==='admin')loadDashboardDiagnostics();
|
if(document.body.dataset.role==='admin')loadDashboardDiagnostics();
|
||||||
historyTimer=setInterval(loadMetricsHistory,60*1000);
|
historyTimer=setInterval(()=>{if(!document.hidden)loadMetricsHistory();},60*1000);
|
||||||
if(document.body.dataset.role==='admin')dashboardDiagnosticsTimer=setInterval(loadDashboardDiagnostics,60*1000);
|
if(document.body.dataset.role==='admin')dashboardDiagnosticsTimer=setInterval(()=>{if(!document.hidden)loadDashboardDiagnostics();},60*1000);
|
||||||
}
|
}
|
||||||
if(page==='server'){
|
if(page==='server'){
|
||||||
loadServerDiagnostics();
|
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();
|
boot();
|
||||||
})();
|
})();
|
||||||
+1
-1
@@ -78,7 +78,7 @@ if [[ ! -f /etc/wgtools/wgtools.env ]]; then
|
|||||||
WGTOOLS_INTERFACE=$WG_INTERFACE
|
WGTOOLS_INTERFACE=$WG_INTERFACE
|
||||||
WGTOOLS_PORT=$WEB_PORT
|
WGTOOLS_PORT=$WEB_PORT
|
||||||
WGTOOLS_HELPER=/usr/local/libexec/wgtools-helper
|
WGTOOLS_HELPER=/usr/local/libexec/wgtools-helper
|
||||||
WGTOOLS_REFRESH_SECONDS=5
|
WGTOOLS_REFRESH_SECONDS=10
|
||||||
WGTOOLS_ONLINE_THRESHOLD_SECONDS=180
|
WGTOOLS_ONLINE_THRESHOLD_SECONDS=180
|
||||||
WGTOOLS_DATABASE=/var/lib/wgtools/wgtools.db
|
WGTOOLS_DATABASE=/var/lib/wgtools/wgtools.db
|
||||||
WGTOOLS_SESSION_KEY_FILE=/var/lib/wgtools/session.key
|
WGTOOLS_SESSION_KEY_FILE=/var/lib/wgtools/session.key
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ class HelpTranslationTests(unittest.TestCase):
|
|||||||
def test_unknown_language_defaults_to_english(self):
|
def test_unknown_language_defaults_to_english(self):
|
||||||
self.assertEqual(get_help_sections('non-existent-language'), HELP['en'])
|
self.assertEqual(get_help_sections('non-existent-language'), HELP['en'])
|
||||||
def test_version(self):
|
def test_version(self):
|
||||||
self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.2')
|
self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.3')
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -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)
|
||||||
@@ -15,7 +15,7 @@ LANGS = ('en', 'ru', 'de', 'fr', 'it', 'es', 'pl')
|
|||||||
|
|
||||||
class CandidateTests(unittest.TestCase):
|
class CandidateTests(unittest.TestCase):
|
||||||
def test_versions_and_locale_fallback_contract(self):
|
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.3')
|
||||||
en = json.loads((ROOT/'app/locales/en.json').read_text())
|
en = json.loads((ROOT/'app/locales/en.json').read_text())
|
||||||
self.assertGreaterEqual(len(en), 1098)
|
self.assertGreaterEqual(len(en), 1098)
|
||||||
for lang in LANGS:
|
for lang in LANGS:
|
||||||
|
|||||||
Reference in new issue
Block a user