Merge remote-tracking branch 'origin/main' into claude/fonctionnalites-frontend

This commit is contained in:
Claude committed 2026-08-28 06:50:43 +00:00
commit 0541e1b0e3
8 files changed
+236 -36

No files matched your search

+11 -2
View File
@@ -3,6 +3,7 @@ import 'package:shelf/shelf.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import '../models/playlist_config.dart'; import '../models/playlist_config.dart';
import '../services/xmltv_epg_service.dart'; import '../services/xmltv_epg_service.dart';
import '../utils/log_redactor.dart';
/// API EPG — proxy vers Xtream avec cache 30 minutes /// API EPG — proxy vers Xtream avec cache 30 minutes
/// GET /api/epg/<channel_id>?days=1 /// GET /api/epg/<channel_id>?days=1
@@ -112,8 +113,11 @@ class EpgApi {
}, },
); );
} catch (e) { } catch (e) {
// Détail redacté en log uniquement : une ClientException Dart contient
// l'URI amont, credentials Xtream inclus.
print('[EpgApi] Erreur EPG: ${LogRedactor.redactUrl('$e')}');
return Response.internalServerError( return Response.internalServerError(
body: json.encode({'error': 'Erreur lors de la récupération EPG: $e'}), body: json.encode({'error': 'Erreur lors de la récupération EPG'}),
headers: {'Content-Type': 'application/json'}, headers: {'Content-Type': 'application/json'},
); );
} }
@@ -258,7 +262,12 @@ class EpgApi {
return {'channel_id': channelId, 'programmes': programmes}; return {'channel_id': channelId, 'programmes': programmes};
} catch (e) { } catch (e) {
return {'channel_id': channelId, 'programmes': [], 'error': e.toString()}; print('[EpgApi] Erreur panneau pour $channelId: ${LogRedactor.redactUrl('$e')}');
return {
'channel_id': channelId,
'programmes': [],
'error': 'EPG indisponible',
};
} }
} }
+74 -15
View File
@@ -3,6 +3,8 @@ import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'package:shelf/shelf.dart'; import 'package:shelf/shelf.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import '../database/database.dart';
import '../middleware/auth_middleware.dart';
import '../models/playlist_config.dart'; import '../models/playlist_config.dart';
import '../utils/log_redactor.dart'; import '../utils/log_redactor.dart';
@@ -31,6 +33,7 @@ bool isForbiddenProxyHost(String host) {
/// Handler for the Xtream Proxy /// Handler for the Xtream Proxy
class ProxyHandler { class ProxyHandler {
final Future<PlaylistConfig?> Function(Request) _getPlaylist; final Future<PlaylistConfig?> Function(Request) _getPlaylist;
final AppDatabase _db;
final http.Client _client = http.Client(); final http.Client _client = http.Client();
final Map<String, (PlaylistConfig, DateTime)> _playlistCache = {}; final Map<String, (PlaylistConfig, DateTime)> _playlistCache = {};
@@ -70,7 +73,7 @@ class ProxyHandler {
return playlist; return playlist;
} }
ProxyHandler(this._getPlaylist); ProxyHandler(this._getPlaylist, this._db);
/// Create Xtream proxy handler with M3U8 URL rewriting support /// Create Xtream proxy handler with M3U8 URL rewriting support
Handler get handler { Handler get handler {
@@ -84,8 +87,16 @@ class ProxyHandler {
return Response.notFound(null); return Response.notFound(null);
} }
// NOTE: Authentication REMOVED from proxy to allow browser-initiated requests (img src, etc.) // Authentification par session. Les requêtes initiées par le navigateur
// SSRF protection is still active via domain validation below. // (img src, hls.js) ne portent pas d'en-tête Authorization mais envoient
// le cookie HttpOnly `session` (SameSite=Lax, même origine) posé au
// login : extractAuthToken accepte les deux. Un proxy ouvert offrait un
// rebond SSRF non authentifié vers n'importe quel hôte public via les
// extensions d'image.
final token = extractAuthToken(request);
if (token == null || _db.findSessionByToken(token) == null) {
return Response(401, body: 'Unauthorized');
}
Uri? targetUrl; Uri? targetUrl;
@@ -139,6 +150,7 @@ class ProxyHandler {
targetUrl.path.contains('/picons/') || targetUrl.path.contains('/picons/') ||
targetUrl.path.contains('/logos/'); targetUrl.path.contains('/logos/');
String? allowedHost;
if (!isStaticAsset) { if (!isStaticAsset) {
// For API calls, enforce domain allowlist // For API calls, enforce domain allowlist
final playlist = await _getCachedPlaylist(request); final playlist = await _getCachedPlaylist(request);
@@ -149,7 +161,7 @@ class ProxyHandler {
} }
final targetHost = targetUrl.host.toLowerCase(); final targetHost = targetUrl.host.toLowerCase();
final allowedHost = Uri.parse(playlist.dns).host.toLowerCase(); allowedHost = Uri.parse(playlist.dns).host.toLowerCase();
if (targetHost != allowedHost) { if (targetHost != allowedHost) {
print( print(
@@ -175,7 +187,6 @@ class ProxyHandler {
try { try {
print('[Proxy] Forwarding to: ${LogRedactor.redactUrl(targetUrl.toString())}'); print('[Proxy] Forwarding to: ${LogRedactor.redactUrl(targetUrl.toString())}');
final proxyRequest = http.Request(request.method, targetUrl);
// Forward safe request headers // Forward safe request headers
for (final header in _allowedRequestHeaders) { for (final header in _allowedRequestHeaders) {
@@ -184,18 +195,61 @@ class ProxyHandler {
} }
} }
proxyRequest.headers.addAll(proxyHeaders); List<int>? postBody;
proxyRequest.followRedirects = true;
if (request.method == 'POST') { if (request.method == 'POST') {
final bodyBytes = await request.read().toList(); final bodyBytes = await request.read().toList();
proxyRequest.bodyBytes = bodyBytes.expand((i) => i).toList(); postBody = bodyBytes.expand((i) => i).toList();
} }
// Added 90s timeout to allow frontend (60s) to time out gracefully first // Redirections suivies MANUELLEMENT : chaque destination est
final response = await _client // revalidée (hôte privé, allowlist de domaine). Avec
.send(proxyRequest) // followRedirects, la validation ne portait que sur l'URL
.timeout(const Duration(seconds: 90)); // initiale — une 302 du serveur amont suffisait pour atteindre
// un hôte interne malgré l'anti-SSRF.
http.StreamedResponse response;
var currentUrl = targetUrl;
var redirects = 0;
while (true) {
final proxyRequest = http.Request(request.method, currentUrl);
proxyRequest.headers.addAll(proxyHeaders);
proxyRequest.followRedirects = false;
if (postBody != null) proxyRequest.bodyBytes = postBody;
// Added 90s timeout to allow frontend (60s) to time out gracefully first
response = await _client
.send(proxyRequest)
.timeout(const Duration(seconds: 90));
final location = response.headers['location'];
final isRedirect = response.statusCode >= 300 &&
response.statusCode < 400 &&
location != null;
if (!isRedirect) break;
if (++redirects > 3) {
return Response.forbidden('Too many redirects');
}
final next = Uri.parse(location);
currentUrl = next.isAbsolute ? next : currentUrl.resolve(location);
if (currentUrl.scheme != 'http' && currentUrl.scheme != 'https') {
return Response.forbidden('Unsupported redirect scheme');
}
if (isForbiddenProxyHost(currentUrl.host)) {
print(
'[Proxy] Blocked SSRF redirect to private host: ${currentUrl.host}',
);
return Response.forbidden('Access to this host is forbidden');
}
if (allowedHost != null &&
currentUrl.host.toLowerCase() != allowedHost) {
print(
'[Proxy] Blocked redirect to ${currentUrl.host} (Allowed: $allowedHost)',
);
return Response.forbidden(
'Access to this domain is forbidden by policy',
);
}
}
// Build response headers from source response // Build response headers from source response
final responseHeaders = <String, String>{ final responseHeaders = <String, String>{
@@ -221,7 +275,12 @@ class ProxyHandler {
rethrow; rethrow;
} }
} catch (e) { } catch (e) {
print('[ProxyHandler] error on $path: $e'); // Redaction : une ClientException porte l'URL amont, credentials
// Xtream inclus. Jamais de détail d'exception vers le client.
print(
'[ProxyHandler] error on ${LogRedactor.redactUrl(path)}: '
'${LogRedactor.redactUrl('$e')}',
);
// Return transparent 1x1 pixel image fallback for images // Return transparent 1x1 pixel image fallback for images
if (targetUrl?.path.endsWith('.png') == true || if (targetUrl?.path.endsWith('.png') == true ||
@@ -235,7 +294,7 @@ class ProxyHandler {
} }
return Response.internalServerError( return Response.internalServerError(
body: jsonEncode({'error': 'Proxy error', 'message': e.toString()}), body: jsonEncode({'error': 'Proxy error'}),
headers: {'content-type': 'application/json'}, headers: {'content-type': 'application/json'},
); );
} }
+14
View File
@@ -65,6 +65,13 @@ class UsersHandler {
}), headers: {'Content-Type': 'application/json'},); }), headers: {'Content-Type': 'application/json'},);
} }
if (password.length < 8) {
return Response.badRequest(body: jsonEncode({
'success': false,
'error': 'Le mot de passe doit faire au moins 8 caractères',
}), headers: {'Content-Type': 'application/json'},);
}
if (db.findUserByUsername(username) != null) { if (db.findUserByUsername(username) != null) {
return Response.badRequest(body: jsonEncode({ return Response.badRequest(body: jsonEncode({
'success': false, 'success': false,
@@ -103,6 +110,13 @@ class UsersHandler {
}), headers: {'Content-Type': 'application/json'},); }), headers: {'Content-Type': 'application/json'},);
} }
if (password.length < 8) {
return Response.badRequest(body: jsonEncode({
'success': false,
'error': 'Le mot de passe doit faire au moins 8 caractères',
}), headers: {'Content-Type': 'application/json'},);
}
db.updateUserPassword(id, password); db.updateUserPassword(id, password);
return Response.ok(jsonEncode({'success': true}), headers: {'Content-Type': 'application/json'}); return Response.ok(jsonEncode({'success': true}), headers: {'Content-Type': 'application/json'});
+35 -3
View File
@@ -1,4 +1,5 @@
import 'dart:io'; import 'dart:io';
import 'dart:math';
import 'package:sqlite3/sqlite3.dart'; import 'package:sqlite3/sqlite3.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
import '../models/user.dart'; import '../models/user.dart';
@@ -195,14 +196,21 @@ class AppDatabase {
); );
} }
/// Seed default admin user if no users exist /// Seed default admin user if no users exist.
///
/// Le mot de passe initial vient de ADMIN_INITIAL_PASSWORD, ou est généré
/// aléatoirement et affiché UNE FOIS dans les logs de démarrage. L'ancien
/// couple admin/admin restait souvent en place sur les instances exposées.
Future<void> seedAdmin() async { Future<void> seedAdmin() async {
final result = _db.select('SELECT COUNT(*) as count FROM users'); final result = _db.select('SELECT COUNT(*) as count FROM users');
final count = result.first['count'] as int; final count = result.first['count'] as int;
if (count == 0) { if (count == 0) {
final adminId = _uuid.v4(); final adminId = _uuid.v4();
final passwordHash = PasswordHasher.hash('admin'); final envPassword = Platform.environment['ADMIN_INITIAL_PASSWORD'];
final generated = envPassword == null || envPassword.isEmpty;
final password = generated ? _generatePassword() : envPassword;
final passwordHash = PasswordHasher.hash(password);
_db.execute( _db.execute(
''' '''
@@ -212,10 +220,34 @@ class AppDatabase {
[adminId, 'admin', passwordHash], [adminId, 'admin', passwordHash],
); );
print('Default admin user created (username: admin, password: admin)'); if (generated) {
print('╔══════════════════════════════════════════════════════════╗');
print(' Compte admin créé — mot de passe initial (affiché une');
print(' seule fois, changez-le après la première connexion) :');
print(' utilisateur: admin');
print(' mot de passe: $password');
print('╚══════════════════════════════════════════════════════════╝');
} else {
print(
'Default admin user created (username: admin, '
'password: ADMIN_INITIAL_PASSWORD)',
);
}
} }
} }
static String _generatePassword({int length = 16}) {
// Sans caractères ambigus (0/O, 1/l/I) : le mot de passe est recopié
// depuis les logs du conteneur.
const chars =
'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
final random = Random.secure();
return List.generate(
length,
(_) => chars[random.nextInt(chars.length)],
).join();
}
// ==================== Users ==================== // ==================== Users ====================
/// Find user by username /// Find user by username
+6 -1
View File
@@ -77,7 +77,12 @@ Middleware streamAuthMiddleware(AppDatabase db) {
}; };
} }
/// Extract token from Authorization header or cookie /// Extract token from Authorization header or cookie.
/// Public : le proxy /api/xtream fait sa propre vérification de session
/// (le contrôle doit rester DANS le handler, après le test de chemin,
/// pour que les requêtes non-proxy tombent sur le handler statique).
String? extractAuthToken(Request request) => _extractToken(request);
String? _extractToken(Request request) { String? _extractToken(Request request) {
// Try Authorization header first // Try Authorization header first
final authHeader = request.headers['authorization']; final authHeader = request.headers['authorization'];
+82 -11
View File
@@ -1,26 +1,94 @@
import 'package:shelf/shelf.dart'; import 'package:shelf/shelf.dart';
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io';
import '../utils/log_redactor.dart';
/// Security Middleware Collection /// Security Middleware Collection
/// ///
/// Includes: /// Includes:
/// - Redacted request logging
/// - Honeypot Routes (Trap for bots) /// - Honeypot Routes (Trap for bots)
/// - Security Headers (HSTS, XSS Protection, CSP Report-Only) /// - Security Headers (HSTS, XSS Protection, CSP Report-Only)
/// - Rate Limiting (Basic DoS protection) /// - Rate Limiting (Basic DoS protection)
/// - Login-specific rate limiting (brute-force protection) /// - Login-specific rate limiting (brute-force protection)
/// Resolve the real client IP. /// Proxys de confiance dont l'en-tête X-Forwarded-For est honoré.
/// Honors the first hop of X-Forwarded-For when behind nginx, otherwise /// Par défaut : loopback et plages privées RFC1918 (le reverse proxy du
/// falls back to the socket connection info. /// docker-compose parle depuis le réseau Docker). Surcharger avec
String clientIpOf(Request request) { /// TRUSTED_PROXIES (liste d'IP séparées par des virgules) pour restreindre.
final forwarded = request.headers['x-forwarded-for']; final List<String> _trustedProxies =
if (forwarded != null && forwarded.isNotEmpty) { (Platform.environment['TRUSTED_PROXIES'] ?? '')
return forwarded.split(',').first.trim(); .split(',')
.map((s) => s.trim())
.where((s) => s.isNotEmpty)
.toList();
bool _isTrustedProxy(String address) {
if (_trustedProxies.isNotEmpty) return _trustedProxies.contains(address);
final ip = InternetAddress.tryParse(address);
if (ip == null) return false;
if (ip.isLoopback) return true;
if (ip.type == InternetAddressType.IPv4) {
final parts = ip.address.split('.').map(int.parse).toList();
if (parts[0] == 10) return true;
if (parts[0] == 172 && parts[1] >= 16 && parts[1] <= 31) return true;
if (parts[0] == 192 && parts[1] == 168) return true;
} }
return false;
}
/// Resolve the real client IP.
///
/// X-Forwarded-For n'est honoré que si la connexion socket provient d'un
/// proxy de confiance : sinon un client direct peut forger l'en-tête et
/// contourner le rate limit global comme la limite de tentatives de login.
String clientIpOf(Request request) {
final connectionInfo = final connectionInfo =
request.context['shelf.io.connection_info'] as HttpConnectionInfo?; request.context['shelf.io.connection_info'] as HttpConnectionInfo?;
return connectionInfo?.remoteAddress.address ?? 'unknown'; final socketAddress = connectionInfo?.remoteAddress.address;
final forwarded = request.headers['x-forwarded-for'];
if (forwarded != null &&
forwarded.isNotEmpty &&
socketAddress != null &&
_isTrustedProxy(socketAddress)) {
return forwarded.split(',').first.trim();
}
return socketAddress ?? 'unknown';
}
/// 0. Redacted request logging.
///
/// Remplace `logRequests()` de shelf : le chemin `/api/xtream/<url>` embarque
/// `username`/`password` Xtream en clair dans l'URI, que le logger standard
/// écrivait tels quels — annulant l'effort de LogRedactor partout ailleurs.
Middleware redactedLogRequests() {
return (Handler handler) {
return (Request request) async {
final watch = Stopwatch()..start();
try {
final response = await handler(request);
watch.stop();
final query =
request.requestedUri.hasQuery ? '?${request.requestedUri.query}' : '';
print(
'${DateTime.now().toIso8601String()} ${response.statusCode} '
'${request.method} '
'${LogRedactor.redactUrl('${request.requestedUri.path}$query')} '
'(${watch.elapsedMilliseconds}ms)',
);
return response;
} catch (e) {
watch.stop();
print(
'${DateTime.now().toIso8601String()} ERR ${request.method} '
'${LogRedactor.redactUrl(request.requestedUri.path)}: '
'${LogRedactor.redactUrl('$e')}',
);
rethrow;
}
};
};
} }
/// 1. Security Headers Middleware /// 1. Security Headers Middleware
@@ -71,11 +139,14 @@ Middleware honeypotMiddleware() {
return (Handler handler) { return (Handler handler) {
return (Request request) { return (Request request) {
final path = request.url.path; // Comparaison sur le chemin exact ou un préfixe de segment. L'ancienne
// comparaison `contains(trap.replaceAll('/', ''))` bloquait toute URL
// contenant « console », « env » ou « wpadmin » n'importe où — y
// compris des URLs proxifiées parfaitement légitimes.
final path = '/${request.url.path}';
// Check if path contains any honeypot target
for (final trap in honeypotPaths) { for (final trap in honeypotPaths) {
if (path.contains(trap.replaceAll('/', ''))) { // Simple check if (path == trap || path.startsWith('$trap/')) {
print('SECURITY ALERT: Honeypot triggered by ${clientIpOf(request)} on path: $path'); print('SECURITY ALERT: Honeypot triggered by ${clientIpOf(request)} on path: $path');
return Response.forbidden('Access Denied'); return Response.forbidden('Access Denied');
} }
+7 -3
View File
@@ -120,7 +120,7 @@ void main(List<String> args) async {
final playlistsHandler = PlaylistsHandler(db); final playlistsHandler = PlaylistsHandler(db);
final usersHandler = UsersHandler(db); final usersHandler = UsersHandler(db);
final settingsHandler = SettingsHandler(db); final settingsHandler = SettingsHandler(db);
final proxyHandler = ProxyHandler(getPlaylist); final proxyHandler = ProxyHandler(getPlaylist, db);
final recordingsApi = RecordingsApi(db, recordingScheduler); final recordingsApi = RecordingsApi(db, recordingScheduler);
// Source XMLTV de repli. Vider EPG_XMLTV_URLS désactive tout appel sortant : // Source XMLTV de repli. Vider EPG_XMLTV_URLS désactive tout appel sortant :
// l'EPG se limite alors au panneau de l'abonné. // l'EPG se limite alors au panneau de l'abonné.
@@ -222,8 +222,10 @@ void main(List<String> args) async {
// Do NOT mount here as it would intercept and block the actual proxy // Do NOT mount here as it would intercept and block the actual proxy
// Initialize Cleanup Service // Initialize Cleanup Service
// Ne JAMAIS cibler Directory.systemTemp en récursif : il contient les
// temporaires de la VM Dart et le dossier des sessions HLS — les fichiers
// de plus de 24 h y étaient supprimés aveuglément.
final cleanupService = CleanupService(); final cleanupService = CleanupService();
cleanupService.addTarget(Directory.systemTemp);
cleanupService.addTarget(Directory('/app/data/logs')); cleanupService.addTarget(Directory('/app/data/logs'));
cleanupService.addTarget(Directory('/app/data/tmp')); cleanupService.addTarget(Directory('/app/data/tmp'));
@@ -338,8 +340,10 @@ void main(List<String> args) async {
.handler; .handler;
// Add middleware // Add middleware
// redactedLogRequests remplace logRequests() : l'URI de /api/xtream/<url>
// contient username/password Xtream en clair.
final pipeline = const Pipeline() final pipeline = const Pipeline()
.addMiddleware(logRequests()) .addMiddleware(redactedLogRequests())
.addMiddleware(securityHeadersMiddleware()) .addMiddleware(securityHeadersMiddleware())
.addMiddleware(honeypotMiddleware()) .addMiddleware(honeypotMiddleware())
.addMiddleware(rateLimitMiddleware()) .addMiddleware(rateLimitMiddleware())
+7 -1
View File
@@ -131,7 +131,10 @@
}; };
XFPlayer.prototype.send = function (msg) { XFPlayer.prototype.send = function (msg) {
try { global.parent.postMessage(msg, '*'); } catch (e) {} // Cible restreinte à notre origine : l'iframe est toujours même-origine
// que le parent Flutter, un wildcard '*' livrerait l'état du player à
// n'importe quelle page qui embarquerait player.html.
try { global.parent.postMessage(msg, global.location.origin); } catch (e) {}
}; };
// ---------------- Démarrage ---------------- // ---------------- Démarrage ----------------
@@ -491,6 +494,9 @@
XFPlayer.prototype._wireParentMessages = function () { XFPlayer.prototype._wireParentMessages = function () {
var self = this; var self = this;
global.addEventListener('message', function (event) { global.addEventListener('message', function (event) {
// N'accepter que les commandes émises par notre propre origine
// (le côté Flutter filtre déjà les messages entrants de la même façon).
if (event.origin !== global.location.origin) return;
var d = event.data; var d = event.data;
if (!d || !d.type) return; if (!d || !d.type) return;
var v = self.video; var v = self.video;