AP manageur V1.1 (Bêta)

This commit is contained in:
yoannmultigaming committed 2026-11-25 01:10:15 +01:00
1 parent 7114691e0a
commit a9630cc035
5 files changed
+143 -46

No files matched your search

+99 -40
View File
@@ -741,8 +741,11 @@ def init_db():
c.commit()
recovery_table(c)
c.execute('CREATE TABLE IF NOT EXISTS connection_logs(id INTEGER PRIMARY KEY,event_time TEXT,event TEXT,name TEXT,ip TEXT,mac TEXT)')
c.execute('CREATE INDEX IF NOT EXISTS idx_connection_logs_mac ON connection_logs(mac)')
c.execute('CREATE INDEX IF NOT EXISTS idx_connection_logs_time ON connection_logs(event_time)')
c.execute('CREATE TABLE IF NOT EXISTS blocked_clients(mac TEXT PRIMARY KEY,blocked_at TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS client_names(mac TEXT PRIMARY KEY,name TEXT NOT NULL,last_ip TEXT,last_seen TEXT,device_type TEXT DEFAULT "",is_custom INTEGER DEFAULT 0)')
c.execute('CREATE INDEX IF NOT EXISTS idx_client_names_last_seen ON client_names(last_seen)')
cn_cols = {row[1] for row in c.execute('PRAGMA table_info(client_names)').fetchall()}
if 'device_type' not in cn_cols:
try:
@@ -2409,6 +2412,14 @@ def connection_name():
except OSError: pass
pref_con = get_pref('ap_connection_name', '')
if pref_con: return pref_con
try:
lines = command('nmcli', '-t', '-g', 'NAME,TYPE', 'connection', 'show').splitlines()
for line in lines:
if ':802-11-wireless' in line or ':wifi' in line:
cname = line.split(':')[0].strip()
if cname:
return cname
except Exception: pass
pref_ssid = get_pref('ap_ssid', '')
if pref_ssid: return 'AP-' + pref_ssid
return os.environ.get('AP_CONNECTION', '')
@@ -3995,27 +4006,36 @@ def stop_hostapd(iface=None):
if iface:
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True)
def ensure_nm_manages_wifi(iface=None):
def ensure_nm_manages_wifi(iface=None, force=False):
"""Rend le contrôle de l'interface Wi-Fi à NetworkManager (pour le mode AP/NAT) et attend qu'elle soit prête."""
iface = iface or INTERFACE
if not iface:
return
# Si le périphérique est déjà sous le contrôle de NetworkManager (pas de hostapd actif, non asservi à un pont et état >= 30)
# il est contre-productif de faire un reset physique (down/up) qui déconnecterait l'interface.
is_master = os.path.exists(f'/sys/class/net/{iface}/master')
hostapd_act = is_hostapd_running()
current_st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface, timeout=2)
if not force and not is_master and not hostapd_act:
if current_st and not current_st.startswith('10') and not current_st.startswith('20'):
return
stop_hostapd(iface)
# S'assurer que wpa_supplicant est actif (indispensable pour que NM puisse initialiser la radio Wi-Fi)
ensure_wpa_supplicant_running()
subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True)
subprocess.run(['ip', 'addr', 'flush', 'dev', iface], capture_output=True)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True)
subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True)
subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True)
subprocess.run(['nmcli', 'radio', 'wifi', 'on'], capture_output=True)
for _ in range(25):
st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface)
subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True, timeout=3)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True, timeout=3)
subprocess.run(['ip', 'addr', 'flush', 'dev', iface], capture_output=True, timeout=3)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'down'], capture_output=True, timeout=3)
subprocess.run(['iw', 'dev', iface, 'set', 'type', 'managed'], capture_output=True, timeout=3)
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True, timeout=3)
subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True, timeout=5)
subprocess.run(['nmcli', 'radio', 'wifi', 'on'], capture_output=True, timeout=5)
for _ in range(35):
st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface, timeout=2)
if st and not st.startswith('10') and not st.startswith('20'): # 10=unmanaged, 20=unavailable
break
time.sleep(0.15)
time.sleep(0.2)
def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=None):
"""Démarre le point d'accès Wi-Fi en mode pont directement via hostapd (bridge=br0) sans que NetworkManager ne touche au pont hôte."""
@@ -4846,36 +4866,47 @@ def status(force_refresh=False):
db_pass = get_pref('ap_password', '') or ''
db_sec = (get_pref('ap_security', '') or '').lower()
db_auto = get_pref('ap_autoconnect', None)
nm_ssid = command('nmcli','-t','-g','802-11-wireless.ssid','connection','show',name) if name else ''
nm_pass = command('nmcli','--show-secrets','-t','-g','802-11-wireless-security.psk','connection','show',name) if name else ''
key = command('nmcli','-t','-g','802-11-wireless-security.key-mgmt','connection','show',name).lower() if name else ''
proto = command('nmcli','-t','-g','802-11-wireless-security.proto','connection','show',name).lower() if name else ''
# Optimisation haute performance : si la configuration existe en BDD, éviter 4 à 5 appels nmcli bloquants
if db_ssid and db_pass:
ssid = db_ssid
password = db_pass
sec = db_sec if db_sec in ('wpa1', 'wpa2', 'wpa3') else 'wpa2'
auto = (str(db_auto).lower() in ('1', 'true', 'yes', 'oui')) if db_auto is not None else True
else:
nm_ssid = command('nmcli','-t','-g','802-11-wireless.ssid','connection','show',name, timeout=2) if name else ''
nm_pass = command('nmcli','--show-secrets','-t','-g','802-11-wireless-security.psk','connection','show',name, timeout=2) if name else ''
key = command('nmcli','-t','-g','802-11-wireless-security.key-mgmt','connection','show',name, timeout=2).lower() if name else ''
proto = command('nmcli','-t','-g','802-11-wireless-security.proto','connection','show',name, timeout=2).lower() if name else ''
ssid = nm_ssid or db_ssid
password = nm_pass or db_pass
if key:
sec = 'wpa3' if key == 'sae' else 'wpa1' if proto == 'wpa' else 'wpa2'
else:
sec = db_sec if db_sec in ('wpa1', 'wpa2', 'wpa3') else 'wpa2'
mode = current_mode()
state = command('nmcli','-t','-g','GENERAL.STATE','device','show',INTERFACE)
# CORRECTION : "30 (disconnected)" contient "connected" ; seul le code 100 signifie connecté.
if mode == 'bridge':
active = is_hostapd_running() or (is_iface_up(INTERFACE) and os.path.exists(f'/sys/class/net/{INTERFACE}/master'))
else:
active = state.startswith('100')
nm_auto = command('nmcli','-t','-g','connection.autoconnect','connection','show',name).lower() if name else ''
if nm_auto in ('yes', 'no') and mode != 'bridge':
nm_auto = command('nmcli','-t','-g','connection.autoconnect','connection','show',name, timeout=2).lower() if name else ''
if nm_auto in ('yes', 'no'):
auto = (nm_auto == 'yes')
elif db_auto is not None:
auto = str(db_auto).lower() in ('1', 'true', 'yes', 'oui')
else:
auto = False
mode = current_mode()
state = command('nmcli','-t','-g','GENERAL.STATE','device','show',INTERFACE, timeout=2)
# CORRECTION : "30 (disconnected)" contient "connected" ; seul le code 100 signifie connecté.
if mode == 'bridge':
active = is_hostapd_running() or (is_iface_up(INTERFACE) and os.path.exists(f'/sys/class/net/{INTERFACE}/master'))
else:
active = state.startswith('100')
if active and uptime_start() is None:
mark_ap_started()
master = (command('nmcli','-t','-g','connection.master','connection','show',name) or command('nmcli','-t','-g','connection.controller','connection','show',name)) if name else ''
if not master and os.path.exists(f'/sys/class/net/{INTERFACE}/master'):
master = ''
if os.path.exists(f'/sys/class/net/{INTERFACE}/master'):
try: master = os.path.basename(os.readlink(f'/sys/class/net/{INTERFACE}/master'))
except OSError: pass
elif name and mode == 'bridge':
master = command('nmcli','-t','-g','connection.master','connection','show',name, timeout=2)
b_name = master or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
eff_chan = get_effective_ap_channel(AP_BAND)
@@ -6714,7 +6745,7 @@ def restore_ap_from_db(force_start=False):
state = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', INTERFACE)
if not state.startswith('100'):
print(f"[ap-api] Démarrage automatique du Wi-Fi '{db_ssid}' (mode=ap)...", flush=True)
r = subprocess.run(['nmcli', 'connection', 'up', target_name], capture_output=True, text=True)
r = subprocess.run(['nmcli', '--wait', '15', 'connection', 'up', target_name], capture_output=True, text=True, timeout=20)
if r.returncode != 0:
print(f"[ap-api] Erreur démarrage automatique '{target_name}' : {r.stderr.strip()}", flush=True)
return False
@@ -11674,7 +11705,16 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({'ok': True, 'version': APP_VERSION, 'commit': get_current_commit()})
return
if self.path in ('/','/index.html','/ap_dashboard.html'):
try: body=open(os.path.join(os.path.dirname(__file__),'index.html'),'rb').read(); self.send_response(200); self.send_header('Content-Type','text/html; charset=utf-8'); self.send_header('Content-Length',str(len(body))); self.end_headers(); self.wfile.write(body)
try:
body=open(os.path.join(os.path.dirname(__file__),'index.html'),'rb').read()
self.send_response(200)
self.send_header('Content-Type','text/html; charset=utf-8')
self.send_header('Content-Length',str(len(body)))
self.send_header('X-Content-Type-Options','nosniff')
self.send_header('X-Frame-Options','SAMEORIGIN')
self.send_header('Referrer-Policy','strict-origin-when-cross-origin')
self.end_headers()
self.wfile.write(body)
except OSError: self.send_error(404,'index.html introuvable')
return
if self.path in ('/setup', '/setup.html', '/Setup.html', '/Setup.HTML'):
@@ -11683,6 +11723,9 @@ class Handler(BaseHTTPRequestHandler):
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.send_header('X-Content-Type-Options','nosniff')
self.send_header('X-Frame-Options','SAMEORIGIN')
self.send_header('Referrer-Policy','strict-origin-when-cross-origin')
self.end_headers()
self.wfile.write(body)
except OSError:
@@ -11697,6 +11740,8 @@ class Handler(BaseHTTPRequestHandler):
self.send_response(200)
self.send_header('Content-Type', 'application/javascript; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.send_header('Cache-Control', 'public, max-age=3600')
self.send_header('X-Content-Type-Options', 'nosniff')
self.end_headers()
self.wfile.write(body)
return
@@ -11712,6 +11757,8 @@ class Handler(BaseHTTPRequestHandler):
self.send_response(200)
self.send_header('Content-Type', 'text/css; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.send_header('Cache-Control', 'public, max-age=3600')
self.send_header('X-Content-Type-Options', 'nosniff')
self.end_headers()
self.wfile.write(body)
return
@@ -11746,9 +11793,17 @@ class Handler(BaseHTTPRequestHandler):
self.send_error(404, 'Jeu introuvable')
return
if self.path == '/favicon.png' or self.path.startswith('/images/'):
clean_name = 'favicon.png' if self.path == '/favicon.png' else os.path.basename(urllib.parse.urlparse(self.path).path)
img_path = os.path.join(os.path.dirname(__file__), 'images', clean_name)
ext = os.path.splitext(clean_name)[1].lower()
if self.path == '/favicon.png':
img_path = os.path.join(os.path.dirname(__file__), 'images', 'favicon.png')
else:
rel_sub = urllib.parse.unquote(urllib.parse.urlparse(self.path).path).lstrip('/')
base_dir = os.path.abspath(os.path.dirname(__file__))
img_path = os.path.abspath(os.path.join(base_dir, rel_sub))
images_base = os.path.abspath(os.path.join(base_dir, 'images'))
if not (img_path == images_base or img_path.startswith(images_base + os.sep)):
self.send_error(403, 'Accès interdit')
return
ext = os.path.splitext(img_path)[1].lower()
mime_map = {'.png': 'image/png', '.svg': 'image/svg+xml', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.ico': 'image/x-icon'}
if os.path.isfile(img_path) and ext in mime_map:
try:
@@ -11756,9 +11811,8 @@ class Handler(BaseHTTPRequestHandler):
self.send_response(200)
self.send_header('Content-Type', mime_map[ext])
self.send_header('Content-Length', str(len(body)))
self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
self.send_header('Pragma', 'no-cache')
self.send_header('Expires', '0')
self.send_header('Cache-Control', 'public, max-age=86400')
self.send_header('X-Content-Type-Options', 'nosniff')
self.end_headers()
self.wfile.write(body)
return
@@ -12977,6 +13031,7 @@ class Handler(BaseHTTPRequestHandler):
raise RuntimeError('Paramètres Wi-Fi manquants en BDD : veuillez ré-enregistrer les réglages Wi-Fi')
if action == 'restart':
stop_hostapd(INTERFACE)
time.sleep(0.3)
setup_bridge(b_name, b_eth)
start_bridge_hostapd(db_ssid, db_pass, sec=db_sec, bridge_name=b_name, iface=INTERFACE)
mark_ap_started()
@@ -12988,21 +13043,25 @@ class Handler(BaseHTTPRequestHandler):
else:
if action in ('start', 'restart'):
ensure_nm_manages_wifi(INTERFACE)
nm_exists = bool(name) and (subprocess.run(['nmcli', 'connection', 'show', name], capture_output=True, text=True).returncode == 0)
nm_exists = bool(name) and (subprocess.run(['nmcli', 'connection', 'show', name], capture_output=True, text=True, timeout=5).returncode == 0)
if not nm_exists and get_pref('ap_ssid', ''):
if not restore_ap_from_db(force_start=True):
raise RuntimeError('Impossible de restaurer et démarrer la connexion Wi-Fi depuis la BDD')
else:
if action == 'restart':
subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True)
r = subprocess.run(['nmcli', 'connection', 'up', name], capture_output=True, text=True)
if r.returncode: raise RuntimeError(r.stderr.strip())
subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True, timeout=10)
time.sleep(0.5)
r = subprocess.run(['nmcli', '--wait', '15', 'connection', 'up', name], capture_output=True, text=True, timeout=20)
if r.returncode:
print(f"[ap-control] Échec activation '{name}' ({r.stderr.strip()}), tentative de restauration BDD...", flush=True)
if not restore_ap_from_db(force_start=True):
raise RuntimeError(r.stderr.strip() or "Échec de l'activation du point d'accès Wi-Fi")
disable_wifi_powersave(INTERFACE)
setup_ap_nat(INTERFACE)
mark_ap_started()
elif action == 'stop':
if name:
r = subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True)
r = subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True, timeout=10)
if r.returncode and 'not an active connection' not in r.stderr.lower():
raise RuntimeError(r.stderr.strip())
teardown_ap_nat()
+32 -3
View File
@@ -9676,11 +9676,29 @@ ${vpnBadgeTopo}
async function controlAp(action) {
return runAction(async () => {
const apBtn = $('apControl');
const rstBtn = $('apRestart');
const origApText = apBtn ? apBtn.textContent : '';
const origRstText = rstBtn ? rstBtn.textContent : '';
if (action === 'start' && apBtn) {
apBtn.innerHTML = `<span style="display:inline-flex;animation:spin 1s linear infinite">⚙️</span> <span>${escapeHtml(t('btn_starting', 'Démarrage…'))}</span>`;
} else if (action === 'stop' && apBtn) {
apBtn.innerHTML = `<span style="display:inline-flex;animation:spin 1s linear infinite">⚙️</span> <span>${escapeHtml(t('btn_stopping', 'Arrêt…'))}</span>`;
} else if (action === 'restart' && rstBtn) {
rstBtn.innerHTML = `<span style="display:inline-flex;animation:spin 1s linear infinite">⚙️</span> <span>${escapeHtml(t('btn_restarting', 'Redémarrage…'))}</span>`;
}
try {
const response = await apiFetch('/api/ap/control', { method: 'POST', timeout: 45000, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) });
const response = await apiFetch('/api/ap/control', { method: 'POST', timeout: 35000, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }) });
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Action refusée');
await new Promise(resolve => setTimeout(resolve, 1000)); await load();
} catch (e) { alert(tErr(e.message)) }
await new Promise(resolve => setTimeout(resolve, 800));
await load();
} catch (e) {
alert(tErr(e.message));
} finally {
if (apBtn && origApText) apBtn.textContent = origApText;
if (rstBtn && origRstText) rstBtn.textContent = origRstText;
updateApButtons();
}
});
}
@@ -15910,6 +15928,7 @@ ${vpnBadgeTopo}
})();
setInterval(() => {
if (document.hidden) return;
if (authToken && currentTab !== 'settings') {
load();
if (currentTab === 'stats') { if (currentStatsSubTab === 'topology') loadTopology(); else loadStats(); }
@@ -15918,11 +15937,21 @@ ${vpnBadgeTopo}
/* Actualisation automatique des journaux toutes les minutes */
setInterval(() => {
if (document.hidden) return;
if (authToken) {
loadLogs();
}
}, 60000);
document.addEventListener('visibilitychange', () => {
if (!document.hidden && authToken) {
if (currentTab !== 'settings') {
load();
if (currentTab === 'stats') { if (currentStatsSubTab === 'topology') loadTopology(); else loadStats(); }
}
}
});
// =====================================================================
// GESTION DES PROFILS VPN & ROUTAGE CLIENTS (WireGuard & OpenVPN)
// =====================================================================
+4 -1
View File
@@ -1454,5 +1454,8 @@ window.I18N['en-gb'] = {
"setup_step5_prefs_title": "Finalizing preferences, updates & backups…",
"setup_step5_prefs_desc": "Saving theme, application title, update interval and backup schedule…",
"setup_launch_success_title": "✅ AP Manageur configured successfully!",
"setup_launch_redirecting": "Redirecting to dashboard…"
"setup_launch_redirecting": "Redirecting to dashboard…",
"btn_starting": "Starting…",
"btn_stopping": "Stopping…",
"btn_restarting": "Restarting…"
};
+4 -1
View File
@@ -1454,5 +1454,8 @@ window.I18N['en-us'] = {
"setup_step5_prefs_title": "Finalizing preferences, updates & backups…",
"setup_step5_prefs_desc": "Saving theme, application title, update interval and backup schedule…",
"setup_launch_success_title": "✅ AP Manageur configured successfully!",
"setup_launch_redirecting": "Redirecting to dashboard…"
"setup_launch_redirecting": "Redirecting to dashboard…",
"btn_starting": "Starting…",
"btn_stopping": "Stopping…",
"btn_restarting": "Restarting…"
};
+4 -1
View File
@@ -1454,5 +1454,8 @@ window.I18N['fr'] = {
"setup_step5_prefs_title": "Finalisation des préférences, mises à jour & sauvegardes…",
"setup_step5_prefs_desc": "Enregistrement du thème, du titre, de la mise à jour auto et des sauvegardes…",
"setup_launch_success_title": "✅ Configuration réussie !",
"setup_launch_redirecting": "Redirection vers le tableau de bord…"
"setup_launch_redirecting": "Redirection vers le tableau de bord…",
"btn_starting": "Démarrage…",
"btn_stopping": "Arrêt…",
"btn_restarting": "Redémarrage…"
};