diff --git a/ap.py b/ap.py index cbda9df..02433d5 100644 --- a/ap.py +++ b/ap.py @@ -290,7 +290,7 @@ if not is_auto_channel(): else: AP_CHANNEL = get_effective_ap_channel(AP_BAND) -APP_VERSION = 'V5.5' +APP_VERSION = 'V1.1 (Béta)' SERVER_BOOT_TIME = time.time() app_startup_done = False SESSION_TTL = 30 * 86400 # 30 jours (1 mois) @@ -783,6 +783,20 @@ def init_db(): updated_at TEXT DEFAULT '' ) ''') + c.execute(''' + CREATE TABLE IF NOT EXISTS api_keys ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + key_hash TEXT UNIQUE NOT NULL, + prefix TEXT NOT NULL, + permissions TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT DEFAULT NULL, + last_used_at TEXT DEFAULT NULL, + last_ip TEXT DEFAULT NULL, + is_active INTEGER DEFAULT 1 + ) + ''') init_device_types_table(c) # Assainissement et nettoyage des anciennes données non-MAC (sauvegardes, audits, etc.) try: @@ -1430,8 +1444,129 @@ def list_sessions(current_token='', lang='fr'): }) return res +def parse_api_key_permissions(perms_str): + if isinstance(perms_str, list): + return [str(p).strip().lower() for p in perms_str if str(p).strip()] + if not perms_str: + return [] + try: + val = json.loads(perms_str) + if isinstance(val, list): + return [str(p).strip().lower() for p in val if str(p).strip()] + except Exception: + pass + return [p.strip().lower() for p in str(perms_str).split(',') if p.strip()] + +_api_keys_cache = {} +_api_keys_cache_lock = threading.Lock() + +def get_api_key_by_token(token): + if not token or not isinstance(token, str) or not token.startswith('ap_key_'): + return None + token_hash = hashlib.sha256(token.encode('utf-8')).hexdigest() + now_time = time.time() + with _api_keys_cache_lock: + cached = _api_keys_cache.get(token_hash) + if cached and (now_time - cached.get('_cached_at', 0) < 15): + return cached + + try: + c = db() + row = c.execute(''' + SELECT id, name, key_hash, prefix, permissions, created_at, expires_at, last_used_at, last_ip, is_active + FROM api_keys WHERE key_hash=? + ''', (token_hash,)).fetchone() + c.close() + if row: + key_data = { + 'id': row[0], + 'name': row[1], + 'key_hash': row[2], + 'prefix': row[3], + 'permissions': parse_api_key_permissions(row[4]), + 'created_at': row[5], + 'expires_at': row[6], + 'last_used_at': row[7], + 'last_ip': row[8], + 'is_active': int(row[9] or 0), + '_cached_at': now_time + } + with _api_keys_cache_lock: + _api_keys_cache[token_hash] = key_data + return key_data + except Exception as e: + print(f"[ap-api-keys] Erreur récupération clé API: {e}", flush=True) + return None + +def update_api_key_usage(key_id, ip=''): + try: + now_str = time.strftime('%Y-%m-%d %H:%M:%S') + c = db() + c.execute('UPDATE api_keys SET last_used_at=?, last_ip=? WHERE id=?', (now_str, ip or '', key_id)) + c.commit(); c.close() + except Exception: + pass + +def check_api_key_permission(perms, method, path): + if not perms: + return False + if 'admin' in perms: + return True + method = method.upper() + path_only = path.split('?')[0] + + # Droits 'read' (lecture seule métriques, statut, abonnés, logs) + if 'read' in perms and method in ('GET', 'HEAD'): + read_prefixes = ( + '/api/status', '/api/stats', '/api/clients', '/api/devices', + '/api/device-types', '/api/logs', '/api/network/topology', + '/api/wifi/channel', '/api/vpn/profiles', '/api/vpn/clients', + '/api/vpn/check-ip', '/api/vpn/public-ip', '/api/preferences', + '/api/settings/proxy', '/api/notifications/settings', + '/api/advanced/domains', '/api/advanced/geoip', + '/api/advanced/capture/status', '/api/advanced/capture/packets', + '/api/system/update' + ) + if any(path_only == p or path_only.startswith(p + '/') for p in read_prefixes): + return True + + # Droits 'wifi' + if 'wifi' in perms: + if method in ('GET', 'HEAD') and path_only in ('/api/wifi/channel', '/api/status'): + return True + if method == 'POST' and path_only in ('/api/ap/control', '/api/ap/mode', '/api/settings', '/api/setup', '/api/stats/refresh'): + return True + + # Droits 'clients' + if 'clients' in perms: + if method in ('GET', 'HEAD') and (path_only.startswith('/api/clients') or path_only.startswith('/api/devices')): + return True + if method == 'POST' and ( + path_only in ('/api/clients/block', '/api/devices/limits', '/api/devices/rename', '/api/devices/set_type', '/api/devices/delete') + or path_only.startswith('/api/device-types') + ): + return True + + # Droits 'vpn' + if 'vpn' in perms: + if method in ('GET', 'HEAD') and path_only.startswith('/api/vpn'): + return True + if method == 'POST' and path_only.startswith('/api/vpn'): + return True + + # Droits 'backup' + if 'backup' in perms: + if method in ('GET', 'HEAD') and (path_only.startswith('/api/backup') or path_only.startswith('/api/backups')): + return True + if method == 'POST' and (path_only.startswith('/api/backup') or path_only.startswith('/api/backups')): + return True + + return False + def extract_token(h): - token = h.headers.get('X-Session-Token', '') if hasattr(h, 'headers') else '' + token = h.headers.get('X-API-Key', '') if hasattr(h, 'headers') else '' + if not token and hasattr(h, 'headers'): + token = h.headers.get('X-Session-Token', '') if not token and hasattr(h, 'headers'): auth_hdr = h.headers.get('Authorization', '') if auth_hdr.lower().startswith('bearer '): @@ -1447,10 +1582,44 @@ def extract_token(h): parsed = urllib.parse.urlparse(h.path) token = urllib.parse.parse_qs(parsed.query).get('token', [''])[0] except Exception: pass + if not token and hasattr(h, 'path') and 'api_key=' in h.path: + try: + parsed = urllib.parse.urlparse(h.path) + token = urllib.parse.parse_qs(parsed.query).get('api_key', [''])[0] + except Exception: pass return token def valid_session(h): token = extract_token(h) + if not token: + return False + + # Authentification via clé d'API (ap_key_...) + if token.startswith('ap_key_'): + k = get_api_key_by_token(token) + if not k or not k.get('is_active'): + return False + exp = k.get('expires_at') + if exp and exp.strip(): + now_str = time.strftime('%Y-%m-%d %H:%M:%S') + if now_str > exp: + return False + method = getattr(h, 'command', 'GET') + path = getattr(h, 'path', '') + path_only = path.split('?')[0] + perms = k.get('permissions', []) + # La gestion des clés d'API requiert un accès administrateur total + if path_only.startswith('/api/auth/api-keys') and 'admin' not in perms: + return False + if not check_api_key_permission(perms, method, path): + return False + try: + update_api_key_usage(k['id'], request_ip(h)) + except Exception: + pass + return True + + # Authentification classique de session web s = get_session(token) if s is not None: try: @@ -1462,6 +1631,13 @@ def valid_session(h): def username(h): token = extract_token(h) + if not token: + return '' + if token.startswith('ap_key_'): + k = get_api_key_by_token(token) + if k: + return f"API:{k.get('name', 'Clé API')}" + return 'API' s = get_session(token) return s.get('username', '') if s else '' @@ -8556,6 +8732,15 @@ def export_backup_data(): 'id': r[0], 'username': r[1], 'public_key': r[2], 'name': r[3], 'device_type': r[4], 'sign_count': r[5], 'created_at': r[6], 'last_used_at': r[7] }) + api_keys = [] + has_ak = bool(c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='api_keys'").fetchone()) + if has_ak: + for r in c.execute("SELECT id, name, key_hash, prefix, permissions, created_at, expires_at, last_used_at, last_ip, is_active FROM api_keys").fetchall(): + api_keys.append({ + 'id': r[0], 'name': r[1], 'key_hash': r[2], 'prefix': r[3], + 'permissions': r[4], 'created_at': r[5], 'expires_at': r[6], + 'last_used_at': r[7], 'last_ip': r[8], 'is_active': r[9] + }) client_traffic = [] for r in c.execute("SELECT mac, rx_bytes, tx_bytes, last_updated FROM client_traffic").fetchall(): client_traffic.append({ @@ -8597,6 +8782,7 @@ def export_backup_data(): 'blocked_clients': blocked_clients, 'auth_users': auth_users, 'auth_passkeys': auth_passkeys, + 'api_keys': api_keys, 'client_traffic': client_traffic, 'client_traffic_daily': client_traffic_daily, 'connection_logs': connection_logs @@ -8851,6 +9037,27 @@ def import_backup_data(payload, options=None): last_used_at=excluded.last_used_at ''', (pk_id, pk_uname, pk_key, pk_name, pk_dev, pk_count, pk_c_at, pk_u_at)) stats['auth_passkeys'] += 1 + if 'api_keys' in backup and isinstance(backup['api_keys'], list): + for ak in backup['api_keys']: + ak_name = str(ak.get('name', '')).strip() + ak_hash = str(ak.get('key_hash', '')).strip() + ak_prefix = str(ak.get('prefix', '')).strip() + ak_perms = json.dumps(ak.get('permissions')) if isinstance(ak.get('permissions'), list) else str(ak.get('permissions', '[]')) + ak_c_at = str(ak.get('created_at', '')).strip() or time.strftime('%Y-%m-%d %H:%M:%S') + ak_exp = ak.get('expires_at') + ak_act = 1 if ak.get('is_active', 1) else 0 + if ak_name and ak_hash and ak_prefix: + c.execute(''' + INSERT INTO api_keys (name, key_hash, prefix, permissions, created_at, expires_at, is_active) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(key_hash) DO UPDATE SET + name=excluded.name, + prefix=excluded.prefix, + permissions=excluded.permissions, + expires_at=excluded.expires_at, + is_active=excluded.is_active + ''', (ak_name, ak_hash, ak_prefix, ak_perms, ak_c_at, ak_exp, ak_act)) + stats['api_keys'] = stats.get('api_keys', 0) + 1 c.commit() finally: @@ -10821,6 +11028,14 @@ API_MSG_I18N = { 'Nom d’icône manquant': {'en-us': 'Missing icon name', 'en-gb': 'Missing icon name'}, 'Profil connecté': {'en-us': 'Profile connected', 'en-gb': 'Profile connected'}, 'Profil déconnecté': {'en-us': 'Profile disconnected', 'en-gb': 'Profile disconnected'}, + 'Clé d’API créée avec succès': {'en-us': 'API key created successfully', 'en-gb': 'API key created successfully'}, + 'Clé d’API activée avec succès': {'en-us': 'API key enabled successfully', 'en-gb': 'API key enabled successfully'}, + 'Clé d’API désactivée avec succès': {'en-us': 'API key disabled successfully', 'en-gb': 'API key disabled successfully'}, + 'Clé d’API supprimée avec succès': {'en-us': 'API key deleted successfully', 'en-gb': 'API key deleted successfully'}, + 'Le nom de la clé API est obligatoire': {'en-us': 'API key name is required', 'en-gb': 'API key name is required'}, + 'Au moins une autorisation doit être sélectionnée': {'en-us': 'At least one permission must be selected', 'en-gb': 'At least one permission must be selected'}, + 'Clé API introuvable': {'en-us': 'API key not found', 'en-gb': 'API key not found'}, + 'Droits administrateur requis': {'en-us': 'Administrator privileges required', 'en-gb': 'Administrator privileges required'}, 'Authentification requise': {'en-us': 'Authentication required', 'en-gb': 'Authentication required'}, 'Nom d’utilisateur ou mot de passe incorrect': {'en-us': 'Incorrect username or password', 'en-gb': 'Incorrect username or password'}, @@ -11250,6 +11465,38 @@ class Handler(BaseHTTPRequestHandler): never_label = 'Never' if is_en else 'Jamais' items = [{'id': r[0], 'name': r[1], 'device_type': r[2], 'sign_count': r[3], 'created_at': r[4], 'last_used_at': r[5] or never_label} for r in rows] self.send_json({'ok': True, 'passkeys': items}); return + if self.path == '/api/auth/api-keys': + if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return + token = extract_token(self) + if token.startswith('ap_key_'): + k = get_api_key_by_token(token) + if not k or 'admin' not in k.get('permissions', []): + self.send_json({'error': 'Droits administrateur requis'}, 403); return + try: + c = db() + rows = c.execute(''' + SELECT id, name, prefix, permissions, created_at, expires_at, last_used_at, last_ip, is_active + FROM api_keys + ORDER BY id DESC + ''').fetchall() + c.close() + keys_list = [] + for r in rows: + keys_list.append({ + 'id': r[0], + 'name': r[1], + 'prefix': r[2], + 'permissions': parse_api_key_permissions(r[3]), + 'created_at': r[4], + 'expires_at': r[5] or None, + 'last_used_at': r[6] or None, + 'last_ip': r[7] or '—', + 'is_active': int(r[8] or 0) + }) + self.send_json({'ok': True, 'api_keys': keys_list}) + except Exception as e: + self.send_json({'error': f'Erreur chargement clés API: {e}'}, 500) + return if self.path == '/api/settings/proxy': if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return cfg = get_reverse_proxy_config() @@ -11702,6 +11949,100 @@ class Handler(BaseHTTPRequestHandler): log('modification_identifiants', f"Renommage machine -> {new_name}", request_ip(self), 'AUTH') self.send_json({'ok': True, 'message': 'Machine renommée avec succès', 'name': new_name}) return + if self.path == '/api/auth/api-keys/create': + if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return + token = extract_token(self) + if token.startswith('ap_key_'): + k = get_api_key_by_token(token) + if not k or 'admin' not in k.get('permissions', []): + self.send_json({'error': 'Droits administrateur requis'}, 403); return + name = str(data.get('name', '')).strip() + if not name: + self.send_json({'error': 'Le nom de la clé API est obligatoire'}, 400); return + perms = parse_api_key_permissions(data.get('permissions', [])) + if not perms: + self.send_json({'error': 'Au moins une autorisation doit être sélectionnée'}, 400); return + expires_in_days = int(data.get('expires_in_days', 0) or 0) + expires_at = None + if expires_in_days > 0: + expires_at = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time() + expires_in_days * 86400)) + + raw_token = f"ap_key_{secrets.token_hex(20)}" + token_hash = hashlib.sha256(raw_token.encode('utf-8')).hexdigest() + prefix = f"ap_key_{raw_token[7:13]}...{raw_token[-4:]}" + now_str = time.strftime('%Y-%m-%d %H:%M:%S') + + c = db() + c.execute(''' + INSERT INTO api_keys(name, key_hash, prefix, permissions, created_at, expires_at, is_active) + VALUES(?, ?, ?, ?, ?, ?, 1) + ''', (name, token_hash, prefix, json.dumps(perms), now_str, expires_at)) + new_id = c.execute('SELECT last_insert_rowid()').fetchone()[0] + c.commit(); c.close() + + with _api_keys_cache_lock: + _api_keys_cache.clear() + + log('cle_api_creee', f"{username(self) or 'admin'} ({name})", request_ip(self), 'SETTINGS') + + self.send_json({ + 'ok': True, + 'message': 'Clé d’API créée avec succès', + 'api_key': { + 'id': new_id, + 'name': name, + 'prefix': prefix, + 'token': raw_token, + 'permissions': perms, + 'created_at': now_str, + 'expires_at': expires_at, + 'is_active': 1 + } + }) + return + if self.path == '/api/auth/api-keys/toggle': + if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return + token = extract_token(self) + if token.startswith('ap_key_'): + k = get_api_key_by_token(token) + if not k or 'admin' not in k.get('permissions', []): + self.send_json({'error': 'Droits administrateur requis'}, 403); return + kid = int(data.get('id', 0)) + c = db() + row = c.execute('SELECT name, is_active FROM api_keys WHERE id=?', (kid,)).fetchone() + if not row: + c.close() + self.send_json({'error': 'Clé API introuvable'}, 404); return + new_state = 0 if row[1] else 1 + c.execute('UPDATE api_keys SET is_active=? WHERE id=?', (new_state, kid)) + c.commit(); c.close() + with _api_keys_cache_lock: + _api_keys_cache.clear() + status_txt = 'activée' if new_state else 'désactivée' + log('cle_api_modifiee', f"{username(self) or 'admin'} ({row[0]} -> {status_txt})", request_ip(self), 'SETTINGS') + self.send_json({'ok': True, 'is_active': new_state, 'message': f'Clé d’API {status_txt} avec succès'}) + return + if self.path == '/api/auth/api-keys/delete': + if not valid_session(self): self.send_json({'error':'Authentification requise'},401); return + token = extract_token(self) + if token.startswith('ap_key_'): + k = get_api_key_by_token(token) + if not k or 'admin' not in k.get('permissions', []): + self.send_json({'error': 'Droits administrateur requis'}, 403); return + kid = int(data.get('id', 0)) + c = db() + row = c.execute('SELECT name FROM api_keys WHERE id=?', (kid,)).fetchone() + if not row: + c.close() + self.send_json({'error': 'Clé API introuvable'}, 404); return + key_name = row[0] + c.execute('DELETE FROM api_keys WHERE id=?', (kid,)) + c.commit(); c.close() + with _api_keys_cache_lock: + _api_keys_cache.clear() + log('cle_api_supprimee', f"{username(self) or 'admin'} ({key_name})", request_ip(self), 'SETTINGS') + self.send_json({'ok': True, 'message': 'Clé d’API supprimée avec succès'}) + return if self.path == '/api/system/update/settings': if not valid_session(self) and auth_state()['configured']: self.send_json({'error':'Authentification requise'},401); return enabled = bool(data.get('enabled', True)) @@ -11741,7 +12082,7 @@ class Handler(BaseHTTPRequestHandler): if not target_commit: raise ValueError('Impossible de déterminer le dernier commit') v_data = { - 'version': 'V5.5', + 'version': APP_VERSION, 'commit': target_commit, 'build_date': datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') } @@ -12164,8 +12505,10 @@ class Handler(BaseHTTPRequestHandler): c.execute('DROP TABLE IF EXISTS recovery_codes') c.execute('DELETE FROM preferences') c.execute('DELETE FROM auth_sessions') + c.execute('DELETE FROM api_keys') c.commit(); c.close() sessions.clear() + with _api_keys_cache_lock: _api_keys_cache.clear() invalidate_status_cache() try: sync_vpn_client_rules() except Exception: pass diff --git a/index.html b/index.html index c539149..4e034d1 100644 --- a/index.html +++ b/index.html @@ -2376,7 +2376,7 @@ Administration de l’AP Wi‑Fi
AP Manageur V5.5 + 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)
@@ -2571,7 +2571,7 @@

Administration de l’AP Wi‑Fi

AP Manageur V5.5 + 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)
@@ -3547,6 +3547,43 @@
+ +
+
+
+

⚡ Clés d’API & Accès programmatique

+

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.

+
+ +
+ +
+ + + + + + + + + + + + + + + + + + +
NOM DE LA CLÉCLÉAUTORISATIONSDATE DE CRÉATIONEXPIRATIONDERNIÈRE UTILISATIONSTATUTACTION
Chargement des clés d’API…
+
+ +
@@ -5540,7 +5577,7 @@
Version actuelle
—
-
AP Manageur V5.5
+
AP Manageur V1.1 (Béta)
Dernière version (Gitea)
@@ -6842,7 +6879,7 @@
fichier.json - V5.5 + V1.1 (Béta)
Date de création : —
@@ -6951,6 +6988,130 @@
+ + + + + +