feat: security hardening, streaming overhaul, design polish, tests

Security:
- Replace unsalted SHA-256 password hashing with bcrypt (lazy rehash on login)
- Add authenticated /api/xtream-api gateway: Xtream credentials are injected
  server-side and never sent to the frontend; /api/playlists no longer
  returns passwords
- Redact credentials from all logs (login body, proxy/FFmpeg/scheduler URLs)
- Add auth to recordings, EPG, season-passes and streaming routes
  (HttpOnly session cookie for hls.js; loopback bypass for local FFmpeg)
- Lock player postMessage to same-origin in both directions
- Vendor and pin hls.js 1.6.7 / mpegts.js 1.7.3 (drop CDN @latest)
- Fix rate limiter (client IP was never resolved), add login rate limit,
  restrict CORS, add CSP Report-Only, block private-IP SSRF targets,
  fix path traversal in recording log retrieval, chmod 777 -> 770
- Remove dead HiveService (seeded admin/admin into IndexedDB with SHA-256)
- Fix authMiddleware not populating 'user' context (getPlaylist ignored the
  logged-in user; admin purge always returned 403)

Streaming:
- New FfmpegSessionManager: process registry, idle reaper (4 min live /
  15 min VOD), orphan cleanup at startup, clean SIGTERM shutdown,
  fast-fail with stderr instead of 30 s timeout
- Quality selection (source/high/medium/low) for live and VOD; source mode
  streams with -c:v copy (zero transcoding); selector wired into the player
- Concurrent recordings (MAX_CONCURRENT_RECORDINGS, default 2); conflicts
  retry on the next tick instead of silently failing
- Lower live latency (HLS window 20 -> 10 segments, liveSync 10 -> 3)
- Fix recording log lookup (.mp4 vs .mkv mismatch)

Design:
- Replace hardcoded colors with AppColors tokens (12 files)
- web/theme.css syncs HTML players with the Flutter palette
- DPAD/keyboard navigation (arrow-key focus, player shortcuts)
- Tooltips on player icon buttons, Semantics on content cards
- Remove 7 dead widgets broken since the Stitch merge

Quality:
- bin/test/: 21 unit tests (bcrypt, redaction, traversal, SSRF, recording
  conflicts) plus a quality-selector widget test
- GitHub Actions CI (analyze + test + build web)
- Archive stale status docs into docs/archive/

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
MichaelandClaude Fable 5 committed 2026-06-10 10:07:18 +02:00
1 parent cb5eca7547
commit 60d3f42901
107 files changed
+4525 -3815

No files matched your search

+13 -5
View File
@@ -23,8 +23,7 @@ class AuthHandler {
try {
print('[Auth] Login attempt received');
final bodyStr = await request.readAsString();
print('[Auth] Request body: $bodyStr');
final payload = jsonDecode(bodyStr) as Map<String, dynamic>;
final username = payload['username'] as String?;
final password = payload['password'] as String?;
@@ -51,13 +50,19 @@ class AuthHandler {
print('[Auth] User verified, creating session for userId: ${user.id}');
// Create session
final session = db.createSession(user.id);
print('[Auth] Session created with token: ${session.token.substring(0, 8)}...');
// HttpOnly session cookie so same-origin media requests (hls.js inside
// the player iframe cannot send Authorization headers) are authenticated.
final maxAge = session.expiresAt.difference(DateTime.now()).inSeconds;
return Response.ok(jsonEncode({
'success': true,
'user': user.toJson(),
'token': session.token,
}), headers: {'Content-Type': 'application/json'},);
}), headers: {
'Content-Type': 'application/json',
'Set-Cookie':
'session=${session.token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=$maxAge',
},);
} catch (e, stackTrace) {
print('[Auth] ERROR during login: $e');
print('[Auth] Stack trace: $stackTrace');
@@ -83,7 +88,10 @@ class AuthHandler {
return Response.ok(jsonEncode({
'success': true,
}), headers: {'Content-Type': 'application/json'},);
}), headers: {
'Content-Type': 'application/json',
'Set-Cookie': 'session=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0',
},);
} catch (e) {
return Response.internalServerError(
body: jsonEncode({'success': false, 'error': e.toString()}),
+1 -3
View File
@@ -1,19 +1,17 @@
import 'dart:convert';
import 'package:shelf/shelf.dart';
import 'package:http/http.dart' as http;
import '../database/database.dart';
import '../models/playlist_config.dart';
/// API EPG — proxy vers Xtream avec cache 30 minutes
/// GET /api/epg/<channel_id>?days=1
class EpgApi {
final AppDatabase _db;
final Future<PlaylistConfig?> Function(Request) _getPlaylist;
// Cache simple en mémoire : channelId → {data, expiresAt}
final Map<String, _CacheEntry> _cache = {};
EpgApi(this._db, this._getPlaylist);
EpgApi(this._getPlaylist);
Future<Response> handleGetEpg(Request request, String channelId) async {
// Vérifier le cache
+6 -1
View File
@@ -120,7 +120,12 @@ class PlaylistsHandler {
final name = payload['name'] as String? ?? existing.name;
final serverUrl = payload['serverUrl'] as String? ?? existing.serverUrl;
final username = payload['username'] as String? ?? existing.username;
final password = payload['password'] as String? ?? existing.password;
// Empty password means "keep current": clients never receive the real
// password, so edit forms send it back blank.
final incomingPassword = payload['password'] as String?;
final password = (incomingPassword == null || incomingPassword.isEmpty)
? existing.password
: incomingPassword;
final dns = payload['dns'] as String? ?? existing.dns;
final playlist = db.updatePlaylist(
+37 -27
View File
@@ -1,14 +1,36 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:http/http.dart' as http;
import '../models/playlist_config.dart';
import '../database/database.dart';
import '../utils/log_redactor.dart';
/// Returns true when [host] must never be proxied (loopback, private LAN,
/// link-local/cloud-metadata ranges) — SSRF protection for asset URLs that
/// bypass the playlist-domain allowlist.
bool isForbiddenProxyHost(String host) {
final lower = host.toLowerCase();
if (lower == 'localhost' || lower == '::1') return true;
final ip = InternetAddress.tryParse(lower);
if (ip == null) return false; // Hostname: validated by domain allowlist path
if (ip.isLoopback || ip.isLinkLocal) return true;
if (ip.type == InternetAddressType.IPv4) {
final parts = ip.address.split('.').map(int.parse).toList();
if (parts[0] == 10) return true; // 10.0.0.0/8
if (parts[0] == 172 && parts[1] >= 16 && parts[1] <= 31) return true;
if (parts[0] == 192 && parts[1] == 168) return true; // 192.168.0.0/16
if (parts[0] == 169 && parts[1] == 254) return true; // metadata/link-local
if (parts[0] == 0) return true;
}
return false;
}
/// Handler for the Xtream Proxy
class ProxyHandler {
final Future<PlaylistConfig?> Function(Request) _getPlaylist;
final AppDatabase _db;
final http.Client _client = http.Client();
final Map<String, (PlaylistConfig, DateTime)> _playlistCache = {};
@@ -48,30 +70,7 @@ class ProxyHandler {
return playlist;
}
ProxyHandler(this._getPlaylist, this._db);
/// Extract token from Authorization header or cookie
String? _extractToken(Request request) {
// Try Authorization header first
final authHeader = request.headers['authorization'];
if (authHeader != null && authHeader.startsWith('Bearer ')) {
return authHeader.substring(7);
}
// Try cookie
final cookie = request.headers['cookie'];
if (cookie != null) {
final parts = cookie.split(';');
for (final part in parts) {
final trimmed = part.trim();
if (trimmed.startsWith('session=')) {
return trimmed.substring(8);
}
}
}
return null;
}
ProxyHandler(this._getPlaylist);
/// Create Xtream proxy handler with M3U8 URL rewriting support
Handler get handler {
@@ -118,6 +117,17 @@ class ProxyHandler {
targetUrl = Uri.parse(fullUrl);
// Only plain http(s) may be proxied
if (targetUrl.scheme != 'http' && targetUrl.scheme != 'https') {
return Response.forbidden('Unsupported URL scheme');
}
// Never proxy to loopback/private/link-local targets (SSRF)
if (isForbiddenProxyHost(targetUrl.host)) {
print('[Proxy] Blocked SSRF attempt to private host: ${targetUrl.host}');
return Response.forbidden('Access to this host is forbidden');
}
// SSRF Protection - but allow images/static assets from any host
// Xtream providers often use separate CDN servers for picons/images
final isStaticAsset = targetUrl.path.endsWith('.png') ||
@@ -164,7 +174,7 @@ class ProxyHandler {
}
try {
print('[Proxy] Forwarding to: $targetUrl');
print('[Proxy] Forwarding to: ${LogRedactor.redactUrl(targetUrl.toString())}');
final proxyRequest = http.Request(request.method, targetUrl);
// Forward safe request headers
+26 -7
View File
@@ -1,9 +1,11 @@
import 'dart:io';
import 'dart:convert';
import 'package:path/path.dart' as p;
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
import '../database/database.dart';
import '../models/user.dart';
import '../services/recording_scheduler.dart';
import '../utils/safe_path.dart';
class RecordingsApi {
final AppDatabase _db;
@@ -30,12 +32,24 @@ class RecordingsApi {
);
}
final logFilePath = recording.filePath!.replaceAll('.mp4', '.log');
final logFile = File(logFilePath);
// Les enregistrements sont écrits en .mkv avec un .log à côté
// (l'ancien replaceAll('.mp4', '.log') ne trouvait jamais le fichier).
final logFilePath = p.setExtension(recording.filePath!, '.log');
// Anti path-traversal : le log doit rester dans /app/recordings
final safeLogPath = SafePath.resolveWithin('/app/recordings', logFilePath);
if (safeLogPath == null) {
return Response.forbidden(
json.encode({'error': 'Chemin de log invalide'}),
headers: {'Content-Type': 'application/json'},
);
}
final logFile = File(safeLogPath);
if (!await logFile.exists()) {
return Response.notFound(
json.encode({'error': 'Le fichier de log est introuvable. Chemin: $logFilePath'}),
json.encode({'error': 'Le fichier de log est introuvable.'}),
headers: {'Content-Type': 'application/json'},
);
}
@@ -47,9 +61,13 @@ class RecordingsApi {
);
}
/// GET /api/recordings — Liste tous les enregistrements
/// GET /api/recordings — Liste les enregistrements de l'utilisateur
/// (tous les enregistrements pour un admin)
Response handleGetAll(Request request) {
final recordings = _db.getAllRecordings();
final user = request.context['user'] as User?;
final recordings = (user != null && !user.isAdmin)
? _db.getUserRecordings(user.id)
: _db.getAllRecordings();
return Response.ok(
json.encode(recordings.map((r) => r.toMap()).toList()),
headers: {'Content-Type': 'application/json'},
@@ -62,8 +80,9 @@ class RecordingsApi {
final payload = await request.readAsString();
final data = json.decode(payload);
final userId = request.context['userId'] as String? ?? 'dev_user_id';
final recording = _db.createRecording(
userId: 'dev_user_id',
userId: userId,
channelId: data['channel_id'],
streamUrl: data['stream_url'],
title: data['title'] ?? 'Sans Titre',
+332 -506
View File
@@ -1,20 +1,19 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:http/http.dart' as http;
import '../database/database.dart';
import '../models/playlist_config.dart';
/// Active FFmpeg processes for VOD transcoding
final Map<String, Process> _vodProcesses = {};
import '../services/ffmpeg_session_manager.dart';
import '../utils/log_redactor.dart';
/// Directory for temporary HLS segments
final Directory _hlsTempDir =
Directory('${Directory.systemTemp.path}/xtremflow_streams');
/// Global FFmpeg session registry (initialized in [initStreaming]).
final FfmpegSessionManager sessionManager = FfmpegSessionManager(_hlsTempDir);
/// Helper to resolve FFmpeg path (SYSTEM PATH vs Portable)
String _getFFmpegPath() {
if (Platform.isWindows) {
@@ -35,91 +34,149 @@ bool _isNvidiaGpuEnabled() {
return envValue.toLowerCase() == 'true' || envValue == '1';
}
/// Log GPU status on first use
bool _gpuStatusLogged = false;
void _logGpuStatus() {
if (!_gpuStatusLogged) {
if (_isNvidiaGpuEnabled()) {
print('[FFmpeg] NVIDIA GPU acceleration ENABLED (NVDEC/NVENC)');
} else {
print(
'[FFmpeg] Using CPU processing (set NVIDIA_GPU=true to enable GPU)',
);
}
_gpuStatusLogged = true;
}
}
/// Initialize streaming subsystem
Future<void> initStreaming() async {
if (!_hlsTempDir.existsSync()) {
await _hlsTempDir.create(recursive: true);
await sessionManager.init();
}
/// Supported quality presets. `source` skips video transcoding entirely
/// (`-c:v copy`) — a huge CPU win since most Xtream streams are already
/// H.264. Audio is always normalized to AAC for HLS compatibility.
const supportedQualities = {'source', 'high', 'medium', 'low'};
String _sanitizeQuality(String? quality) {
return supportedQualities.contains(quality) ? quality! : 'high';
}
bool _isValidStreamId(String id) => RegExp(r'^[a-zA-Z0-9_-]+$').hasMatch(id);
/// Video encoding args for the requested quality (live profile).
List<String> _liveVideoArgs(String quality, bool gpu) {
switch (quality) {
case 'source':
return ['-c:v', 'copy'];
case 'medium':
return gpu
? [
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune', 'hq',
'-b:v', '3000k', '-maxrate', '4500k', '-bufsize', '6000k',
'-profile:v', 'high', '-level', '4.0', '-pix_fmt', 'yuv420p',
'-g', '50',
]
: [
'-c:v', 'libx264', '-preset', 'veryfast', '-tune', 'zerolatency',
'-profile:v', 'high', '-level', '4.0',
'-b:v', '3000k', '-maxrate', '4500k', '-bufsize', '6000k',
'-pix_fmt', 'yuv420p', '-g', '50',
];
case 'low':
return gpu
? [
'-c:v', 'h264_nvenc', '-preset', 'p4',
'-b:v', '1500k', '-maxrate', '2000k', '-bufsize', '3000k',
'-vf', 'scale=-2:720',
'-pix_fmt', 'yuv420p', '-g', '50',
]
: [
'-c:v', 'libx264', '-preset', 'veryfast', '-tune', 'zerolatency',
'-b:v', '1500k', '-maxrate', '2000k', '-bufsize', '3000k',
'-vf', 'scale=-2:720',
'-pix_fmt', 'yuv420p', '-g', '50',
];
case 'high':
default:
return gpu
? [
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune', 'hq',
'-b:v', '8000k', '-maxrate', '12000k', '-bufsize', '16000k',
'-profile:v', 'high', '-level', '4.0', '-pix_fmt', 'yuv420p',
'-g', '50',
]
: [
'-c:v', 'libx264', '-preset', 'medium', '-tune', 'zerolatency',
'-profile:v', 'high', '-level', '4.0',
'-b:v', '6000k', '-maxrate', '8000k', '-bufsize', '12000k',
'-pix_fmt', 'yuv420p', '-g', '50',
];
}
}
/// Helper to resolve HTTP redirects and get final URL
/// Some IPTV servers return 302 redirects that FFmpeg doesn't follow properly
Future<String> _resolveRedirects(String url, {int maxRedirects = 5}) async {
String currentUrl = url;
final client = http.Client();
try {
for (int i = 0; i < maxRedirects; i++) {
final request = http.Request('GET', Uri.parse(currentUrl));
request.headers['User-Agent'] = 'VLC/3.0.18 LibVLC/3.0.18';
request.followRedirects = false;
final response = await client.send(request).timeout(
const Duration(seconds: 30),
onTimeout: () =>
throw TimeoutException('Redirect resolution timeout'),
);
// Check if it's a redirect (301, 302, 307, 308)
if (response.statusCode >= 300 && response.statusCode < 400) {
final location = response.headers['location'];
if (location != null && location.isNotEmpty) {
// Handle relative URLs
if (location.startsWith('/')) {
final uri = Uri.parse(currentUrl);
currentUrl = '${uri.scheme}://${uri.host}:${uri.port}$location';
} else {
currentUrl = location;
}
print('[Redirect] $i: $url -> $currentUrl');
await response.stream.drain();
continue;
}
}
// Not a redirect - we're done
await response.stream.drain();
break;
}
} catch (e) {
print('[Redirect] Error resolving redirects: $e');
// Return original URL if redirect resolution fails
} finally {
client.close();
/// Video encoding args for the requested quality (VOD profile).
List<String> _vodVideoArgs(String quality, bool gpu) {
switch (quality) {
case 'source':
return ['-c:v', 'copy'];
case 'medium':
return gpu
? [
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune', 'hq',
'-rc', 'cbr', '-b:v', '2500k', '-maxrate', '3000k',
'-bufsize', '5000k', '-g', '48', '-bf', '2',
'-pix_fmt', 'yuv420p',
]
: [
'-c:v', 'libx264', '-preset', 'fast', '-crf', '23',
'-maxrate', '6000k', '-bufsize', '12000k',
'-pix_fmt', 'yuv420p', '-g', '48', '-threads', '0',
];
case 'low':
return gpu
? [
'-c:v', 'h264_nvenc', '-preset', 'p4',
'-rc', 'cbr', '-b:v', '1500k', '-maxrate', '2000k',
'-bufsize', '3000k', '-vf', 'scale=-2:720',
'-g', '48', '-pix_fmt', 'yuv420p',
]
: [
'-c:v', 'libx264', '-preset', 'fast', '-crf', '26',
'-maxrate', '3000k', '-bufsize', '6000k',
'-vf', 'scale=-2:720',
'-pix_fmt', 'yuv420p', '-g', '48', '-threads', '0',
];
case 'high':
default:
return gpu
? [
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune', 'hq',
'-rc', 'cbr', '-b:v', '4000k', '-maxrate', '4500k',
'-bufsize', '8000k', '-g', '48', '-bf', '2',
'-pix_fmt', 'yuv420p',
]
: [
'-c:v', 'libx264', '-preset', 'medium', '-crf', '18',
'-maxrate', '12000k', '-bufsize', '24000k',
'-pix_fmt', 'yuv420p', '-g', '48', '-threads', '0',
];
}
return currentUrl;
}
/// Helper to get current playlist configuration (mocked for now, implies single user)
/// In a real scenario, this should come from the request session/context
PlaylistConfig? _getCurrentPlaylist(Request request) {
// TODO: Retrieve from DB/Session based on Auth
// For now, we assume the frontend sends enough info or we look up the active one
return null; // Implemented later in server.dart injection
/// Audio args. Source mode keeps it simple (plain AAC); transcoded modes
/// keep the downmix + loudness normalization filter.
List<String> _audioArgs({required bool withFilters}) {
return [
'-c:a', 'aac', '-b:a', '192k', '-ac', '2', '-ar', '48000',
if (withFilters)
...['-af',
'pan=stereo|FL=1.0*FL+0.707*FC+0.5*BL+0.5*SL+0.5*LFE|FR=1.0*FR+0.707*FC+0.5*BR+0.5*SR+0.5*LFE,dynaudnorm=f=150:g=15']
else
...['-af', 'aresample=async=1'],
];
}
// ==========================================
// 1. LIVE TV HANDLER (Direct MPEG-TS Proxy)
// ==========================================
Map<String, String> _hlsHeaders() => {
'Content-Type': 'application/vnd.apple.mpegurl',
'Cache-Control': 'no-cache',
'X-Content-Type-Options': 'nosniff',
};
/// Active FFmpeg processes for Live HLS transcoding
final Map<String, Process> _liveProcesses = {};
Map<String, String> _segmentHeaders({int maxAge = 60}) => {
'Content-Type': 'video/mp2t',
'Cache-Control': 'max-age=$maxAge',
};
// ==========================================
// 1. LIVE TV HANDLER (FFmpeg HLS + direct TS proxy)
// ==========================================
Handler createLiveStreamHandler(
Future<PlaylistConfig?> Function(Request) getPlaylist, {
@@ -127,109 +184,89 @@ Handler createLiveStreamHandler(
}) {
final router = Router();
// Route: /api/live/{streamId}/playlist.m3u8 (Master playlist)
router.get('/<streamId>/playlist.m3u8',
(Request request, String streamId) async {
Future<Response> servePlaylist(
Request request,
String streamId,
String quality,
) async {
if (!_isValidStreamId(streamId)) {
return Response.badRequest(body: 'Invalid stream ID');
}
final playlist = await getPlaylist(request);
if (playlist == null) return Response.forbidden('No playlist');
final streamDir = Directory('${_hlsTempDir.path}/live_$streamId');
final targetUrl =
'${playlist.dns}/live/${playlist.username}/${playlist.password}/$streamId.ts';
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
final sessionId = 'live_${streamId}_$quality';
// Start FFmpeg if not already running for this live stream
if (!_liveProcesses.containsKey(streamId)) {
if (streamDir.existsSync()) streamDir.deleteSync(recursive: true);
streamDir.createSync(recursive: true);
if (!sessionManager.contains(sessionId)) {
print(
'[Live HLS] Starting $sessionId: ${LogRedactor.redactUrl(targetUrl)}',
);
}
final targetUrl =
'${playlist.dns}/live/${playlist.username}/${playlist.password}/$streamId.ts';
print('[Live HLS] Starting for $streamId: $targetUrl');
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
final ffmpegArgs = <String>[
final session = await sessionManager.getOrStart(
id: sessionId,
isLive: true,
ffmpegPath: _getFFmpegPath(),
argsBuilder: (dir) => [
'-hide_banner', '-loglevel', 'warning',
if (useNvidiaGpu) ...['-hwaccel', 'cuda'],
if (useNvidiaGpu && quality != 'source') ...['-hwaccel', 'cuda'],
'-headers', 'User-Agent: VLC/3.0.18 LibVLC/3.0.18\r\n',
'-reconnect', '1', '-reconnect_streamed', '1',
'-reconnect_delay_max', '10',
'-i', targetUrl,
// Video
if (useNvidiaGpu) ...[
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune',
'hq',
'-b:v', '8000k', '-maxrate', '12000k', '-bufsize', '16000k',
'-profile:v', 'high', '-level', '4.0',
'-pix_fmt', 'yuv420p',
'-g', '50',
] else ...[
'-c:v', 'libx264', '-preset', 'medium', '-tune', 'zerolatency',
'-profile:v', 'high', '-level', '4.0',
'-b:v', '6000k', '-maxrate', '8000k', '-bufsize', '12000k',
'-pix_fmt', 'yuv420p',
'-g', '50',
],
// Audio: High quality + Sync filter
'-c:a', 'aac', '-b:a', '192k', '-ac', '2', '-ar', '48000',
'-af', 'aresample=async=1',
// HLS Sliding Window — larger window so iOS never requests a deleted segment
..._liveVideoArgs(quality, useNvidiaGpu),
..._audioArgs(withFilters: false),
// HLS sliding window: 10 x 2s segments (lower live latency than the
// previous 20-segment window while still safe for iOS)
'-f', 'hls',
'-hls_time', '2',
'-hls_list_size', '20',
'-hls_list_size', '10',
'-hls_flags', 'delete_segments+independent_segments',
'-hls_segment_type', 'mpegts',
'-hls_segment_filename', 'seg_%03d.ts',
'playlist.m3u8',
];
final process = await Process.start(
_getFFmpegPath(),
ffmpegArgs,
workingDirectory: streamDir.path,
);
_liveProcesses[streamId] = process;
process.stderr
.transform(utf8.decoder)
.listen((d) => print('[Live HLS $streamId] $d'));
process.exitCode.then((_) => _liveProcesses.remove(streamId));
}
// Wait for playlist AND at least one segment reference
final file = File('${streamDir.path}/playlist.m3u8');
int retries = 0;
while (retries < 60) {
if (file.existsSync()) {
final content = file.readAsStringSync();
// Live HLS needs at least 2 or 3 segments to be stable on iOS
// but we start as soon as we have one for speed
if (content.contains('.ts')) break;
}
await Future.delayed(const Duration(milliseconds: 500));
retries++;
}
if (!file.existsSync()) {
return Response.internalServerError(body: 'Timeout starting live HLS');
}
return Response.ok(
file.openRead(),
headers: {
'Content-Type': 'application/vnd.apple.mpegurl',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-cache',
'X-Content-Type-Options': 'nosniff',
},
],
);
final result = await sessionManager.waitForPlaylist(session);
if (!result.ready) {
sessionManager.killSession(sessionId);
return Response(502, body: 'Live transcoder failed: ${result.error}');
}
session.touch();
return Response.ok(
File('${session.dir.path}/playlist.m3u8').openRead(),
headers: _hlsHeaders(),
);
}
// Route: /api/live/{streamId}/{quality}/playlist.m3u8
router.get('/<streamId>/<quality>/playlist.m3u8',
(Request request, String streamId, String quality) {
return servePlaylist(request, streamId, _sanitizeQuality(quality));
});
// Route: /api/live/{streamId}.ts (Direct Proxy for internal recordings or raw playback)
// Back-compat route: /api/live/{streamId}/playlist.m3u8 (?quality=...)
// Redirects so relative segment URLs resolve inside the quality path.
router.get('/<streamId>/playlist.m3u8',
(Request request, String streamId) async {
final quality =
_sanitizeQuality(request.url.queryParameters['quality']);
return Response.found('/api/live/$streamId/$quality/playlist.m3u8');
});
// Route: /api/live/{streamId}.ts (Direct Proxy for recordings/raw playback)
router.get('/<streamId>.ts', (Request request, String streamId) async {
final playlist = await getPlaylist(request);
if (playlist == null) return Response.forbidden('No playlist');
final targetUrl =
'${playlist.dns}/live/${playlist.username}/${playlist.password}/$streamId.ts';
print('[Live Proxy] Forwarding $streamId: $targetUrl');
print('[Live Proxy] Forwarding $streamId: ${LogRedactor.redactUrl(targetUrl)}');
final client = http.Client();
final proxyRequest = http.Request('GET', Uri.parse(targetUrl));
@@ -243,313 +280,143 @@ Handler createLiveStreamHandler(
body: response.stream,
headers: {
'Content-Type': 'video/mp2t',
'Access-Control-Allow-Origin': '*',
'Connection': 'keep-alive',
},
);
});
// Route: /api/live/{streamId}/{segment}
router.get('/<streamId>/<segment>',
(Request request, String streamId, String segment) async {
final file = File('${_hlsTempDir.path}/live_$streamId/$segment');
// Route: /api/live/{streamId}/{quality}/{segment}
router.get('/<streamId>/<quality>/<segment>',
(Request request, String streamId, String quality, String segment) {
if (!_isValidStreamId(streamId) || segment.contains('..')) {
return Response.badRequest(body: 'Invalid request');
}
final sessionId = 'live_${streamId}_${_sanitizeQuality(quality)}';
sessionManager.touch(sessionId);
final file = File('${_hlsTempDir.path}/$sessionId/$segment');
if (!file.existsSync()) return Response.notFound('Segment not found');
return Response.ok(
file.openRead(),
headers: {
'Content-Type': 'video/mp2t',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'max-age=60',
},
);
return Response.ok(file.openRead(), headers: _segmentHeaders());
});
return router;
return router.call;
}
// ==========================================
// 2. VOD HANDLER (FFmpeg HLS Transcoding)
// ==========================================
// ==========================================
// 2. VOD HANDLER (FFmpeg HLS Transcoding)
// ==========================================
final _lastLogTime = <String, int>{};
Handler createVodStreamHandler(
Future<PlaylistConfig?> Function(Request) getPlaylist, {
bool Function()? isGpuEnabled,
}) {
final router = Router();
// Route: /api/vod/{streamId}/playlist.m3u8
router.get('/<streamId>/playlist.m3u8',
(Request request, String streamId) async {
Future<Response> servePlaylist(
Request request,
String streamId,
String quality,
) async {
if (!_isValidStreamId(streamId)) {
return Response.badRequest(body: 'Invalid stream ID');
}
final playlist = await getPlaylist(request);
if (playlist == null) {
return Response.internalServerError(body: 'No playlist');
}
// Validate streamId to prevent Path Traversal
if (!RegExp(r'^[a-zA-Z0-9_-]+$').hasMatch(streamId)) {
return Response.badRequest(body: 'Invalid stream ID');
}
final streamDir = Directory('${_hlsTempDir.path}/$streamId');
// Check if existing session is healthy
if (_vodProcesses.containsKey(streamId)) {
final existingProcess = _vodProcesses[streamId]!;
// Check if process is still running by checking if playlist exists and has content
final playlistFile = File('${streamDir.path}/playlist.m3u8');
if (playlistFile.existsSync()) {
final content = playlistFile.readAsStringSync();
// Check if playlist has segments (healthy transcoding)
if (content.contains('.ts')) {
// Only log once per second to avoid spam
final now = DateTime.now().millisecondsSinceEpoch;
if (!_lastLogTime.containsKey(streamId) ||
(now - _lastLogTime[streamId]! > 2000)) {
print('[VOD] Reusing existing session for $streamId');
_lastLogTime[streamId] = now;
}
// Serve existing playlist
return Response.ok(
playlistFile.openRead(),
headers: {
'Content-Type': 'application/vnd.apple.mpegurl',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-cache',
},
);
}
}
// Playlist missing or empty - process likely failed, clean up
print('[VOD] Cleaning up stale session for $streamId');
try {
existingProcess.kill();
} catch (e) {
// Process may already be dead
}
_vodProcesses.remove(streamId);
// Clean up directory
if (streamDir.existsSync()) {
try {
streamDir.deleteSync(recursive: true);
} catch (e) {
print('[VOD] Failed to clean directory: $e');
}
}
}
// Build Upstream URL based on content type
// Check for type parameter in request URL (?type=series or ?type=movie)
// ?type=series or ?type=movie selects the upstream path
final contentType = request.url.queryParameters['type'] ?? 'movie';
final basePath = contentType == 'series' ? 'series' : 'movie';
// Only start FFmpeg if not already running
if (!_vodProcesses.containsKey(streamId)) {
// Prepare directory (Only for new session)
if (streamDir.existsSync()) {
streamDir.deleteSync(recursive: true);
}
streamDir.createSync(recursive: true);
final targetUrl =
'${playlist.dns}/$basePath/${playlist.username}/${playlist.password}/$streamId.mkv';
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
final sessionId = 'vod_${streamId}_$quality';
final targetUrl =
'${playlist.dns}/$basePath/${playlist.username}/${playlist.password}/$streamId.mkv';
print('[VOD] Starting Transcode ($contentType): $targetUrl');
// Check if NVIDIA GPU is enabled (from database setting or env var fallback)
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
if (useNvidiaGpu) {
print('[VOD] Using NVIDIA GPU acceleration (NVENC)');
}
// Build FFmpeg arguments
final ffmpegArgs = <String>[
'-hide_banner',
'-loglevel',
'warning',
];
// NVIDIA GPU Hardware Acceleration
if (useNvidiaGpu) {
ffmpegArgs.addAll([
'-hwaccel', 'cuda',
// Note: Don't use hwaccel_output_format cuda - it can cause issues
]);
}
// Input and robustness flags
ffmpegArgs.addAll([
'-headers',
'User-Agent: VLC/3.0.18 LibVLC/3.0.18\r\n',
'-reconnect',
'1',
'-reconnect_at_eof',
'1',
'-reconnect_streamed',
'1',
'-reconnect_delay_max',
'10',
'-rw_timeout',
'30000000',
'-timeout',
'30000000',
'-analyzeduration',
'5000000',
'-probesize',
'10000000',
'-i',
targetUrl,
]);
// Video encoding (GPU or CPU)
if (useNvidiaGpu) {
// NVIDIA NVENC - Hardware encoding (50x+ faster, much lower CPU)
ffmpegArgs.addAll([
'-c:v', 'h264_nvenc', // Use NVIDIA NVENC encoder
'-preset', 'p4', // Good quality/speed balance
'-tune', 'hq', // High quality mode
'-rc', 'cbr', // Constant bitrate for HLS
'-b:v', '4000k', // Target bitrate
'-maxrate', '4500k',
'-bufsize', '8000k',
'-g', '48', // Keyframe every 2 seconds
'-bf', '2', // B-frames for quality
'-pix_fmt', 'yuv420p',
]);
} else {
// CPU encoding (libx264)
ffmpegArgs.addAll([
'-c:v',
'libx264',
'-preset',
'medium', // Quality over raw speed for VOD
'-crf',
'18', // Near-native visual quality
'-maxrate',
'12000k',
'-bufsize',
'24000k',
'-pix_fmt',
'yuv420p',
'-g', '48',
'-threads',
'0',
]);
}
// Audio encoding (same for both)
ffmpegArgs.addAll([
'-c:a',
'aac',
'-b:a',
'192k',
'-ar',
'48000',
'-af',
'pan=stereo|FL=1.0*FL+0.707*FC+0.5*BL+0.5*SL+0.5*LFE|FR=1.0*FR+0.707*FC+0.5*BR+0.5*SR+0.5*LFE,dynaudnorm=f=150:g=15',
]);
// HLS output settings
ffmpegArgs.addAll([
'-f',
'hls',
'-hls_time',
'4',
'-hls_list_size',
'0',
'-hls_playlist_type',
'event',
'-hls_allow_cache',
'1',
'-hls_flags',
'independent_segments',
'-hls_segment_type',
'mpegts',
'-hls_segment_filename',
'segment_%03d.ts',
'-start_number',
'0',
'playlist.m3u8',
]);
final ffmpegPath = _getFFmpegPath();
Process.start(
ffmpegPath,
ffmpegArgs,
workingDirectory: streamDir.path,
).then((process) {
_vodProcesses[streamId] = process;
process.stderr.transform(utf8.decoder).listen((data) {
// Log only major errors or startup info to keep logs clean(er)
// or keep verbose if debugging
print('[FFmpeg $streamId] $data');
});
process.exitCode.then((code) {
print('[VOD] FFmpeg exited with code $code');
_vodProcesses.remove(streamId);
});
});
}
// Wait for playlist AND at least one segment to be referenced
final playlistFile = File('${streamDir.path}/playlist.m3u8');
int retries = 0;
while (retries < 60) {
if (playlistFile.existsSync()) {
final content = playlistFile.readAsStringSync();
if (content.contains('.ts')) break; // At least one segment is ready
}
await Future.delayed(const Duration(milliseconds: 500));
retries++;
}
if (!playlistFile.existsSync()) {
return Response.internalServerError(
body: 'Timeout waiting for transcoder',
if (!sessionManager.contains(sessionId)) {
print(
'[VOD] Starting $sessionId ($contentType): ${LogRedactor.redactUrl(targetUrl)}',
);
}
return Response.ok(
playlistFile.openRead(),
headers: {
'Content-Type': 'application/vnd.apple.mpegurl', // Correct HLS Mime
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-cache',
},
final session = await sessionManager.getOrStart(
id: sessionId,
isLive: false,
ffmpegPath: _getFFmpegPath(),
argsBuilder: (dir) => [
'-hide_banner', '-loglevel', 'warning',
if (useNvidiaGpu && quality != 'source') ...['-hwaccel', 'cuda'],
'-headers', 'User-Agent: VLC/3.0.18 LibVLC/3.0.18\r\n',
'-reconnect', '1',
'-reconnect_at_eof', '1',
'-reconnect_streamed', '1',
'-reconnect_delay_max', '10',
'-rw_timeout', '30000000',
'-timeout', '30000000',
'-analyzeduration', '5000000',
'-probesize', '10000000',
'-i', targetUrl,
..._vodVideoArgs(quality, useNvidiaGpu),
..._audioArgs(withFilters: quality != 'source'),
'-f', 'hls',
'-hls_time', '4',
'-hls_list_size', '0',
'-hls_playlist_type', 'event',
'-hls_allow_cache', '1',
'-hls_flags', 'independent_segments',
'-hls_segment_type', 'mpegts',
'-hls_segment_filename', 'segment_%03d.ts',
'-start_number', '0',
'playlist.m3u8',
],
);
});
// Route: /api/vod/{streamId}/segment_{n}.ts (Serve segments)
router.get('/<streamId>/<segment>',
(Request request, String streamId, String segment) async {
final file = File('${_hlsTempDir.path}/$streamId/$segment');
if (!file.existsSync()) {
return Response.notFound('Segment not found');
final result = await sessionManager.waitForPlaylist(session);
if (!result.ready) {
sessionManager.killSession(sessionId);
return Response(502, body: 'VOD transcoder failed: ${result.error}');
}
session.touch();
return Response.ok(
file.openRead(),
headers: {
'Content-Type': 'video/mp2t',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'max-age=3600', // Cache segments
},
File('${session.dir.path}/playlist.m3u8').openRead(),
headers: _hlsHeaders(),
);
}
// Route: /api/vod/{streamId}/{quality}/playlist.m3u8
router.get('/<streamId>/<quality>/playlist.m3u8',
(Request request, String streamId, String quality) {
return servePlaylist(request, streamId, _sanitizeQuality(quality));
});
return router;
// Back-compat route: /api/vod/{streamId}/playlist.m3u8 (?quality=...)
router.get('/<streamId>/playlist.m3u8',
(Request request, String streamId) async {
final quality =
_sanitizeQuality(request.url.queryParameters['quality']);
final query = request.url.queryParameters['type'] != null
? '?type=${request.url.queryParameters['type']}'
: '';
return Response.found('/api/vod/$streamId/$quality/playlist.m3u8$query');
});
// Route: /api/vod/{streamId}/{quality}/{segment}
router.get('/<streamId>/<quality>/<segment>',
(Request request, String streamId, String quality, String segment) {
if (!_isValidStreamId(streamId) || segment.contains('..')) {
return Response.badRequest(body: 'Invalid request');
}
final sessionId = 'vod_${streamId}_${_sanitizeQuality(quality)}';
sessionManager.touch(sessionId);
final file = File('${_hlsTempDir.path}/$sessionId/$segment');
if (!file.existsSync()) return Response.notFound('Segment not found');
return Response.ok(file.openRead(), headers: _segmentHeaders(maxAge: 3600));
});
return router.call;
}
// ==========================================
@@ -562,7 +429,8 @@ Handler createRecordingStreamHandler(
}) {
final router = Router();
router.get('/<streamId>/playlist.m3u8', (Request request, String streamId) async {
router.get('/<streamId>/playlist.m3u8',
(Request request, String streamId) async {
final recording = db.getRecordingById(streamId);
if (recording == null) {
return Response.notFound('Recording not found');
@@ -573,121 +441,79 @@ Handler createRecordingStreamHandler(
return Response(202, body: 'Recording not yet started');
}
if (recording.status == 'failed') {
return Response(422, body: 'Recording failed: ${recording.errorReason ?? 'unknown error'}');
return Response(422,
body: 'Recording failed: ${recording.errorReason ?? 'unknown error'}');
}
if (recording.status != 'completed' && recording.status != 'recording') {
return Response.internalServerError(body: 'Invalid recording status: ${recording.status}');
return Response.internalServerError(
body: 'Invalid recording status: ${recording.status}');
}
// Check file path and existence
if (recording.filePath == null) {
return Response.internalServerError(body: 'Recording file path not set');
}
final targetUrl = recording.filePath!;
if (!File(targetUrl).existsSync()) {
return Response.internalServerError(body: 'Physical recording file not found: $targetUrl');
return Response.internalServerError(
body: 'Physical recording file not found');
}
final streamDir = Directory('${_hlsTempDir.path}/rec_$streamId');
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
final sessionId = 'rec_$streamId';
if (_vodProcesses.containsKey('rec_$streamId')) {
final existingProcess = _vodProcesses['rec_$streamId']!;
final playlistFile = File('${streamDir.path}/playlist.m3u8');
if (playlistFile.existsSync() && playlistFile.readAsStringSync().contains('.ts')) {
return Response.ok(
playlistFile.openRead(),
headers: {
'Content-Type': 'application/vnd.apple.mpegurl',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-cache',
},
);
}
try { existingProcess.kill(); } catch (_) {}
_vodProcesses.remove('rec_$streamId');
if (streamDir.existsSync()) streamDir.deleteSync(recursive: true);
}
if (!_vodProcesses.containsKey('rec_$streamId')) {
if (streamDir.existsSync()) streamDir.deleteSync(recursive: true);
streamDir.createSync(recursive: true);
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
final ffmpegArgs = <String>[
final session = await sessionManager.getOrStart(
id: sessionId,
isLive: false,
ffmpegPath: _getFFmpegPath(),
argsBuilder: (dir) => [
'-hide_banner', '-loglevel', 'warning',
if (useNvidiaGpu) ...['-hwaccel', 'cuda'],
'-i', targetUrl,
];
if (useNvidiaGpu) {
ffmpegArgs.addAll([
if (useNvidiaGpu) ...[
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune', 'hq',
'-rc', 'cbr', '-b:v', '3000k', '-maxrate', '3500k', '-bufsize', '6000k',
'-rc', 'cbr', '-b:v', '3000k', '-maxrate', '3500k',
'-bufsize', '6000k',
'-g', '48', '-bf', '2', '-pix_fmt', 'yuv420p',
]);
} else {
ffmpegArgs.addAll([
] else ...[
'-c:v', 'libx264', '-preset', 'medium', '-crf', '18',
'-maxrate', '12000k', '-bufsize', '24000k', '-pix_fmt', 'yuv420p',
'-g', '48', '-threads', '0',
]);
}
ffmpegArgs.addAll([
'-c:a', 'aac', '-b:a', '192k', '-ar', '48000',
'-af', 'pan=stereo|FL=1.0*FL+0.707*FC+0.5*BL+0.5*SL+0.5*LFE|FR=1.0*FR+0.707*FC+0.5*BR+0.5*SR+0.5*LFE,dynaudnorm=f=150:g=15',
],
..._audioArgs(withFilters: true),
'-f', 'hls', '-hls_time', '4', '-hls_list_size', '0',
'-hls_playlist_type', 'vod', '-hls_allow_cache', '1',
'-hls_flags', 'independent_segments', '-hls_segment_type', 'mpegts',
'-hls_segment_filename', 'segment_%03d.ts', '-start_number', '0',
'playlist.m3u8',
]);
],
);
Process.start(_getFFmpegPath(), ffmpegArgs, workingDirectory: streamDir.path).then((process) {
_vodProcesses['rec_$streamId'] = process;
process.stderr.transform(utf8.decoder).listen((data) => print('[FFmpeg Rec $streamId] $data'));
process.exitCode.then((code) {
_vodProcesses.remove('rec_$streamId');
});
});
final result = await sessionManager.waitForPlaylist(session);
if (!result.ready) {
sessionManager.killSession(sessionId);
return Response(502,
body: 'Recording transcoder failed: ${result.error}');
}
final playlistFile = File('${streamDir.path}/playlist.m3u8');
int retries = 0;
while (retries < 60) {
if (playlistFile.existsSync() && playlistFile.readAsStringSync().contains('.ts')) break;
await Future.delayed(const Duration(milliseconds: 500));
retries++;
}
if (!playlistFile.existsSync()) return Response.internalServerError(body: 'Timeout waiting for transcoder');
session.touch();
return Response.ok(
playlistFile.openRead(),
headers: {
'Content-Type': 'application/vnd.apple.mpegurl',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'no-cache',
},
File('${session.dir.path}/playlist.m3u8').openRead(),
headers: _hlsHeaders(),
);
});
router.get('/<streamId>/<segment>', (Request request, String streamId, String segment) async {
final file = File('${_hlsTempDir.path}/rec_$streamId/$segment');
router.get('/<streamId>/<segment>',
(Request request, String streamId, String segment) async {
if (segment.contains('..')) {
return Response.badRequest(body: 'Invalid request');
}
final sessionId = 'rec_$streamId';
sessionManager.touch(sessionId);
final file = File('${_hlsTempDir.path}/$sessionId/$segment');
if (!file.existsSync()) return Response.notFound('Segment not found');
return Response.ok(
file.openRead(),
headers: {
'Content-Type': 'video/mp2t',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'max-age=3600',
},
);
return Response.ok(file.openRead(), headers: _segmentHeaders(maxAge: 3600));
});
return router;
return router.call;
}
+78
View File
@@ -0,0 +1,78 @@
import 'dart:convert';
import 'package:shelf/shelf.dart';
import 'package:http/http.dart' as http;
import '../models/playlist_config.dart';
import '../utils/log_redactor.dart';
/// Authenticated gateway to the Xtream `player_api.php` endpoint.
///
/// The frontend never sees the Xtream credentials: it calls
/// `GET /api/xtream-api?action=...` with its session token and the server
/// injects the username/password of the user's playlist before forwarding.
class XtreamApiHandler {
final Future<PlaylistConfig?> Function(Request) _getPlaylist;
final http.Client _client = http.Client();
XtreamApiHandler(this._getPlaylist);
/// Query parameters the client is allowed to pass through to Xtream.
static const _allowedParams = {
'action',
'category_id',
'stream_id',
'series_id',
'vod_id',
'limit',
'type',
};
Future<Response> handle(Request request) async {
final playlist = await _getPlaylist(request);
if (playlist == null) {
return Response.forbidden(
jsonEncode({'error': 'No playlist configured'}),
headers: {'Content-Type': 'application/json'},
);
}
final params = <String, String>{
'username': playlist.username,
'password': playlist.password,
};
request.url.queryParameters.forEach((key, value) {
if (_allowedParams.contains(key)) params[key] = value;
});
final base = Uri.parse('${playlist.dns}/player_api.php');
final targetUrl = base.replace(queryParameters: params);
try {
final proxyRequest = http.Request('GET', targetUrl)
..headers['User-Agent'] = 'VLC/3.0.18 LibVLC/3.0.18'
..headers['Accept'] = '*/*'
..followRedirects = true;
final response = await _client
.send(proxyRequest)
.timeout(const Duration(seconds: 90));
return Response(
response.statusCode,
body: response.stream,
headers: {
'Content-Type':
response.headers['content-type'] ?? 'application/json',
'Cache-Control': 'no-store',
},
);
} catch (e) {
print(
'[XtreamApi] Error forwarding to ${LogRedactor.redactUrl(targetUrl.toString())}: $e',
);
return Response.internalServerError(
body: jsonEncode({'error': 'Upstream Xtream API error'}),
headers: {'Content-Type': 'application/json'},
);
}
}
}
+18
View File
@@ -186,9 +186,27 @@ class AppDatabase {
return null;
}
// Lazy migration: rehash legacy SHA-256 hashes with bcrypt on
// successful login (the only moment the plaintext is available).
if (PasswordHasher.isLegacy(passwordHash)) {
updatePasswordHash(
result.first['id'] as String,
PasswordHasher.hash(password),
);
print('[Auth] Migrated legacy password hash for user: $username');
}
return User.fromMap(result.first);
}
/// Replace a user's stored password hash (used by lazy bcrypt migration)
void updatePasswordHash(String userId, String newHash) {
_db.execute(
'UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
[newHash, userId],
);
}
/// Create new user
User createUser(String username, String password, {bool isAdmin = false}) {
final userId = _uuid.v4();
+34 -2
View File
@@ -1,3 +1,4 @@
import 'dart:io';
import 'package:shelf/shelf.dart';
import '../database/database.dart';
@@ -16,16 +17,20 @@ Middleware authMiddleware(AppDatabase db) {
return Response(401, body: 'Unauthorized');
}
// Verify session
// Verify session (findSessionByToken enforces expires_at)
final session = db.findSessionByToken(token);
if (session == null) {
return Response(401, body: 'Invalid or expired session');
}
// Add userId to context
// Add user info to context. Both keys are populated because handlers
// are inconsistent: playlists_handler reads 'userId', while
// getPlaylist/admin routes read 'user'.
final user = db.findUserById(session.userId);
final updatedRequest = request.change(context: {
...request.context,
'userId': session.userId,
if (user != null) 'user': user,
},);
return handler(updatedRequest);
@@ -33,6 +38,33 @@ Middleware authMiddleware(AppDatabase db) {
};
}
/// Auth middleware for streaming routes (HLS playlists/segments).
///
/// hls.js/mpegts.js inside the player iframe cannot send Authorization
/// headers, so these routes accept the HttpOnly session cookie instead.
/// Loopback requests without X-Forwarded-For are allowed through because
/// the recording scheduler's local FFmpeg fetches
/// `http://localhost:8089/api/live/<id>.ts` without credentials.
Middleware streamAuthMiddleware(AppDatabase db) {
return (Handler handler) {
return (Request request) async {
final connectionInfo =
request.context['shelf.io.connection_info'] as HttpConnectionInfo?;
final isLoopback = connectionInfo?.remoteAddress.isLoopback ?? false;
final viaProxy = request.headers.containsKey('x-forwarded-for');
if (isLoopback && !viaProxy) {
return handler(request);
}
final token = _extractToken(request);
if (token == null || db.findSessionByToken(token) == null) {
return Response(401, body: 'Unauthorized');
}
return handler(request);
};
};
}
/// Extract token from Authorization header or cookie
String? _extractToken(Request request) {
// Try Authorization header first
+83 -20
View File
@@ -1,12 +1,27 @@
import 'package:shelf/shelf.dart';
import 'dart:async';
import 'dart:io';
/// Security Middleware Collection
///
///
/// Includes:
/// - Honeypot Routes (Trap for bots)
/// - Security Headers (HSTS, XSS Protection)
/// - Security Headers (HSTS, XSS Protection, CSP Report-Only)
/// - Rate Limiting (Basic DoS protection)
/// - Login-specific rate limiting (brute-force protection)
/// Resolve the real client IP.
/// Honors the first hop of X-Forwarded-For when behind nginx, otherwise
/// falls back to the socket connection info.
String clientIpOf(Request request) {
final forwarded = request.headers['x-forwarded-for'];
if (forwarded != null && forwarded.isNotEmpty) {
return forwarded.split(',').first.trim();
}
final connectionInfo =
request.context['shelf.io.connection_info'] as HttpConnectionInfo?;
return connectionInfo?.remoteAddress.address ?? 'unknown';
}
/// 1. Security Headers Middleware
/// Adds standard security headers to every response.
@@ -14,15 +29,24 @@ Middleware securityHeadersMiddleware() {
return (Handler handler) {
return (Request request) async {
final response = await handler(request);
return response.change(headers: {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'SAMEORIGIN', // Changed from DENY to allow embedding player.html
'X-Frame-Options': 'SAMEORIGIN', // Allow embedding player.html iframes
'X-XSS-Protection': '1; mode=block',
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
'Referrer-Policy': 'strict-origin-when-cross-origin',
// Note: CSP is tricky with Flutter Web (requires 'unsafe-eval' for Dart),
// so we omit it here to avoid breaking the app, or use a permissive one.
// Report-Only first: Flutter Web (CanvasKit/wasm) and google_fonts
// can break under an enforcing CSP. Promote to enforcing only after
// a clean soak with no violations in browser consoles.
'Content-Security-Policy-Report-Only':
"default-src 'self'; "
"script-src 'self' 'wasm-unsafe-eval' 'unsafe-eval'; "
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
"font-src 'self' https://fonts.gstatic.com; "
"img-src 'self' data: blob: https:; "
"media-src 'self' blob:; "
"connect-src 'self' https://fonts.gstatic.com",
},);
};
};
@@ -48,15 +72,15 @@ Middleware honeypotMiddleware() {
return (Handler handler) {
return (Request request) {
final path = request.url.path;
// Check if path contains any honeypot target
for (final trap in honeypotPaths) {
if (path.contains(trap.replaceAll('/', ''))) { // Simple check
print('SECURITY ALERT: Honeypot triggered by ${request.context['clientIp'] ?? 'unknown IP'} on path: $path');
print('SECURITY ALERT: Honeypot triggered by ${clientIpOf(request)} on path: $path');
return Response.forbidden('Access Denied');
}
}
return handler(request);
};
};
@@ -64,10 +88,10 @@ Middleware honeypotMiddleware() {
/// 3. Rate Limit Middleware (In-Memory)
/// Limits requests per IP address.
/// Default: 100 requests per minute per IP.
/// Default: 200 requests per minute per IP.
Middleware rateLimitMiddleware({int requestsPerMinute = 200}) {
final clientRequests = <String, List<DateTime>>{};
// Cleanup timer to remove old entries and prevent memory leaks
Timer.periodic(const Duration(minutes: 5), (_) {
final now = DateTime.now();
@@ -80,26 +104,23 @@ Middleware rateLimitMiddleware({int requestsPerMinute = 200}) {
return (Handler handler) {
return (Request request) {
// Identify client by IP (passed from main server or headers)
// Note: In real prod behind Nginx, use X-Forwarded-For
// Here we assume direct or standard setup.
final clientIp = (request.context['clientIp'] as String?) ?? 'unknown';
final clientIp = clientIpOf(request);
if (clientIp != 'unknown' && clientIp != '127.0.0.1') {
final now = DateTime.now();
// Get or create history for this IP
final history = clientRequests.putIfAbsent(clientIp, () => []);
// Clean old requests (older than 1 minute)
history.removeWhere((t) => now.difference(t).inMinutes >= 1);
// Check limit
if (history.length >= requestsPerMinute) {
print('SECURITY WARN: Rate limit exceeded for $clientIp');
return Response(429, body: 'Too Many Requests');
}
// Add current request
history.add(now);
}
@@ -108,3 +129,45 @@ Middleware rateLimitMiddleware({int requestsPerMinute = 200}) {
};
};
}
/// 4. Login Rate Limit Middleware
/// Strict per-IP limit on login attempts (brute-force protection),
/// plus a small delay on each attempt to slow credential stuffing.
Middleware loginRateLimitMiddleware({int attemptsPerMinute = 10}) {
final attempts = <String, List<DateTime>>{};
Timer.periodic(const Duration(minutes: 5), (_) {
final now = DateTime.now();
attempts.removeWhere((_, times) {
times.removeWhere((t) => now.difference(t).inMinutes > 1);
return times.isEmpty;
});
});
return (Handler handler) {
return (Request request) async {
// Only throttle the login POST; other auth routes pass through
if (!(request.method == 'POST' && request.url.path.endsWith('login'))) {
return handler(request);
}
final clientIp = clientIpOf(request);
final now = DateTime.now();
final history = attempts.putIfAbsent(clientIp, () => []);
history.removeWhere((t) => now.difference(t).inMinutes >= 1);
if (history.length >= attemptsPerMinute) {
print('SECURITY WARN: Login rate limit exceeded for $clientIp');
return Response(429, body: 'Too many login attempts. Try again later.');
}
history.add(now);
final response = await handler(request);
if (response.statusCode == 401) {
// Slow down brute-force attempts on failed logins
await Future.delayed(const Duration(milliseconds: 300));
}
return response;
};
};
}
+3 -1
View File
@@ -42,7 +42,9 @@ class Playlist {
'name': name,
'serverUrl': serverUrl,
'username': username,
'password': password,
// Never expose the Xtream password to clients; the backend injects
// credentials server-side (see xtream_api_handler.dart).
'password': '',
'dns': dns,
'createdAt': createdAt.toIso8601String(),
'updatedAt': updatedAt.toIso8601String(),
+5
View File
@@ -14,6 +14,11 @@ dependencies:
args: ^2.4.2
sqlite3: ^2.4.0
crypto: ^3.0.3
bcrypt: ^1.1.3
path: ^1.9.0
uuid: ^4.3.3
hive: ^2.2.3
equatable: ^2.0.5
dev_dependencies:
test: ^1.25.0
+97 -29
View File
@@ -5,7 +5,6 @@ import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_static/shelf_static.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:http/http.dart' as http;
import 'package:args/args.dart';
import 'database/database.dart';
import 'models/user.dart';
@@ -20,6 +19,7 @@ import 'api/proxy_handler.dart';
import 'api/recordings_api.dart';
import 'api/epg_api.dart';
import 'api/season_passes_api.dart';
import 'api/xtream_api_handler.dart';
import 'middleware/auth_middleware.dart';
import 'middleware/security_middleware.dart';
import 'services/cleanup_service.dart';
@@ -113,15 +113,46 @@ void main(List<String> args) async {
final playlistsHandler = PlaylistsHandler(db);
final usersHandler = UsersHandler(db);
final settingsHandler = SettingsHandler(db);
final proxyHandler = ProxyHandler(getPlaylist, db);
final proxyHandler = ProxyHandler(getPlaylist);
final recordingsApi = RecordingsApi(db, recordingScheduler);
final epgApi = EpgApi(db, getPlaylist);
final epgApi = EpgApi(getPlaylist);
final seasonPassesApi = SeasonPassesApi(db);
final xtreamApiHandler = XtreamApiHandler(getPlaylist);
// TV Recordings sub-router (wrapped with auth below).
// NOTE: /api/recordings/stream/* falls through this router (404) and is
// handled by streamingRouter further down the Cascade.
final recordingsRouter = Router()
..get('/', recordingsApi.handleGetAll)
..post('/', recordingsApi.handlePost)
..delete('/<id>', recordingsApi.handleDelete)
..post('/stop/<id>', recordingsApi.handleStop)
..get('/logs/<id>', recordingsApi.getLogHandler);
final epgRouter = Router()..get('/<channelId>', epgApi.handleGetEpg);
final seasonPassesRouter = Router()
..get('/', seasonPassesApi.handleGetAll)
..post('/', seasonPassesApi.handlePost)
..delete('/<id>', seasonPassesApi.handleDelete);
// Setup router
final apiRouter = Router()
// Auth endpoints
..mount('/api/auth', authHandler.router)
// Auth endpoints (with per-IP brute-force protection on login)
..mount(
'/api/auth',
const Pipeline()
.addMiddleware(loginRateLimitMiddleware())
.addHandler(authHandler.router.call),
)
// Xtream API gateway: injects credentials server-side so the
// frontend never sees them
..mount(
'/api/xtream-api',
const Pipeline()
.addMiddleware(authMiddleware(db))
.addHandler(xtreamApiHandler.handle),
)
// Playlists endpoints
..mount(
'/api/playlists',
@@ -143,18 +174,27 @@ void main(List<String> args) async {
.addMiddleware(authMiddleware(db))
.addHandler(settingsHandler.router.call),
)
// TV Recordings - routes explicites
..get('/api/recordings', recordingsApi.handleGetAll)
..post('/api/recordings', recordingsApi.handlePost)
..delete('/api/recordings/<id>', recordingsApi.handleDelete)
..post('/api/recordings/stop/<id>', recordingsApi.handleStop)
..get('/api/recordings/logs/<id>', recordingsApi.getLogHandler)
// EPG - guide TV
..get('/api/epg/<channelId>', epgApi.handleGetEpg)
// Season Passes - enregistrements répétés
..get('/api/season-passes', seasonPassesApi.handleGetAll)
..post('/api/season-passes', seasonPassesApi.handlePost)
..delete('/api/season-passes/<id>', seasonPassesApi.handleDelete);
// TV Recordings (auth required)
..mount(
'/api/recordings',
const Pipeline()
.addMiddleware(authMiddleware(db))
.addHandler(recordingsRouter.call),
)
// EPG - guide TV (auth required)
..mount(
'/api/epg',
const Pipeline()
.addMiddleware(authMiddleware(db))
.addHandler(epgRouter.call),
)
// Season Passes - enregistrements répétés (auth required)
..mount(
'/api/season-passes',
const Pipeline()
.addMiddleware(authMiddleware(db))
.addHandler(seasonPassesRouter.call),
);
// NOTE: /api/xtream is handled by proxyHandler in the Cascade below
// Do NOT mount here as it would intercept and block the actual proxy
@@ -256,11 +296,17 @@ void main(List<String> args) async {
// This allows non-/api/xtream requests to fall through to static handler
final proxyPipeline = proxyHandler.handler;
// Streaming routes accept the HttpOnly session cookie (hls.js cannot send
// Authorization headers); local FFmpeg loopback fetches bypass auth.
final protectedStreaming = const Pipeline()
.addMiddleware(streamAuthMiddleware(db))
.addHandler(streamingRouter.call);
// Main handler
final handler = Cascade()
.add(apiRouter.call) /* Standard API endpoints */
.add(proxyPipeline) /* Xtream Proxy (auth inside handler) */
.add(streamingRouter.call) /* Streaming endpoints */
.add(protectedStreaming) /* Streaming endpoints */
.add(staticHandler)
.handler;
@@ -292,26 +338,48 @@ void main(List<String> args) async {
});
}
/// CORS middleware to allow cross-origin requests
/// CORS middleware.
///
/// The app is served same-origin by this server, so CORS headers are only
/// needed for development (Flutter dev server on another port) or an
/// explicitly configured external origin via the ALLOWED_ORIGIN env var.
/// The request Origin is echoed back only when it matches the allowlist —
/// never a wildcard.
Middleware _corsMiddleware() {
final extraOrigin = Platform.environment['ALLOWED_ORIGIN'];
bool isAllowed(String origin) {
if (extraOrigin != null && extraOrigin.isNotEmpty && origin == extraOrigin) {
return true;
}
// Local development origins (flutter run -d chrome, etc.)
final uri = Uri.tryParse(origin);
return uri != null && (uri.host == 'localhost' || uri.host == '127.0.0.1');
}
return (Handler handler) {
return (Request request) async {
final origin = request.headers['origin'];
final headers = <String, String>{
if (origin != null && isAllowed(origin)) ...{
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers':
'Origin, Content-Type, Accept, Authorization, Range',
'Access-Control-Expose-Headers': 'Content-Length, Content-Range',
'Access-Control-Allow-Credentials': 'true',
'Vary': 'Origin',
},
};
// Handle preflight requests
if (request.method == 'OPTIONS') {
return Response.ok('', headers: _corsHeaders);
return Response.ok('', headers: headers);
}
// Process request and add CORS headers to response
final response = await handler(request);
return response.change(headers: _corsHeaders);
return headers.isEmpty ? response : response.change(headers: headers);
};
};
}
final _corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers':
'Origin, Content-Type, Accept, Authorization, Range',
'Access-Control-Expose-Headers': 'Content-Length, Content-Range',
};
+192
View File
@@ -0,0 +1,192 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
/// One running FFmpeg transcoding session (live, VOD or recording playback).
class FfmpegSession {
final String id;
final Process process;
final Directory dir;
final bool isLive;
DateTime lastAccess = DateTime.now();
bool exited = false;
int? exitCode;
/// Last stderr lines, kept for fast-fail diagnostics.
final List<String> recentStderr = [];
FfmpegSession({
required this.id,
required this.process,
required this.dir,
required this.isLive,
});
void touch() => lastAccess = DateTime.now();
}
/// Registry of FFmpeg transcoding processes.
///
/// Responsibilities:
/// - one process per session id (`live_{id}_{quality}`, `vod_{id}`, ...)
/// - reaper kills sessions idle beyond a TTL (no viewer fetching segments)
/// - startup wipe of the HLS temp dir (orphan dirs after a crash)
/// - SIGTERM/SIGINT hook so `docker stop` leaves no orphan ffmpeg
class FfmpegSessionManager {
final Directory baseDir;
final Map<String, FfmpegSession> _sessions = {};
Timer? _reaper;
static const liveIdleTimeout = Duration(minutes: 4);
static const vodIdleTimeout = Duration(minutes: 15);
FfmpegSessionManager(this.baseDir);
/// Wipe orphan session dirs and start the reaper. Call once at startup.
Future<void> init() async {
if (baseDir.existsSync()) {
try {
baseDir.deleteSync(recursive: true);
} catch (e) {
print('[FFmpegManager] Could not wipe temp dir: $e');
}
}
baseDir.createSync(recursive: true);
_reaper = Timer.periodic(const Duration(seconds: 60), (_) => _reap());
// Clean shutdown for docker stop / Ctrl+C
ProcessSignal.sigterm.watch().listen((_) {
killAll();
exit(0);
});
ProcessSignal.sigint.watch().listen((_) {
killAll();
exit(0);
});
}
FfmpegSession? get(String id) => _sessions[id];
/// Marks a session as recently used (call from playlist AND segment routes).
void touch(String id) => _sessions[id]?.touch();
bool contains(String id) => _sessions.containsKey(id);
/// Returns the existing healthy session or starts a new FFmpeg process.
///
/// [argsBuilder] receives the session working directory and returns the
/// FFmpeg argument list. The session directory is recreated for new
/// sessions.
Future<FfmpegSession> getOrStart({
required String id,
required bool isLive,
required String ffmpegPath,
required List<String> Function(Directory dir) argsBuilder,
}) async {
final existing = _sessions[id];
if (existing != null && !existing.exited) {
existing.touch();
return existing;
}
if (existing != null) {
// Process died: clean up before restarting
killSession(id);
}
final dir = Directory('${baseDir.path}/$id');
if (dir.existsSync()) dir.deleteSync(recursive: true);
dir.createSync(recursive: true);
final args = argsBuilder(dir);
final process = await Process.start(
ffmpegPath,
args,
workingDirectory: dir.path,
);
final session = FfmpegSession(
id: id,
process: process,
dir: dir,
isLive: isLive,
);
_sessions[id] = session;
process.stderr.transform(utf8.decoder).listen((data) {
session.recentStderr.add(data);
if (session.recentStderr.length > 20) session.recentStderr.removeAt(0);
print('[FFmpeg $id] $data');
});
process.exitCode.then((code) {
session.exited = true;
session.exitCode = code;
print('[FFmpegManager] Session $id exited with code $code');
});
return session;
}
/// Waits until the session's playlist references at least one segment.
/// Fails fast when the process dies before producing output, returning
/// the recent stderr for diagnostics.
Future<({bool ready, String? error})> waitForPlaylist(
FfmpegSession session, {
Duration timeout = const Duration(seconds: 30),
}) async {
final playlistFile = File('${session.dir.path}/playlist.m3u8');
final deadline = DateTime.now().add(timeout);
while (DateTime.now().isBefore(deadline)) {
if (session.exited && session.exitCode != 0) {
return (
ready: false,
error: 'FFmpeg exited (${session.exitCode}): '
'${session.recentStderr.join().trim()}'
);
}
if (playlistFile.existsSync() &&
playlistFile.readAsStringSync().contains('.ts')) {
return (ready: true, error: null);
}
await Future.delayed(const Duration(milliseconds: 500));
}
return (ready: false, error: 'Timeout waiting for transcoder');
}
void killSession(String id) {
final session = _sessions.remove(id);
if (session == null) return;
try {
session.process.kill(ProcessSignal.sigterm);
} catch (_) {}
try {
if (session.dir.existsSync()) session.dir.deleteSync(recursive: true);
} catch (e) {
print('[FFmpegManager] Could not delete dir for $id: $e');
}
}
void killAll() {
print('[FFmpegManager] Killing ${_sessions.length} session(s)');
for (final id in _sessions.keys.toList()) {
killSession(id);
}
_reaper?.cancel();
}
void _reap() {
final now = DateTime.now();
for (final session in _sessions.values.toList()) {
final timeout = session.isLive ? liveIdleTimeout : vodIdleTimeout;
if (session.exited || now.difference(session.lastAccess) > timeout) {
print(
'[FFmpegManager] Reaping idle session ${session.id} '
'(idle ${now.difference(session.lastAccess).inSeconds}s)',
);
killSession(session.id);
}
}
}
}
+33
View File
@@ -0,0 +1,33 @@
/// Pure decision logic for the recording scheduler, extracted for testability.
enum RecordingAction {
/// Start the recording now.
start,
/// Capacity reached but the window is still open: retry on a later tick.
wait,
/// The end time passed before the recording could start.
fail,
/// Not yet due — nothing to do.
none,
}
/// Decides what to do with a scheduled recording on a scheduler tick.
RecordingAction decideRecordingAction({
required DateTime now,
required DateTime startTime,
required DateTime endTime,
required int activeCount,
required int maxConcurrent,
}) {
final nowUtc = now.toUtc();
final startUtc = startTime.toUtc();
final endUtc = endTime.toUtc();
if (nowUtc.isAfter(endUtc)) return RecordingAction.fail;
if (!nowUtc.isAfter(startUtc)) return RecordingAction.none;
if (activeCount >= maxConcurrent) return RecordingAction.wait;
return RecordingAction.start;
}
+76 -67
View File
@@ -4,17 +4,30 @@ import 'dart:io';
import 'package:http/http.dart' as http;
import '../database/database.dart';
import '../models/recording.dart';
import '../utils/log_redactor.dart';
import 'recording_decision.dart';
import 'package:path/path.dart' as p;
class _ActiveRecording {
final Recording recording;
final Process process;
_ActiveRecording(this.recording, this.process);
}
class RecordingScheduler {
final AppDatabase _db;
Timer? _timer;
Timer? _seasonPassTimer;
bool _isRunning = false;
// Stocker l'enregistrement actuellement en cours d'exécution
Recording? _currentRecording;
Process? _ffmpegProcess;
/// Enregistrements actuellement en cours, indexés par id.
final Map<String, _ActiveRecording> _active = {};
/// Nombre maximum d'enregistrements simultanés (env MAX_CONCURRENT_RECORDINGS).
final int maxConcurrent = int.tryParse(
Platform.environment['MAX_CONCURRENT_RECORDINGS'] ?? '',
) ??
2;
// Playlist config pour les appels EPG des season passes
// Rempli depuis server.dart après initialisation
@@ -26,7 +39,8 @@ class RecordingScheduler {
void start() {
print(
'[RecordingScheduler] Démarrage du planificateur d\'enregistrements TV',
'[RecordingScheduler] Démarrage du planificateur d\'enregistrements TV '
'(max simultanés: $maxConcurrent)',
);
// Vérifier toutes les 10 secondes (pour un démarrage quasi-immédiat)
_timer = Timer.periodic(
@@ -45,7 +59,9 @@ class RecordingScheduler {
void stop() {
_timer?.cancel();
_seasonPassTimer?.cancel();
_stopCurrentRecording(reason: 'Arrêt du service planificateur');
for (final id in _active.keys.toList()) {
_stopActiveRecording(id, reason: 'Arrêt du service planificateur');
}
print('[RecordingScheduler] Arrêté');
}
@@ -58,17 +74,15 @@ class RecordingScheduler {
final now = DateTime.now().toUtc();
final recordings = _db.getAllRecordings();
print(
'[RecordingScheduler] VÉRIFICATION: now=$now recordings=${recordings.length}',
);
// Si un enregistrement est en cours, vérifier s'il doit s'arrêter
if (_currentRecording != null) {
if (now.isAfter(_currentRecording!.endTime.toUtc())) {
// Arrêter les enregistrements actifs dont l'heure de fin est passée
for (final id in _active.keys.toList()) {
final active = _active[id]!;
if (now.isAfter(active.recording.endTime.toUtc())) {
print(
'[RecordingScheduler] Fin de l\'enregistrement : ${_currentRecording!.title}',
'[RecordingScheduler] Fin de l\'enregistrement : ${active.recording.title}',
);
await _stopCurrentRecording();
_stopActiveRecording(id);
}
}
@@ -76,7 +90,7 @@ class RecordingScheduler {
for (final recording in recordings) {
// Nettoyer les enregistrements bloqués "recording" suite à un crash serveur
if (recording.status == 'recording' &&
_currentRecording?.id != recording.id) {
!_active.containsKey(recording.id)) {
print(
'[RecordingScheduler] Enregistrement orphelin détecté: ${recording.id}',
);
@@ -89,41 +103,38 @@ class RecordingScheduler {
}
if (recording.status == 'scheduled') {
final startUtc = recording.startTime.toUtc();
final endUtc = recording.endTime.toUtc();
print(
'[RecordingScheduler] "${recording.title}" start=$startUtc end=$endUtc now=$now isAfterStart=${now.isAfter(startUtc)} isBeforeEnd=${now.isBefore(endUtc)}',
final action = decideRecordingAction(
now: now,
startTime: recording.startTime,
endTime: recording.endTime,
activeCount: _active.length,
maxConcurrent: maxConcurrent,
);
// Si l'enregistrement est planifié, qu'il est temps de démarrer et qu'il n'est pas déjà fini
if (now.isAfter(startUtc) && now.isBefore(endUtc)) {
if (_currentRecording != null) {
switch (action) {
case RecordingAction.start:
print(
'[RecordingScheduler] Conflit: "${recording.title}" ne peut pas démarrer, "${_currentRecording!.title}" est en cours.',
'[RecordingScheduler] *** DÉMARRAGE DE L\'ENREGISTREMENT : ${recording.title} ***',
);
await _startRecording(recording);
case RecordingAction.wait:
// Capacité atteinte mais la fenêtre est encore ouverte :
// on garde le statut "scheduled" et on réessaiera au prochain tick.
print(
'[RecordingScheduler] Capacité max atteinte (${_active.length}/$maxConcurrent), '
'"${recording.title}" en attente.',
);
case RecordingAction.fail:
print(
'[RecordingScheduler] Enregistrement "${recording.title}" manqué (fin dépassée).',
);
_db.updateRecordingStatus(
recording.id,
'failed',
errorReason: 'Un autre enregistrement était déjà en cours.',
errorReason: 'Heure de fin dépassée avant le démarrage',
);
continue;
}
print(
'[RecordingScheduler] *** DÉMARRAGE DE L\'ENREGISTREMENT : ${recording.title} ***',
);
await _startRecording(recording);
}
// Si l'enregistrement est planifié mais que la date de fin est dépassée (loupé)
if (now.isAfter(endUtc)) {
print(
'[RecordingScheduler] Enregistrement "${recording.title}" manqué (fin dépassée).',
);
_db.updateRecordingStatus(
recording.id,
'failed',
errorReason: 'Heure de fin dépassée avant le démarrage',
);
case RecordingAction.none:
break;
}
}
}
@@ -223,7 +234,6 @@ class RecordingScheduler {
}
Future<void> _startRecording(Recording recording) async {
_currentRecording = recording;
_db.updateRecordingStatus(recording.id, 'recording');
// Un seul bloc try/catch englobant TOUT pour éviter les Unhandled exceptions
@@ -269,11 +279,12 @@ class RecordingScheduler {
];
// Créer le fichier de log de façon sécurisée (openWrite peut lancer une exception)
// Le contenu du log est exposé via l'API : ne jamais y écrire de credentials.
IOSink? logSink;
try {
logSink = File(logFilePath).openWrite();
logSink.writeln('[${DateTime.now()}] Démarrage: ${recording.title}');
logSink.writeln('URL: $streamUrl');
logSink.writeln('URL: ${LogRedactor.redactUrl(streamUrl)}');
logSink.writeln('Destination: $filePath');
} catch (logError) {
// Si on ne peut pas créer le log, on continue quand même (l'enregistrement reste prioritaire)
@@ -294,21 +305,24 @@ class RecordingScheduler {
ffmpegPath = '/usr/local/bin/ffmpeg';
}
logSink?.writeln('Commande: $ffmpegPath ${args.join(' ')}\n');
print('[RecordingScheduler] Exécution: $ffmpegPath ${args.join(' ')}');
final redactedArgs =
args.map(LogRedactor.redactUrl).join(' ');
logSink?.writeln('Commande: $ffmpegPath $redactedArgs\n');
print('[RecordingScheduler] Exécution: $ffmpegPath $redactedArgs');
_ffmpegProcess = await Process.start(ffmpegPath, args);
final process = await Process.start(ffmpegPath, args);
_active[recording.id] = _ActiveRecording(recording, process);
// Rediriger stdout/stderr dans le log
_ffmpegProcess!.stdout.listen((event) => logSink?.add(event));
_ffmpegProcess!.stderr.listen((event) => logSink?.add(event));
process.stdout.listen((event) => logSink?.add(event));
process.stderr.listen((event) => logSink?.add(event));
// Enregistrer le chemin du fichier dans la BDD
_db.updateRecordingStatus(recording.id, 'recording', filePath: filePath);
// Écouter la fin du processus FFmpeg de manière asynchrone
_ffmpegProcess!.exitCode.then((exitCode) async {
if (_currentRecording?.id == recording.id) {
process.exitCode.then((exitCode) async {
if (_active.containsKey(recording.id)) {
logSink?.writeln(
'\n[${DateTime.now()}] FFmpeg terminé avec le code $exitCode',
);
@@ -329,8 +343,7 @@ class RecordingScheduler {
errorReason: 'Erreur FFmpeg code $exitCode. Voir logs.',
);
}
_currentRecording = null;
_ffmpegProcess = null;
_active.remove(recording.id);
} else {
await logSink?.close();
}
@@ -343,34 +356,30 @@ class RecordingScheduler {
'failed',
errorReason: 'Erreur au lancement: $e',
);
_currentRecording = null;
_ffmpegProcess = null;
_active.remove(recording.id);
}
}
/// Arrêter un enregistrement en cours (appelé depuis l'API)
Future<bool> stopRecording(String id) async {
if (_ffmpegProcess != null && _currentRecording?.id == id) {
if (_active.containsKey(id)) {
print(
'[RecordingScheduler] Arrêt demandé pour: ${_currentRecording!.title}',
'[RecordingScheduler] Arrêt demandé pour: ${_active[id]!.recording.title}',
);
_ffmpegProcess!.kill(ProcessSignal.sigterm);
_db.updateRecordingStatus(id, 'completed');
_ffmpegProcess = null;
_currentRecording = null;
_stopActiveRecording(id);
return true;
}
return false; // Pas d'enregistrement actif avec cet ID
}
Future<void> _stopCurrentRecording({String? reason}) async {
if (_ffmpegProcess != null && _currentRecording != null) {
print('[RecordingScheduler] Arrêt auto: ${reason ?? "Fin programmée"}');
_ffmpegProcess!.kill(ProcessSignal.sigterm);
_db.updateRecordingStatus(_currentRecording!.id, 'completed');
_ffmpegProcess = null;
_currentRecording = null;
void _stopActiveRecording(String id, {String? reason}) {
final active = _active.remove(id);
if (active == null) return;
if (reason != null) {
print('[RecordingScheduler] Arrêt: $reason (${active.recording.title})');
}
active.process.kill(ProcessSignal.sigterm);
_db.updateRecordingStatus(id, 'completed');
}
Future<void> _checkDiskSpaceAndRotate(Directory dir) async {
+33
View File
@@ -0,0 +1,33 @@
import 'package:test/test.dart';
import '../utils/log_redactor.dart';
void main() {
group('LogRedactor.redactUrl', () {
test('masks credentials in query strings', () {
final out = LogRedactor.redactUrl(
'http://srv:8080/player_api.php?username=john&password=hunter2&action=get_live_streams',
);
expect(out, isNot(contains('john')));
expect(out, isNot(contains('hunter2')));
expect(out, contains('username=***'));
expect(out, contains('password=***'));
expect(out, contains('action=get_live_streams'));
});
test('masks credentials in live/movie/series path segments', () {
for (final kind in ['live', 'movie', 'series']) {
final out = LogRedactor.redactUrl(
'http://srv:8080/$kind/john/hunter2/12345.ts',
);
expect(out, isNot(contains('john')), reason: kind);
expect(out, isNot(contains('hunter2')), reason: kind);
expect(out, contains('/$kind/***/***/12345.ts'), reason: kind);
}
});
test('leaves URLs without credentials untouched', () {
const url = 'http://srv:8080/images/logo.png';
expect(LogRedactor.redactUrl(url), url);
});
});
}
+37
View File
@@ -0,0 +1,37 @@
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:test/test.dart';
import '../utils/password_hasher.dart';
void main() {
group('PasswordHasher', () {
test('bcrypt roundtrip verifies the original password', () {
final hash = PasswordHasher.hash('s3cret-Pass!');
expect(hash, startsWith(r'$2'));
expect(PasswordHasher.verify('s3cret-Pass!', hash), isTrue);
expect(PasswordHasher.verify('wrong', hash), isFalse);
});
test('legacy unsalted SHA-256 hashes still verify', () {
final legacy = sha256.convert(utf8.encode('admin')).toString();
expect(PasswordHasher.verify('admin', legacy), isTrue);
expect(PasswordHasher.verify('not-admin', legacy), isFalse);
});
test('isLegacy detects SHA-256 hex digests only', () {
final legacy = sha256.convert(utf8.encode('admin')).toString();
expect(PasswordHasher.isLegacy(legacy), isTrue);
expect(PasswordHasher.isLegacy(PasswordHasher.hash('admin')), isFalse);
});
test('rehash produces a non-legacy hash', () {
final rehashed = PasswordHasher.hash('admin');
expect(PasswordHasher.isLegacy(rehashed), isFalse);
expect(PasswordHasher.verify('admin', rehashed), isTrue);
});
test('malformed hash never verifies', () {
expect(PasswordHasher.verify('x', 'garbage-hash'), isFalse);
});
});
}
+73
View File
@@ -0,0 +1,73 @@
import 'package:test/test.dart';
import '../services/recording_decision.dart';
void main() {
final now = DateTime.utc(2026, 6, 10, 12, 0);
group('decideRecordingAction', () {
test('starts when due and capacity available', () {
expect(
decideRecordingAction(
now: now,
startTime: now.subtract(const Duration(minutes: 1)),
endTime: now.add(const Duration(hours: 1)),
activeCount: 0,
maxConcurrent: 2,
),
RecordingAction.start,
);
});
test('waits (keeps scheduled) when at capacity but window still open', () {
expect(
decideRecordingAction(
now: now,
startTime: now.subtract(const Duration(minutes: 1)),
endTime: now.add(const Duration(hours: 1)),
activeCount: 2,
maxConcurrent: 2,
),
RecordingAction.wait,
);
});
test('fails when the end time has passed', () {
expect(
decideRecordingAction(
now: now,
startTime: now.subtract(const Duration(hours: 2)),
endTime: now.subtract(const Duration(minutes: 5)),
activeCount: 0,
maxConcurrent: 2,
),
RecordingAction.fail,
);
});
test('does nothing before the start time', () {
expect(
decideRecordingAction(
now: now,
startTime: now.add(const Duration(minutes: 30)),
endTime: now.add(const Duration(hours: 1)),
activeCount: 0,
maxConcurrent: 2,
),
RecordingAction.none,
);
});
test('second overlapping recording starts when maxConcurrent is 2', () {
expect(
decideRecordingAction(
now: now,
startTime: now.subtract(const Duration(minutes: 1)),
endTime: now.add(const Duration(hours: 1)),
activeCount: 1,
maxConcurrent: 2,
),
RecordingAction.start,
);
});
});
}
+40
View File
@@ -0,0 +1,40 @@
import 'package:test/test.dart';
import '../utils/safe_path.dart';
void main() {
group('SafePath.resolveWithin', () {
const base = '/app/recordings';
test('accepts files inside the base directory', () {
expect(
SafePath.resolveWithin(base, '/app/recordings/show.log'),
isNotNull,
);
expect(SafePath.resolveWithin(base, 'show.log'), isNotNull);
expect(
SafePath.resolveWithin(base, '/app/recordings/sub/dir/file.log'),
isNotNull,
);
});
test('rejects .. traversal', () {
expect(
SafePath.resolveWithin(base, '/app/recordings/../data/xtremflow.db'),
isNull,
);
expect(SafePath.resolveWithin(base, '../../etc/passwd'), isNull);
});
test('rejects absolute paths outside the base', () {
expect(SafePath.resolveWithin(base, '/etc/passwd'), isNull);
expect(SafePath.resolveWithin(base, '/app/data/xtremflow.db'), isNull);
});
test('rejects sibling directories with a shared prefix', () {
expect(
SafePath.resolveWithin(base, '/app/recordings-evil/file.log'),
isNull,
);
});
});
}
+29
View File
@@ -0,0 +1,29 @@
import 'package:test/test.dart';
import '../api/proxy_handler.dart';
void main() {
group('isForbiddenProxyHost', () {
test('blocks loopback', () {
expect(isForbiddenProxyHost('127.0.0.1'), isTrue);
expect(isForbiddenProxyHost('localhost'), isTrue);
expect(isForbiddenProxyHost('::1'), isTrue);
});
test('blocks private LAN ranges', () {
expect(isForbiddenProxyHost('10.0.0.5'), isTrue);
expect(isForbiddenProxyHost('172.16.0.1'), isTrue);
expect(isForbiddenProxyHost('172.31.255.255'), isTrue);
expect(isForbiddenProxyHost('192.168.1.10'), isTrue);
});
test('blocks link-local / cloud metadata range', () {
expect(isForbiddenProxyHost('169.254.169.254'), isTrue);
});
test('allows public IPs and hostnames', () {
expect(isForbiddenProxyHost('8.8.8.8'), isFalse);
expect(isForbiddenProxyHost('172.32.0.1'), isFalse);
expect(isForbiddenProxyHost('cdn.example.com'), isFalse);
});
});
}
+29
View File
@@ -0,0 +1,29 @@
/// Redacts IPTV credentials from URLs before they reach logs.
///
/// Xtream Codes embeds credentials both in query strings
/// (`?username=u&password=p`) and in path segments
/// (`/live/<user>/<pass>/<id>.ts`, `/movie/...`, `/series/...`).
class LogRedactor {
static final RegExp _queryCreds = RegExp(
r'(username|password)=[^&\s]*',
caseSensitive: false,
);
static final RegExp _pathCreds = RegExp(
r'/(live|movie|series)/[^/\s]+/[^/\s]+/',
caseSensitive: false,
);
/// Returns [url] with credentials replaced by `***`.
static String redactUrl(String url) {
var redacted = url.replaceAllMapped(
_queryCreds,
(m) => '${m.group(1)}=***',
);
redacted = redacted.replaceAllMapped(
_pathCreds,
(m) => '/${m.group(1)}/***/***/',
);
return redacted;
}
}
+25 -7
View File
@@ -1,17 +1,35 @@
import 'dart:convert';
import 'package:bcrypt/bcrypt.dart';
import 'package:crypto/crypto.dart';
class PasswordHasher {
/// Hash a password using SHA256 (simple implementation)
/// Note: In production, use a proper bcrypt implementation
/// Cost factor 10: ~100-300ms per hash in pure Dart, acceptable for login frequency.
static const int _bcryptRounds = 10;
/// Legacy hashes are unsalted SHA-256 hex digests (64 hex chars).
static final RegExp _legacyPattern = RegExp(r'^[0-9a-f]{64}$');
/// Hash a password using bcrypt (salt embedded in the result).
static String hash(String password) {
final bytes = utf8.encode(password);
final digest = sha256.convert(bytes);
return digest.toString();
return BCrypt.hashpw(password, BCrypt.gensalt(logRounds: _bcryptRounds));
}
/// Verify a password against a hash
/// Verify a password against a stored hash.
/// Supports legacy unsalted SHA-256 hashes for accounts created before
/// the bcrypt migration; those are rehashed lazily on successful login.
static bool verify(String password, String hash) {
return PasswordHasher.hash(password) == hash;
if (isLegacy(hash)) {
final digest = sha256.convert(utf8.encode(password)).toString();
return digest == hash;
}
try {
return BCrypt.checkpw(password, hash);
} catch (_) {
// Malformed hash (neither legacy SHA-256 nor valid bcrypt)
return false;
}
}
/// True if the stored hash uses the legacy unsalted SHA-256 scheme.
static bool isLegacy(String hash) => _legacyPattern.hasMatch(hash);
}
+18
View File
@@ -0,0 +1,18 @@
import 'package:path/path.dart' as p;
/// Path validation helpers to prevent directory traversal.
class SafePath {
/// Resolves [candidate] and returns it only if it stays inside [baseDir].
/// Returns null when the path escapes the base directory (e.g. via `..`
/// segments or an absolute path pointing elsewhere).
static String? resolveWithin(String baseDir, String candidate) {
final base = p.normalize(p.absolute(baseDir));
final resolved = p.normalize(
p.isAbsolute(candidate) ? candidate : p.join(base, candidate),
);
if (resolved == base || p.isWithin(base, resolved)) {
return resolved;
}
return null;
}
}