APmanageur Wi-Fi V1.0

This commit is contained in:
yoannmultigaming committed 2026-11-22 22:30:34 +01:00
1 parent ffb20ad344
commit 2effae81b2
7 files changed
+887 -217

No files matched your search

+375 -207
View File
@@ -2376,7 +2376,7 @@
Administration de l’AP Wi‑Fi</h2>
<div class="sub" style="margin-top:4px"><span class="app-short-title">AP Manageur</span> <span
class="app-version"
style="font-weight:700;background:var(--panel2);padding:2px 8px;border-radius:6px;border:1px solid var(--line);color:var(--blue);font-size:11px;margin-left:4px">V5.5</span>
style="font-weight:700;background:var(--panel2);padding:2px 8px;border-radius:6px;border:1px solid var(--line);color:var(--blue);font-size:11px;margin-left:4px">V1.1 (Béta)</span>
</div>
<div id="loaderBadge"
style="display:inline-flex;align-items:center;gap:6px;background:rgba(56,189,248,0.12);border:1px solid rgba(56,189,248,0.3);color:var(--blue);padding:3px 12px;border-radius:20px;font-size:12px;font-weight:600;margin-top:8px">
@@ -2571,7 +2571,7 @@
<div>
<h1><span class="app-title" data-i18n="app_main_heading">Administration de l’AP Wi‑Fi</span></h1>
<div class="sub"><span class="app-short-title">AP Manageur</span> <span class="app-version"
style="font-weight:700;background:var(--panel2);padding:2px 8px;border-radius:6px;border:1px solid var(--line);color:var(--blue);font-size:12px;margin-left:4px">V5.5</span>
style="font-weight:700;background:var(--panel2);padding:2px 8px;border-radius:6px;border:1px solid var(--line);color:var(--blue);font-size:12px;margin-left:4px">V1.1 (Béta)</span>
</div>
</div>
<div class="header-actions">
@@ -3547,6 +3547,43 @@
</div>
<span id="sessionsMessage" class="muted" style="margin-top:10px;display:block"></span>
</div>
<div id="apiKeysBox" style="margin-top:24px;padding-top:20px;border-top:1px solid var(--line)">
<div class="topline" style="flex-wrap:wrap;gap:12px;margin-bottom:12px">
<div>
<h2 style="margin:0 0 4px" data-i18n="settings_apikeys_title">⚡ Clés d’API &amp; Accès programmatique</h2>
<p class="muted" style="margin:0;font-size:13px" data-i18n="settings_apikeys_desc">Générez des clés d’accès pour intégrer AP Manageur avec Home Assistant, des scripts automatisés ou des applications tierces avec des autorisations granulaires.</p>
</div>
<button id="btnCreateApiKey" type="button" onclick="openCreateApiKeyModal()"
style="display:inline-flex;align-items:center;gap:6px;font-size:13px"
data-i18n="settings_apikeys_create_btn">
➕ Créer une nouvelle clé d’API
</button>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th data-i18n="th_apikey_name">NOM DE LA CLÉ</th>
<th data-i18n="th_apikey_prefix">CLÉ</th>
<th data-i18n="th_apikey_perms">AUTORISATIONS</th>
<th data-i18n="th_apikey_created">DATE DE CRÉATION</th>
<th data-i18n="th_apikey_expires">EXPIRATION</th>
<th data-i18n="th_apikey_last_used">DERNIÈRE UTILISATION</th>
<th data-i18n="th_apikey_status">STATUT</th>
<th style="text-align:right" data-i18n="th_action">ACTION</th>
</tr>
</thead>
<tbody id="apiKeysTableBody">
<tr>
<td colspan="8" class="empty" data-i18n="loading_apikeys">Chargement des clés d’API…</td>
</tr>
</tbody>
</table>
</div>
<span id="apiKeysMessage" class="muted" style="margin-top:10px;display:block"></span>
</div>
</div>
<!-- 2b. Profils VPN (WireGuard & OpenVPN) -->
@@ -5540,7 +5577,7 @@
<div style="background:var(--panel2);padding:10px 12px;border-radius:8px;border:1px solid var(--line)">
<div class="label" data-i18n="adv_update_current_ver" style="font-size:11px">Version actuelle</div>
<div id="advUpdateCurrentCommit" style="font-family:monospace;font-size:16px;font-weight:700;color:var(--text);margin-top:2px">—</div>
<div class="muted" style="font-size:11px;margin-top:2px" id="advUpdateVersionTag">AP Manageur V5.5</div>
<div class="muted" style="font-size:11px;margin-top:2px" id="advUpdateVersionTag">AP Manageur V1.1 (Béta)</div>
</div>
<div style="background:var(--panel2);padding:10px 12px;border-radius:8px;border:1px solid var(--line)">
<div class="label" data-i18n="adv_update_latest_ver" style="font-size:11px">Dernière version (Gitea)</div>
@@ -6842,7 +6879,7 @@
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
<span style="font-weight:700;color:var(--text);word-break:break-all"
id="importFileName">fichier.json</span>
<span class="pill pill-blue" id="importFileVersion" style="font-weight:700">V5.5</span>
<span class="pill pill-blue" id="importFileVersion" style="font-weight:700">V1.1 (Béta)</span>
</div>
<div class="muted" style="font-size:12px" id="importFileMeta" data-i18n="modal_import_created_date">Date de
création : —</div>
@@ -6951,6 +6988,130 @@
</div>
</div>
<!-- 9b. Modal Création Clé d'API -->
<div id="modalCreateApiKey" class="modal-overlay">
<div class="modal-card" style="max-width:560px">
<div class="modal-header">
<h3 style="margin:0;display:flex;align-items:center;gap:8px" data-i18n="modal_create_apikey_title">⚡ Créer une clé d’API</h3>
<button type="button" class="secondary" onclick="closeCreateApiKeyModal()"
style="padding:4px 10px;font-size:16px;border-radius:6px">✕</button>
</div>
<div class="modal-body" style="display:flex;flex-direction:column;gap:14px">
<div>
<label class="label" for="apiKeyInputName" data-i18n="apikey_name_label">Nom ou description de la clé</label>
<input id="apiKeyInputName" type="text" maxlength="64" placeholder="Ex: Home Assistant, Script de sauvegarde..." data-i18n-placeholder="placeholder_apikey_name" style="margin:4px 0 0">
</div>
<div>
<label class="label" for="apiKeyExpirationSelect" data-i18n="apikey_expiration_label">Durée de validité (Expiration)</label>
<select id="apiKeyExpirationSelect" style="display:block;width:100%;margin:4px 0 0;padding:10px;border-radius:8px;border:1px solid var(--line);background:var(--panel2);color:var(--text);font-size:14px">
<option value="0" data-i18n="apikey_exp_never">Jamais (illimitée)</option>
<option value="30" data-i18n="apikey_exp_30d">30 jours</option>
<option value="90" data-i18n="apikey_exp_90d">90 jours</option>
<option value="365" data-i18n="apikey_exp_1y">1 an (365 jours)</option>
</select>
</div>
<div>
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
<label class="label" style="margin:0" data-i18n="apikey_perms_label">Types d'autorisations (Droits d'accès)</label>
<button type="button" class="secondary" onclick="toggleAllApiKeyPerms()" style="padding:2px 8px;font-size:11px" id="btnToggleAllPerms" data-i18n="apikey_select_all_btn">Tout sélectionner</button>
</div>
<p class="muted" style="font-size:12px;margin:0 0 10px" data-i18n="apikey_perms_desc">Sélectionnez les accès accordés à cette clé d’API selon son utilisation :</p>
<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px" id="apiKeyPermsGrid">
<label class="check" style="background:var(--panel2);padding:10px 12px;border-radius:8px;border:1px solid var(--line);display:flex;align-items:flex-start;gap:8px;cursor:pointer">
<input type="checkbox" id="permRead" value="read" checked style="margin-top:2px">
<div>
<strong style="font-size:13px;display:block" data-i18n="perm_read_title">👁️ Lecture seule</strong>
<span class="muted" style="font-size:11px" data-i18n="perm_read_desc">Statut, métriques, journaux, abonnés connectés</span>
</div>
</label>
<label class="check" style="background:var(--panel2);padding:10px 12px;border-radius:8px;border:1px solid var(--line);display:flex;align-items:flex-start;gap:8px;cursor:pointer">
<input type="checkbox" id="permWifi" value="wifi" style="margin-top:2px">
<div>
<strong style="font-size:13px;display:block" data-i18n="perm_wifi_title">📶 Gestion Wi-Fi</strong>
<span class="muted" style="font-size:11px" data-i18n="perm_wifi_desc">SSID, canal, démarrer/arrêter/redémarrer l'AP</span>
</div>
</label>
<label class="check" style="background:var(--panel2);padding:10px 12px;border-radius:8px;border:1px solid var(--line);display:flex;align-items:flex-start;gap:8px;cursor:pointer">
<input type="checkbox" id="permClients" value="clients" style="margin-top:2px">
<div>
<strong style="font-size:13px;display:block" data-i18n="perm_clients_title">👥 Clients &amp; Quotas</strong>
<span class="muted" style="font-size:11px" data-i18n="perm_clients_desc">Blocage, débits, quotas, renommage</span>
</div>
</label>
<label class="check" style="background:var(--panel2);padding:10px 12px;border-radius:8px;border:1px solid var(--line);display:flex;align-items:flex-start;gap:8px;cursor:pointer">
<input type="checkbox" id="permVpn" value="vpn" style="margin-top:2px">
<div>
<strong style="font-size:13px;display:block" data-i18n="perm_vpn_title">🛡️ Gestion VPN</strong>
<span class="muted" style="font-size:11px" data-i18n="perm_vpn_desc">Profils, connexion, routage des clients</span>
</div>
</label>
<label class="check" style="background:var(--panel2);padding:10px 12px;border-radius:8px;border:1px solid var(--line);display:flex;align-items:flex-start;gap:8px;cursor:pointer">
<input type="checkbox" id="permBackup" value="backup" style="margin-top:2px">
<div>
<strong style="font-size:13px;display:block" data-i18n="perm_backup_title">📦 Sauvegardes</strong>
<span class="muted" style="font-size:11px" data-i18n="perm_backup_desc">Export, création, planification, restauration</span>
</div>
</label>
<label class="check" style="background:var(--panel2);padding:10px 12px;border-radius:8px;border:1px solid var(--line);display:flex;align-items:flex-start;gap:8px;cursor:pointer">
<input type="checkbox" id="permAdmin" value="admin" style="margin-top:2px">
<div>
<strong style="font-size:13px;display:block;color:var(--yellow)" data-i18n="perm_admin_title">👑 Accès Total Admin</strong>
<span class="muted" style="font-size:11px" data-i18n="perm_admin_desc">Toutes les permissions et administration système</span>
</div>
</label>
</div>
</div>
<div id="apiKeyModalError" class="muted" style="color:var(--red);font-size:12px"></div>
</div>
<div class="modal-footer" style="display:flex;justify-content:flex-end;gap:10px">
<button type="button" class="secondary" onclick="closeCreateApiKeyModal()" data-i18n="btn_cancel">Annuler</button>
<button type="button" id="btnSubmitCreateApiKey" onclick="submitCreateApiKey()" data-i18n="btn_create_key">Générer la clé</button>
</div>
</div>
</div>
<!-- 9c. Modal Affichage Clé d'API Créée -->
<div id="modalApiKeyCreated" class="modal-overlay">
<div class="modal-card" style="max-width:540px">
<div class="modal-header">
<h3 style="margin:0;display:flex;align-items:center;gap:8px;color:var(--green)" data-i18n="modal_key_created_title">✅ Clé d’API créée avec succès !</h3>
<button type="button" class="secondary" onclick="closeApiKeyCreatedModal()"
style="padding:4px 10px;font-size:16px;border-radius:6px">✕</button>
</div>
<div class="modal-body" style="display:flex;flex-direction:column;gap:14px">
<div style="background:rgba(234,179,8,0.12);border:1px solid rgba(234,179,8,0.3);color:var(--yellow);padding:10px 14px;border-radius:8px;font-size:13px" data-i18n-html="apikey_warning_show_once">
⚠️ <strong>Attention :</strong> Copiez cette clé maintenant. Pour des raisons de sécurité, vous ne pourrez plus jamais la revoir. Si vous la perdez, vous devrez en créer une nouvelle.
</div>
<div>
<label class="label" data-i18n="apikey_token_label">Votre clé d'accès secrète</label>
<div style="display:flex;gap:8px;align-items:center;margin-top:4px">
<input type="text" id="createdApiKeyInput" readonly style="font-family:monospace;font-size:13px;font-weight:700;color:var(--blue);margin:0;background:var(--panel2);user-select:all">
<button type="button" id="btnCopyApiKey" onclick="copyCreatedApiKey()" style="display:inline-flex;align-items:center;gap:6px;white-space:nowrap" data-i18n="btn_copy">📋 Copier</button>
</div>
<span id="copyApiKeyStatus" class="muted" style="font-size:11px;margin-top:4px;display:block"></span>
</div>
<div style="background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:10px 12px;font-size:12px">
<strong data-i18n="apikey_usage_example">Exemple d’utilisation :</strong>
<pre style="margin:6px 0 0;padding:8px;background:rgba(0,0,0,0.3);border-radius:6px;overflow-x:auto;font-family:monospace;font-size:11px"><code id="apiKeyCurlExample">curl -H "X-API-Key: ap_key_..." http://192.168.1.1/api/status</code></pre>
</div>
</div>
<div class="modal-footer" style="display:flex;justify-content:flex-end">
<button type="button" onclick="closeApiKeyCreatedModal()" data-i18n="btn_close">J'ai copié ma clé / Fermer</button>
</div>
</div>
</div>
<!-- 10. Modal Easter Egg Arcade Games (Tetris, Dino, Zipline) -->
<div id="modalEasterEggGames" class="modal-overlay" style="z-index:99999">
<div id="modalEasterEggCard" class="modal-card"
@@ -7018,7 +7179,7 @@
function $(id) { return document.getElementById(id); }
const API_URL = location.protocol === 'file:' ? 'http://127.0.0.1:8080' : '';
/* Version de l'application */
const APP_VERSION = "V5.5";
const APP_VERSION = "V1.1 (Béta)";
const ICON_REFRESH_ARROW = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" style="display:inline-block;vertical-align:middle"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.9 1 6.7 2.4L21 8"/><polyline points="21 3 21 8 16 8"/></svg>';
const ICON_GEAR = '⚙️';
const ICON_TABLET = '<svg width="1.15em" height="1.15em" viewBox="0 0 24 24" fill="none" style="display:inline-block;vertical-align:-0.18em;flex-shrink:0" aria-label="Tablette"><rect x="2.5" y="1.5" width="19" height="21" rx="2.5" fill="#1e293b" stroke="#64748b" stroke-width="1"/><rect x="4" y="3.2" width="16" height="15.6" rx="1.2" fill="#38bdf8"/><circle cx="12" cy="2.3" r="0.5" fill="#94a3b8"/><rect x="10" y="20" width="4" height="1.2" rx="0.6" fill="#94a3b8"/></svg>';
@@ -7469,6 +7630,7 @@
try { if (typeof renderTopologyStats === 'function' && typeof topologyDataCache !== 'undefined' && topologyDataCache) renderTopologyStats(topologyDataCache); } catch (_) { }
try { if (typeof renderVpnProfiles === 'function' && typeof vpnProfilesCache !== 'undefined') renderVpnProfiles(vpnProfilesCache); } catch (_) { }
try { if (typeof renderSessionsTable === 'function') renderSessionsTable(); } catch (_) { }
try { if (typeof renderApiKeysTable === 'function') renderApiKeysTable(); } catch (_) { }
try { if (typeof loadPasskeysList === 'function' && window.passkeysById) loadPasskeysList(); } catch (_) { }
try { if (typeof render2faCurrentState === 'function') render2faCurrentState(); } catch (_) { }
try { if (typeof renderDeviceTypesTable === 'function') renderDeviceTypesTable(); } catch (_) { }
@@ -9161,7 +9323,7 @@ ${vpnBadgeTopo}
panel.classList.toggle('active', k === tabKey);
}
});
if (tabKey === 'admin') { if (typeof loadAdminUser === 'function') loadAdminUser(); if (typeof loadSessions === 'function') loadSessions(); if (typeof loadPasskeysList === 'function') loadPasskeysList(); }
if (tabKey === 'admin') { if (typeof loadAdminUser === 'function') loadAdminUser(); if (typeof loadSessions === 'function') loadSessions(); if (typeof loadPasskeysList === 'function') loadPasskeysList(); if (typeof loadApiKeys === 'function') loadApiKeys(); }
if (tabKey === 'vpn') {
if (typeof loadVpnProfiles === 'function') loadVpnProfiles();
if (typeof loadVpnClients === 'function') loadVpnClients();
@@ -9231,204 +9393,6 @@ ${vpnBadgeTopo}
if ($('nav')) $('nav').style.display = configured ? 'flex' : 'none';
if ($('dashboardTab')) $('dashboardTab').style.display = configured ? '' : 'none';
if ($('statsTab')) $('statsTab').style.display = configured ? '' : 'none';
if ($('devicesTab')) $('devicesTab').style.display = configured ? '' : 'none';
if ($('advancedTab')) $('advancedTab').style.display = configured ? '' : 'none';
if ($('settingsTab')) $('settingsTab').style.display = configured ? '' : 'none';
if ($('logsTab')) $('logsTab').style.display = configured ? '' : 'none';
if ($('blockedTab')) $('blockedTab').style.display = configured ? '' : 'none';
if ($('apControl')) {
$('apControl').style.display = configured ? '' : 'none';
$('apControl').textContent = active ? t('btn_stop', 'Arrêter') : t('btn_start', 'Démarrer');
$('apControl').style.background = active ? 'var(--red)' : 'var(--blue)';
$('apControl').style.color = active ? 'white' : 'var(--blue-text, #071326)';
}
if ($('apRestart')) {
$('apRestart').style.display = configured ? '' : 'none';
$('apRestart').disabled = !active;
$('apRestart').style.opacity = active ? '1' : '0.4';
$('apRestart').style.cursor = active ? 'pointer' : 'not-allowed';
$('apRestart').title = active ? t('btn_restart', 'Redémarrer') : t('ap_stopped_no_restart', "L'AP est arrêtée (démarrage requis)");
}
if ($('refresh')) $('refresh').style.display = configured ? '' : 'none';
const updateInfo = (status && status.update) ? status.update : null;
if (updateInfo) lastUpdateData = updateInfo;
const updateAvailable = !!(updateInfo && updateInfo.available);
if ($('btnUpdateAvailable')) {
$('btnUpdateAvailable').style.display = (configured && updateAvailable) ? 'inline-flex' : 'none';
}
}
let lastUpdateData = null;
function openUpdateModal() {
const modal = $('modalUpdateApp');
if (!modal) return;
const u = lastUpdateData || (status && status.update) || {};
const isAvail = !!u.available;
if ($('updateCurrentCommit')) $('updateCurrentCommit').textContent = u.current_commit || (u.current_commit_full ? u.current_commit_full.substring(0, 7) : '—');
if ($('updateLatestCommit')) $('updateLatestCommit').textContent = u.latest_commit || (u.latest_commit_full ? u.latest_commit_full.substring(0, 7) : '—');
if ($('updateCommitMsg')) $('updateCommitMsg').textContent = u.commit_msg || t('update_no_msg', 'Aucun message de commit');
if ($('updateCommitAuthor')) $('updateCommitAuthor').textContent = u.author ? ('Par ' + u.author) : '';
if ($('updateCommitDate')) {
let dStr = '';
if (u.date) {
try { dStr = 'le ' + new Date(u.date).toLocaleString(); } catch (_) { dStr = 'le ' + u.date; }
}
$('updateCommitDate').textContent = dStr;
}
if ($('updateStatusAlert')) {
$('updateStatusAlert').style.background = isAvail ? 'rgba(16,185,129,0.1)' : 'rgba(56,189,248,0.1)';
$('updateStatusAlert').style.borderColor = isAvail ? 'rgba(16,185,129,0.3)' : 'rgba(56,189,248,0.3)';
}
if ($('updateStatusIcon')) {
$('updateStatusIcon').textContent = isAvail ? '🚀' : '✅';
}
if ($('updateStatusTitle')) {
$('updateStatusTitle').textContent = isAvail ? t('update_new_version_found', 'Une nouvelle version de AP Manageur est prête !') : t('update_up_to_date', 'AP Manageur est à jour !');
$('updateStatusTitle').style.color = isAvail ? '#10b981' : 'var(--blue)';
}
if ($('updateStatusDesc')) {
$('updateStatusDesc').textContent = isAvail ? t('update_new_version_desc', "Une mise à jour plus récente de l'application est disponible sur le dépôt.") : t('update_up_to_date_desc', "Vous disposez déjà de la version la plus récente de l'application.");
}
if ($('updateDockerCmdSection')) {
$('updateDockerCmdSection').style.display = isAvail ? 'block' : 'none';
}
modal.classList.add('active');
}
window.openUpdateModal = openUpdateModal;
function closeUpdateModal() {
const modal = $('modalUpdateApp');
if (modal) modal.classList.remove('active');
}
window.closeUpdateModal = closeUpdateModal;
async function copyUpdateCommand() {
const input = $('updateDockerCmd');
const btnText = $('btnCopyUpdateCmdText');
if (!input) return;
const cmd = input.value;
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(cmd);
} else {
input.select();
document.execCommand('copy');
}
if (btnText) {
const original = btnText.textContent;
btnText.textContent = t('update_cmd_copied', '✓ Copié !');
setTimeout(() => { if (btnText) btnText.textContent = original; }, 2000);
}
} catch (err) {
input.select();
document.execCommand('copy');
}
}
window.copyUpdateCommand = copyUpdateCommand;
async function triggerManualUpdateCheck() {
const btn = $('btnCheckUpdateManual');
if (btn) btn.disabled = true;
try {
const res = await apiFetch('/api/system/update?force=1', { cache: 'no-store' });
if (res.ok) {
const u = await res.json();
lastUpdateData = u;
if (status) status.update = u;
updateApButtons();
openUpdateModal();
}
} catch (e) {
console.warn('Erreur vérification mise à jour :', e);
} finally {
if (btn) btn.disabled = false;
}
}
window.triggerManualUpdateCheck = triggerManualUpdateCheck;
async function toggleBlock(mac, blocked) {
return runAction(async () => {
try {
const response = await apiFetch('/api/clients/block', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ mac, blocked }) });
const data = await response.json(); if (!response.ok) throw Error(data.error || 'Opération refusée');
await load();
} catch (e) { alert(tErr(e.message)) }
});
}
function render() {
updateApButtons();
$('clientCount').textContent = status.max_clients > 0 ? `${clients.length} / ${status.max_clients}` : clients.length;
$('ssid').textContent = status.ssid || 'SSID inconnu';
$('uptime').textContent = status.active ? uptime(status.uptime_seconds) : '—';
$('settingsSsid').value = status.ssid || '';
$('settingsPassword').value = status.password || '';
$('settingsSecurity').value = status.security || 'wpa2';
if ($('settingsMaxClients')) $('settingsMaxClients').value = status.max_clients !== undefined ? status.max_clients : 0;
const isBridge = status.mode === 'bridge';
if ($('networkModeBadge')) {
$('networkModeBadge').textContent = isBridge ? t('badge_mode_bridge', 'Pont (DHCP Box)') : t('badge_mode_ap', 'AP (Routeur/NAT)');
$('networkModeBadge').className = 'pill ' + (isBridge ? 'pill-blue' : 'pill-green');
$('networkModeBadge').style.background = '';
$('networkModeBadge').style.color = '';
}
if ($('settingsModeAp') && $('settingsModeBridge')) {
if (isBridge) $('settingsModeBridge').checked = true; else $('settingsModeAp').checked = true;
if ($('settingsBridgeBlock')) $('settingsBridgeBlock').style.display = isBridge ? 'block' : 'none';
}
const ethList = status.ethernet_interfaces || [];
const populateEth = (selId, cur) => {
const el = $(selId); if (!el) return; const val = el.value || cur;
el.innerHTML = ethList.length ? ethList.map(e => `<option value="${e}">${e}</option>`).join('') : '<option value="">Auto-détection</option>';
if (val && ethList.includes(val)) el.value = val; else if (cur && ethList.includes(cur)) el.value = cur;
};
populateEth('setupBridgeEth', status.bridge_eth); populateEth('settingsBridgeEth', status.bridge_eth);
$('settingsAutoconnect').checked = !!status.autoconnect;
$('updated').textContent = formatLastUpdated();
$('state').innerHTML = status.active ? '<i class="dot"></i> ' + t('status_active', 'Actif') : '<i class="dot" style="background:var(--red)"></i> ' + t('status_inactive', 'Inactif');
const totalPages = Math.max(1, Math.ceil(clients.length / 10));
if (clientsPage > totalPages) clientsPage = totalPages; if (clientsPage < 1) clientsPage = 1;
const pagedClients = clients.slice((clientsPage - 1) * 10, clientsPage * 10);
$('clients').innerHTML = pagedClients.length ? pagedClients.map(c => {
const speedHtml = c.blocked
? `<span class="signal-faible">● ${t('status_blocked', 'Bloqué')}</span>`
: `<span style="font-family:monospace;font-size:13px;white-space:nowrap"><span style="color:var(--blue);font-weight:700" title="Débit descendant">↓ ${c.download_speed_str || formatSpeed(c.download_speed)}</span><span style="color:var(--muted);margin:0 5px">|</span><span style="color:var(--green);font-weight:700" title="Débit montant">↑ ${c.upload_speed_str || formatSpeed(c.upload_speed)}</span></span>`;
const vpnHtml = c.vpn_routed
? `<span class="pill pill-green" style="font-size:11px;font-weight:600;display:inline-flex;align-items:center;gap:4px" title="Trafic chiffré via ${escapeHtml(c.vpn_profile_name)}">🛡️ ${escapeHtml(c.vpn_profile_name)}${c.vpn_public_ip ? ` <span style="font-family:monospace;font-size:10px;opacity:.9">(${escapeHtml(c.vpn_public_ip)})</span>` : ''}</span>`
: (c.vpn_profile_name
? (c.kill_switch
? `<span class="pill" style="background:rgba(255,107,107,.15);color:var(--red);font-size:11px;font-weight:600">🛡️ ${t('vpn_killswitch_chk', 'Kill-Switch')}</span>`
: `<span class="pill" style="background:rgba(246,173,85,.15);color:#f6ad55;font-size:11px">⚠️ Direct</span>`)
: `<span class="muted" style="font-size:12px;display:inline-flex;align-items:center;gap:4px">🌐 ${t('topo_direct_wan', 'Direct WAN (Box)')}</span>`);
const ipLabel = c.ip || t('not_assigned', 'Non attribuée');
const nameLabel = String(c.name || t('name_unknown', 'Nom non communiqué')).replace(/[&<>"']/g, ch => '&#' + ch.charCodeAt(0) + ';');
return `<tr><td><div class="client"><div class="avatar">${String(c.name || '?')[0].toUpperCase()}</div><strong>${nameLabel}</strong></div></td><td>${ipLabel}</td><td>${c.mac || '—'}</td><td>${vpnHtml}</td><td>${signalQuality(c.signal_dbm, c)}</td><td>${speedHtml}</td></tr>`;
}).join('') : `<tr><td colspan="6" class="empty">${t('no_clients', 'Aucun client connecté')}</td></tr>`;
renderPagination('clientsPagination', clientsPage, clients.length, 'changeClientsPage', 10);
qr();
}
window.changeClientsPage = (p) => { clientsPage = p; render(); };
let isLoadInProgress = false;
let loadFailureCount = 0;
async function load() {
if (isLoadInProgress) return;
isLoadInProgress = true;
try {
let [a, b] = await Promise.all([apiFetch('/api/status', { cache: 'no-store', timeout: 10000 }), apiFetch('/api/clients', { cache: 'no-store', timeout: 10000 })]);
if (!a.ok || !b.ok) {
const response = !a.ok ? a : b; let detail = 'HTTP ' + response.status;
try { const body = await response.json(); detail = body.error || detail; } catch (_) { }
throw Error(detail);
}
const nextStatus = await a.json(); const nextClients = await b.json();
const signature = nextClients.map(client => client.mac).sort().join('|');
const changed = previousClientSignature !== null && signature !== previousClientSignature;
status = nextStatus; clients = nextClients; previousClientSignature = signature;
@@ -9494,7 +9458,10 @@ ${vpnBadgeTopo}
'suppression_sauvegarde_distante': t('log_suppr_distant', '🗑️ Suppr. sur le drive'),
'export_sauvegarde_complete': t('log_export_sauvegarde', '💾 Export sauvegarde'),
'export_base_sqlite': t('log_export_sqlite', '💾 Export SQLite'),
'export_configuration_json': t('log_export_json', '💾 Export JSON')
'export_configuration_json': t('log_export_json', '💾 Export JSON'),
'cle_api_creee': t('log_cle_api_creee', '⚡ Clé API créée'),
'cle_api_modifiee': t('log_cle_api_modifiee', '⚡ Clé API modifiée'),
'cle_api_supprimee': t('log_cle_api_supprimee', '🗑️ Clé API supprimée')
};
tbody.innerHTML = paged.map(log => {
const ev = String(log.event || '').toLowerCase();
@@ -9505,7 +9472,7 @@ ${vpnBadgeTopo}
eventHtml = '<span style="color:var(--red);font-weight:600">' + t('log_deconnexion', '○ Déconnexion Wi-Fi') + '</span>';
} else {
const label = labels[log.event] || log.event;
if (ev.includes('admin') || ev.includes('2fa') || ev === 'création' || ev === 'démarrage' || ev.includes('sauvegarde') || ev.includes('distant') || ev.includes('export')) {
if (ev.includes('admin') || ev.includes('2fa') || ev.includes('cle_api') || ev === 'création' || ev === 'démarrage' || ev.includes('sauvegarde') || ev.includes('distant') || ev.includes('export')) {
eventHtml = `<span style="color:var(--blue);font-weight:600">${label}</span>`;
} else if (ev.includes('vpn') || ev === 'vpn_route' || ev === 'vpn_connect') {
eventHtml = `<span style="color:var(--green);font-weight:600">${label}</span>`;
@@ -11722,7 +11689,7 @@ ${vpnBadgeTopo}
}
if (logs) loadLogs();
if (blocked) loadBlocked();
if (settings) { selectSettingsTab(currentSettingsTab || 'wifi'); load2fa(); if ((currentSettingsTab || 'wifi') === 'admin') { if (typeof loadAdminUser === 'function') loadAdminUser(); if (typeof loadSessions === 'function') loadSessions(); if (typeof loadPasskeysList === 'function') loadPasskeysList(); } }
if (settings) { selectSettingsTab(currentSettingsTab || 'wifi'); load2fa(); if ((currentSettingsTab || 'wifi') === 'admin') { if (typeof loadAdminUser === 'function') loadAdminUser(); if (typeof loadSessions === 'function') loadSessions(); if (typeof loadPasskeysList === 'function') loadPasskeysList(); if (typeof loadApiKeys === 'function') loadApiKeys(); } }
}
if ($('dashboardTab')) $('dashboardTab').onclick = () => selectTab('dashboard');
@@ -13735,6 +13702,207 @@ ${vpnBadgeTopo}
if ($('btnAddPasskey')) $('btnAddPasskey').onclick = () => runAction(registerPasskey);
if ($('btnAuthPasskey')) $('btnAuthPasskey').onclick = loginWithPasskey;
/* ==========================================================================
Gestion des Clés d'API & Droits d'Accès Programmatique
========================================================================== */
let apiKeysDataCache = [];
async function loadApiKeys() {
const tbody = $('apiKeysTableBody');
if (!tbody) return;
try {
const res = await apiFetch('/api/auth/api-keys', { cache: 'no-store' });
if (!res.ok) throw new Error('HTTP ' + res.status);
const data = await res.json();
apiKeysDataCache = data.api_keys || [];
renderApiKeysTable();
} catch (e) {
tbody.innerHTML = `<tr><td colspan="8" class="empty">${t('apikey_load_error', 'Impossible de charger les clés d’API')} (${escapeHtml(e.message)})</td></tr>`;
}
}
function renderApiKeysTable() {
const tbody = $('apiKeysTableBody');
if (!tbody) return;
if (!apiKeysDataCache || !apiKeysDataCache.length) {
tbody.innerHTML = `<tr><td colspan="8" class="empty">${t('no_api_keys', 'Aucune clé d’API configurée')}</td></tr>`;
return;
}
const permBadges = {
'read': `<span class="pill" style="font-size:10px;background:rgba(56,189,248,0.12);color:var(--blue);border:1px solid rgba(56,189,248,0.3)">👁️ ${t('perm_read_title', 'Lecture')}</span>`,
'wifi': `<span class="pill" style="font-size:10px;background:rgba(16,185,129,0.12);color:var(--green);border:1px solid rgba(16,185,129,0.3)">📶 ${t('perm_wifi_title', 'Wi-Fi')}</span>`,
'clients': `<span class="pill" style="font-size:10px;background:rgba(168,85,247,0.12);color:#c084fc;border:1px solid rgba(168,85,247,0.3)">👥 ${t('perm_clients_title', 'Clients')}</span>`,
'vpn': `<span class="pill" style="font-size:10px;background:rgba(20,184,166,0.12);color:#2dd4bf;border:1px solid rgba(20,184,166,0.3)">🛡️ ${t('perm_vpn_title', 'VPN')}</span>`,
'backup': `<span class="pill" style="font-size:10px;background:rgba(249,115,22,0.12);color:#fb923c;border:1px solid rgba(249,115,22,0.3)">📦 ${t('perm_backup_title', 'Sauvegarde')}</span>`,
'admin': `<span class="pill" style="font-size:10px;background:rgba(234,179,8,0.12);color:var(--yellow);border:1px solid rgba(234,179,8,0.3)">👑 ${t('perm_admin_title', 'Admin')}</span>`
};
tbody.innerHTML = apiKeysDataCache.map(k => {
const isAct = Boolean(k.is_active);
const statusPill = isAct
? `<span class="pill" style="font-size:11px;background:rgba(16,185,129,0.12);color:var(--green);border:1px solid rgba(16,185,129,0.3)">● ${t('active', 'Active')}</span>`
: `<span class="pill" style="font-size:11px;background:rgba(239,68,68,0.12);color:var(--red);border:1px solid rgba(239,68,68,0.3)">○ ${t('disabled', 'Désactivée')}</span>`;
const permsHtml = (k.permissions || []).map(p => permBadges[p] || `<span class="pill" style="font-size:10px">${escapeHtml(p)}</span>`).join(' ') || '—';
const expText = k.expires_at ? escapeHtml(k.expires_at) : `<span class="muted">${t('never', 'Jamais')}</span>`;
const lastUsedText = k.last_used_at ? `${escapeHtml(k.last_used_at)} <span class="muted" style="font-size:10px">(${escapeHtml(k.last_ip || '—')})</span>` : `<span class="muted">${t('never', 'Jamais')}</span>`;
const toggleBtnTitle = isAct ? t('btn_disable_key', 'Désactiver') : t('btn_enable_key', 'Activer');
const toggleBtnIcon = isAct ? '⏸️' : '▶️';
return `<tr>
<td><strong>${escapeHtml(k.name)}</strong></td>
<td><code style="font-size:12px;background:var(--panel2);padding:2px 6px;border-radius:4px;border:1px solid var(--line);color:var(--blue)">${escapeHtml(k.prefix)}</code></td>
<td><div style="display:flex;gap:4px;flex-wrap:wrap">${permsHtml}</div></td>
<td style="font-size:12px">${escapeHtml(k.created_at)}</td>
<td style="font-size:12px">${expText}</td>
<td style="font-size:12px">${lastUsedText}</td>
<td>${statusPill}</td>
<td style="text-align:right">
<div style="display:inline-flex;gap:6px">
<button type="button" class="secondary" onclick="toggleApiKey(${k.id})" title="${toggleBtnTitle}" style="padding:4px 8px;font-size:12px">${toggleBtnIcon}</button>
<button type="button" class="secondary" onclick="deleteApiKey(${k.id}, '${escapeHtml(k.name)}')" title="${t('btn_delete', 'Supprimer')}" style="padding:4px 8px;font-size:12px;color:var(--red)">🗑️</button>
</div>
</td>
</tr>`;
}).join('');
}
window.openCreateApiKeyModal = function() {
const m = $('modalCreateApiKey');
if (!m) return;
$('apiKeyInputName').value = '';
$('apiKeyExpirationSelect').value = '0';
$('permRead').checked = true;
$('permWifi').checked = false;
$('permClients').checked = false;
$('permVpn').checked = false;
$('permBackup').checked = false;
$('permAdmin').checked = false;
$('apiKeyModalError').textContent = '';
m.classList.add('active');
setTimeout(() => $('apiKeyInputName').focus(), 100);
};
window.closeCreateApiKeyModal = function() {
const m = $('modalCreateApiKey');
if (m) m.classList.remove('active');
};
window.toggleAllApiKeyPerms = function() {
const ids = ['permRead', 'permWifi', 'permClients', 'permVpn', 'permBackup', 'permAdmin'];
const allChecked = ids.every(id => $(id)?.checked);
ids.forEach(id => { if ($(id)) $(id).checked = !allChecked; });
};
window.submitCreateApiKey = async function() {
const name = $('apiKeyInputName').value.trim();
const errEl = $('apiKeyModalError');
if (!name) {
errEl.textContent = t('apikey_name_required', 'Veuillez saisir un nom pour cette clé d’API');
return;
}
const perms = [];
if ($('permRead')?.checked) perms.push('read');
if ($('permWifi')?.checked) perms.push('wifi');
if ($('permClients')?.checked) perms.push('clients');
if ($('permVpn')?.checked) perms.push('vpn');
if ($('permBackup')?.checked) perms.push('backup');
if ($('permAdmin')?.checked) perms.push('admin');
if (!perms.length) {
errEl.textContent = t('apikey_perms_required', 'Veuillez sélectionner au moins une autorisation');
return;
}
const expires_in_days = parseInt($('apiKeyExpirationSelect').value, 10) || 0;
errEl.textContent = '';
const btn = $('btnSubmitCreateApiKey');
if (btn) btn.disabled = true;
try {
const res = await apiFetch('/api/auth/api-keys/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, permissions: perms, expires_in_days })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Erreur lors de la création');
closeCreateApiKeyModal();
await loadApiKeys();
if (data.api_key && data.api_key.token) {
$('createdApiKeyInput').value = data.api_key.token;
const host = location.origin || 'http://192.168.1.1';
$('apiKeyCurlExample').textContent = `curl -H "X-API-Key: ${data.api_key.token}" ${host}/api/status`;
$('copyApiKeyStatus').textContent = '';
$('modalApiKeyCreated').classList.add('active');
}
} catch (e) {
errEl.textContent = tErr(e.message);
} finally {
if (btn) btn.disabled = false;
}
};
window.closeApiKeyCreatedModal = function() {
const m = $('modalApiKeyCreated');
if (m) m.classList.remove('active');
};
window.copyCreatedApiKey = function() {
const input = $('createdApiKeyInput');
if (!input) return;
input.select();
navigator.clipboard.writeText(input.value).then(() => {
$('copyApiKeyStatus').textContent = '✅ ' + t('copied_to_clipboard', 'Clé copiée dans le presse-papier !');
setTimeout(() => { if ($('copyApiKeyStatus')) $('copyApiKeyStatus').textContent = ''; }, 3000);
}).catch(() => {
$('copyApiKeyStatus').textContent = t('copy_failed', 'Appuyez sur Ctrl+C pour copier la clé');
});
};
window.toggleApiKey = async function(id) {
const sm = $('apiKeysMessage');
try {
const res = await apiFetch('/api/auth/api-keys/toggle', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Erreur modification');
await loadApiKeys();
if (sm) sm.textContent = tMsg(data.message);
setTimeout(() => { if (sm && (sm.textContent.includes('succès') || sm.textContent.includes('successfully'))) sm.textContent = ''; }, 3000);
} catch (e) {
if (sm) sm.textContent = tErr(e.message);
}
};
window.deleteApiKey = async function(id, name) {
if (!confirm(t('apikey_delete_confirm', `Êtes-vous sûr de vouloir supprimer définitivement la clé d’API « ${name} » ?\nTous les services l'utilisant perdront leur accès.`))) {
return;
}
const sm = $('apiKeysMessage');
try {
const res = await apiFetch('/api/auth/api-keys/delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Erreur suppression');
await loadApiKeys();
if (sm) sm.textContent = tMsg(data.message);
setTimeout(() => { if (sm && (sm.textContent.includes('succès') || sm.textContent.includes('successfully'))) sm.textContent = ''; }, 3000);
} catch (e) {
if (sm) sm.textContent = tErr(e.message);
}
};
/* Système de configuration et test des notifications multi-canaux */
const NOTIF_EVENT_META = {
new_device: { defaultTitle: "📱 Nouvel appareil détecté", defaultMsg: "L'appareil « {name} » vient de se connecter pour la première fois au réseau Wi-Fi." },