From 37753c63963e7d349e35b1ef397173058e10ed37 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Fri, 16 Oct 2026 23:51:19 +0300 Subject: [PATCH 01/17] fix(ads): pass the rewarded ad's nonce through to connect With ads enabled the SSV nonce and the nonce the connect flow waited for were minted separately, so the client rejected the very session the ad had just created and failed with "Session not activated". - showAd() returns the nonce it put in the SSV custom_data (null on no reward) - fetchConfigDirectly({adNonce, resume}) replaces skipAdBypass: a real ad waits for exactly that nonce and polls ~36 s for Google's callback, the bypass path mints its own, and resume re-attaches to the session the device already owns - SOCKS5 "Reconnect" uses resume: true instead of requesting a new session Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 15 ++++++++ lib/components/connect_button.dart | 6 +-- lib/components/support_button.dart | 2 +- lib/logic/ad_manager.dart | 35 ++++++++--------- lib/logic/hivemind_service.dart | 38 +++++++++++-------- lib/logic/vpn_connection.dart | 5 ++- .../settings/in_settings/connection_mode.dart | 10 ++--- 7 files changed, 68 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fda24c1..4f4f6ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,21 @@ Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH --- +## [Unreleased] + +### Fixed +- **Rewarded ads no longer break connecting.** With ads enabled, the ad's + server-side-verification nonce and the nonce the connect flow waited for were + minted separately, so the client rejected the very session the ad created and + failed with "Session not activated". The ad's nonce is now passed through to + the connect call, the fake bypass callback is skipped when a real ad was + watched, and the client polls longer (~36 s) for Google's callback. +- **SOCKS5 "Reconnect" re-attaches to the current session** instead of + requesting a new one, so repairing a lost proxy no longer needs (or grants) + a fresh session. + +--- + ## [3.3.6] — 2026-10-08 ### Fixed diff --git a/lib/components/connect_button.dart b/lib/components/connect_button.dart index 60227d2..93cc9f9 100644 --- a/lib/components/connect_button.dart +++ b/lib/components/connect_button.dart @@ -95,10 +95,10 @@ class _ConnectButtonState extends State setState(() => _busy = true); try { - final adWatched = await ad.showAd('main'); - if (!adWatched && AdManager.adsEnabled) return; + final adNonce = await ad.showAd('main'); + if (adNonce == null && AdManager.adsEnabled) return; - final ok = await vpn.connect(); + final ok = await vpn.connect(adNonce: adNonce); if (ok) { await timer.start(); HapticSettings.success(); diff --git a/lib/components/support_button.dart b/lib/components/support_button.dart index 4565016..ac1d3ab 100644 --- a/lib/components/support_button.dart +++ b/lib/components/support_button.dart @@ -31,7 +31,7 @@ class _SupportButtonState extends State { setState(() => _busy = true); try { - final rewarded = await ad.showAd('support'); + final rewarded = await ad.showAd('support') != null; if (rewarded) { await timer.markSupportRewardClaimed(); await timer.syncNow(); diff --git a/lib/logic/ad_manager.dart b/lib/logic/ad_manager.dart index 51a8fe7..7e0d225 100644 --- a/lib/logic/ad_manager.dart +++ b/lib/logic/ad_manager.dart @@ -1,6 +1,5 @@ import 'dart:async'; import 'dart:convert'; -import 'dart:math'; import 'package:flutter/foundation.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; import 'package:revoltvpn/logic/crypto_service.dart'; @@ -97,13 +96,20 @@ class AdManager extends ChangeNotifier { // ── Show ad (or debug bypass) ───────────────────────────────────── - Future showAd(String adType) async { - // Debug bypass: fire fake AdMob callback so support ads work in dev. - // The server's ADMOB_BYPASS must be True for this to succeed. - if (!adsEnabled && kDebugMode) { + // Returns the nonce carried in the SSV custom_data when the reward was + // earned, null otherwise. The main flow passes it to vpn.connect(adNonce:) + // so the client waits for the session this ad created — minting a second + // nonce there is what broke every connect once ads were on. + Future showAd(String adType) async { + if (!adsEnabled) { + // Main connect: no ad to show — HivemindService.fetchConfigDirectly() + // fires the server-gated bypass itself (rule 87). + if (adType != 'support' || !kDebugMode) return null; + + // Debug bypass: fire fake AdMob callback so support ads work in dev. + // The server's ADMOB_BYPASS must be True for this to succeed. final deviceId = await CryptoService.getDeviceId(); - final nonce = '${Random().nextInt(0x7FFFFFFF)}-${DateTime.now().millisecondsSinceEpoch}'; - HivemindService.setExpectedNonce(nonce); + final nonce = HivemindService.newNonce(); try { final customData = jsonEncode({ 'device_id': deviceId, @@ -115,29 +121,24 @@ class AdManager extends ChangeNotifier { '?signature=test&key_id=test' '&custom_data=${Uri.encodeComponent(customData)}'); await HivemindService.directGet(fakeUrl, timeout: const Duration(seconds: 8)); - return true; + return nonce; } catch (_) { - return false; + return null; } } - if (!adsEnabled) return false; - await ensureSdkInitialized(); if (!_isAdLoaded || _rewardedAd == null) { final loaded = await preloadAd(); if (!loaded || _rewardedAd == null) { debugPrint('[AdManager] Cannot show ad, failed to load.'); - return false; + return null; } } final deviceId = await CryptoService.getDeviceId(); - - final nonce = '${Random().nextInt(0x7FFFFFFF)}-${DateTime.now().millisecondsSinceEpoch}'; - HivemindService.setExpectedNonce(nonce); - debugPrint('[AdManager] Ad nonce: $nonce'); + final nonce = HivemindService.newNonce(); final ssvOptions = ServerSideVerificationOptions( customData: jsonEncode({ @@ -182,7 +183,7 @@ class AdManager extends ChangeNotifier { }, ); - return rewardCompleter.future; + return await rewardCompleter.future ? nonce : null; } @override diff --git a/lib/logic/hivemind_service.dart b/lib/logic/hivemind_service.dart index 3791d2b..ac1daea 100644 --- a/lib/logic/hivemind_service.dart +++ b/lib/logic/hivemind_service.dart @@ -81,13 +81,19 @@ class HivemindService { _expectedNonce = null; } - static void setExpectedNonce(String nonce) { - _expectedNonce = nonce; - } - + // Fetches this device's VLESS URL. Three ways in: + // adNonce != null — a real rewarded ad was watched; its SSV custom_data + // carried this nonce, so wait for a session holding it. + // Google's SSV callback can lag, so poll longer. + // resume == true — re-attach to the session already granted (mode-switch + // reconnect in connection_mode.dart). No ad, no bypass, + // any nonce accepted — device_id already owns it. + // neither — ads disabled: mint a nonce and fire the server-gated + // ADMOB_BYPASS callback (rule 87). static Future fetchConfigDirectly({ void Function(int attempt, int total)? onAttempt, - bool skipAdBypass = false, + String? adNonce, + bool resume = false, }) async { // Capture the generation before the first await. Otherwise a disconnect // that lands while secure storage is resolving the device ID can be lost @@ -96,15 +102,15 @@ class HivemindService { final deviceId = await CryptoService.getDeviceId(); _throwIfCancelled(callId); - final nonce = _newNonce(); + final nonce = resume ? null : (adNonce ?? newNonce()); _expectedNonce = nonce; - if (!skipAdBypass) { - await _runConfiguredBypass(deviceId, nonce); + if (!resume && adNonce == null) { + await _runConfiguredBypass(deviceId, nonce!); _throwIfCancelled(callId); } - const maxAttempts = 5; + final maxAttempts = adNonce != null ? 10 : 5; for (var attempt = 1; attempt <= maxAttempts; attempt++) { _throwIfCancelled(callId); onAttempt?.call(attempt, maxAttempts); @@ -122,7 +128,9 @@ class HivemindService { } if (attempt < maxAttempts) { - await Future.delayed(_pollBackoff[attempt - 1]); + await Future.delayed( + _pollBackoff[min(attempt - 1, _pollBackoff.length - 1)], + ); _throwIfCancelled(callId); } } @@ -142,7 +150,7 @@ class HivemindService { } } - static String _newNonce() { + static String newNonce() { final random = Random.secure(); final high = random.nextInt(0x7FFFFFFF); final low = random.nextInt(0x7FFFFFFF); @@ -161,9 +169,10 @@ class HivemindService { } } + // nonce == null accepts whatever nonce the server holds (resume path). static Future<_HivemindSessionConfig?> _fetchActiveSession( String deviceId, - String nonce, + String? nonce, ) async { final statusUri = _publicUrl('/session/status').replace( queryParameters: {'device_id': deviceId}, @@ -175,9 +184,8 @@ class HivemindService { if (decoded is! Map) return null; final serverNonce = decoded['nonce']; - if (_expectedNonce != nonce || - serverNonce is! String || - serverNonce != nonce) { + if (_expectedNonce != nonce) return null; + if (nonce != null && (serverNonce is! String || serverNonce != nonce)) { return null; } diff --git a/lib/logic/vpn_connection.dart b/lib/logic/vpn_connection.dart index 17368e4..44d0e30 100644 --- a/lib/logic/vpn_connection.dart +++ b/lib/logic/vpn_connection.dart @@ -200,7 +200,7 @@ class VpnConnection extends ChangeNotifier { } } - Future connect({bool skipAdBypass = false}) async { + Future connect({String? adNonce, bool resume = false}) async { if (_disposed || _userDisconnecting || _status == VpnStatus.connected || @@ -254,7 +254,8 @@ class VpnConnection extends ChangeNotifier { String realUrl; try { realUrl = await HivemindService.fetchConfigDirectly( - skipAdBypass: skipAdBypass, + adNonce: adNonce, + resume: resume, onAttempt: (attempt, total) { if (!_isCurrentConnect(connectEpoch)) return; _setStatus( diff --git a/lib/screens/settings/in_settings/connection_mode.dart b/lib/screens/settings/in_settings/connection_mode.dart index 46519d7..c638e66 100644 --- a/lib/screens/settings/in_settings/connection_mode.dart +++ b/lib/screens/settings/in_settings/connection_mode.dart @@ -67,10 +67,10 @@ class _ConnectionModeTileState extends State { widget.onChanged?.call(next); } - /// Recovers from an orphaned proxy: tear the runtime down and start a fresh - /// session so a readable set of credentials exists again. No rewarded ad — - /// the user is repairing a connection they already paid for, not opening a - /// new one. + // Recovers from an orphaned proxy: tear the runtime down and re-attach to + // the session this device already holds (connect(resume: true)), so a + // readable set of credentials exists again. No rewarded ad and no new + // session — the user is repairing a connection they already paid for. Future _reconnect() async { if (_reconnecting) return; final vpn = context.read(); @@ -80,7 +80,7 @@ class _ConnectionModeTileState extends State { try { await timer.disconnect(); if (!mounted) return; - if (await vpn.connect()) { + if (await vpn.connect(resume: true)) { if (!mounted) return; await timer.start(); } From 742f37683ee3a32ebdece497b940cb25c04fbf29 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 00:02:20 +0300 Subject: [PATCH 02/17] feat(session): warn before a session ends and say when protection stops Review findings #1-#3 in internal/APP_REVIEW_2026-10-16.md: every session end dropped the user onto their real IP with no warning, and the app showed no errors at all. - RevoltAlerts (vendored runtime) owns both alerts: a high-importance channel, ids 2 and 3, posted from whichever process is alive - XrayVPNService schedules a 5-minute warning off the deadline it already holds, best effort (a warning that cannot be armed never stops a tunnel), with its own request code so it cannot clobber the expiry alarm - the warning intent is handled above the command dispatch: without that it would fall through to the final else and stop the tunnel 5 minutes early - SessionTimer._doDisconnect takes endedMessage: set for ends the user did not ask for, which both posts the alert and gives the UI a sentence - the API being unreachable no longer disconnects a working tunnel; it is a display state now, with expiry still enforced natively and server-side - status_bar.dart renders connect errors, connecting progress and the session-end reason flutter analyze clean; debug APK builds (Kotlin compiles). Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 18 +++ .../kotlin/com/paladinvpn/app/MainActivity.kt | 26 +++- lib/components/status_bar.dart | 57 +++++++ lib/logic/notification_service.dart | 12 ++ lib/logic/session_timer.dart | 64 +++++--- .../xray/service/XrayVPNService.kt | 107 +++++++++++++ .../flutter_vless/xray/utils/RevoltAlerts.kt | 143 ++++++++++++++++++ 7 files changed, 401 insertions(+), 26 deletions(-) create mode 100644 local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f4f6ea..2ca2eae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,24 @@ Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH ## [Unreleased] +### Added +- **Five-minute warning before a session ends.** The VPN service schedules it + off the same deadline it already enforces, so the warning still arrives when + the app is closed, and a support top-up moves it with the deadline. +- **"Disconnected — not protected" notification** whenever a session ends for + any reason other than you tapping disconnect: expiry, the data limit, the + server ending the session, or the tunnel stopping on its own. +- **The app now shows what went wrong.** Connect errors, the reason a session + ended, and progress while connecting appear under the status bar instead of + the button silently going back to idle. + +### Changed +- **A control-plane outage no longer tears down a working tunnel.** The app used + to disconnect itself after about two minutes of failed status polls, putting + you back on your real IP; it now keeps the tunnel up and shows + "Can't reach the server — still connected". Expiry is still enforced by the + VPN service's own deadline and by the server. + ### Fixed - **Rewarded ads no longer break connecting.** With ads enabled, the ad's server-side-verification nonce and the nonce the connect flow waited for were diff --git a/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt b/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt index 07ca37d..ac30ff4 100644 --- a/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt +++ b/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt @@ -20,6 +20,7 @@ import android.os.VibratorManager import android.provider.Settings import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat +import com.github.tfox.flutter_vless.xray.utils.RevoltAlerts import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.EventChannel @@ -61,14 +62,23 @@ class MainActivity : FlutterActivity() { MethodChannel(flutterEngine.dartExecutor.binaryMessenger, notificationChannel) .setMethodCallHandler { call, result -> - if (call.method == "updateNotificationText") { - val text = call.argument("text") ?: "" - val title = call.argument("title") ?: "Revolt VPN" - val action = call.argument("disconnectLabel") ?: "Disconnect" - updateVpnNotification(title, text, action) - result.success(null) - } else { - result.notImplemented() + when (call.method) { + "updateNotificationText" -> { + val text = call.argument("text") ?: "" + val title = call.argument("title") ?: "Revolt VPN" + val action = call.argument("disconnectLabel") ?: "Disconnect" + updateVpnNotification(title, text, action) + result.success(null) + } + // Session ends only Dart can see (cap exhausted, server + // ended the session, VPN error). The VPN service posts the + // same alert for its own deadline, where this process may + // already be gone. RevoltAlerts owns both. + "showDisconnectedAlert" -> { + RevoltAlerts.postDisconnected(this) + result.success(null) + } + else -> result.notImplemented() } } diff --git a/lib/components/status_bar.dart b/lib/components/status_bar.dart index 707bb52..a539648 100644 --- a/lib/components/status_bar.dart +++ b/lib/components/status_bar.dart @@ -5,6 +5,44 @@ import 'package:revoltvpn/logic/app_colors.dart'; import 'package:revoltvpn/logic/session_timer.dart'; import 'package:revoltvpn/logic/vpn_connection.dart'; +// Nothing rendered the connection's own messages, so they are collected here +// in one place: whatever the user most needs to know right now, and whether it +// is a problem (red) or just progress (dim). +class _StatusDetail { + const _StatusDetail(this.text, {this.isProblem = false}); + + final String text; + final bool isProblem; +} + +_StatusDetail? _detail(VpnConnection vpn, SessionTimer timer) { + final error = vpn.errorMessage; + if (error != null && error.isNotEmpty) { + return _StatusDetail(error.replaceAll('\n', ' '), isProblem: true); + } + + if (vpn.status == VpnStatus.connecting || + vpn.status == VpnStatus.disconnecting) { + return _StatusDetail(vpn.statusMessage); + } + + // The tunnel still carries traffic; only the control plane is missing, so + // this is a warning, not a disconnect (review #2). + if (vpn.status == VpnStatus.connected && timer.serverUnreachable) { + return const _StatusDetail( + 'Can\'t reach the server — still connected', + isProblem: true, + ); + } + + if (vpn.status != VpnStatus.connected) { + final ended = timer.lastEndMessage; + if (ended != null) return _StatusDetail(ended, isProblem: true); + } + + return null; +} + class StatusBar extends StatelessWidget { const StatusBar({super.key}); @@ -24,6 +62,8 @@ class StatusBar extends StatelessWidget { ? 'Connecting…' : (vpn.serverReachable ? 'Ready' : 'Offline')); + final detail = _detail(vpn, timer); + return Padding( padding: const EdgeInsets.symmetric(horizontal: 24), child: Column( @@ -96,6 +136,23 @@ class StatusBar extends StatelessWidget { ], ), ), + // Until this existed, a failed connect, an expired session and a + // cap kill all just turned the button back to idle - the user + // could not tell protected from unprotected (review #3). + if (detail != null) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Text( + detail.text, + textAlign: TextAlign.center, + style: TextStyle( + color: detail.isProblem + ? AppColors.red + : AppColors.textDim, + fontSize: 11, + ), + ), + ), ], ), ); diff --git a/lib/logic/notification_service.dart b/lib/logic/notification_service.dart index 88f46f1..c22a04a 100644 --- a/lib/logic/notification_service.dart +++ b/lib/logic/notification_service.dart @@ -32,6 +32,18 @@ class NotificationService { } } + // Posts the "disconnected - not protected" alert for a session end the user + // did not ask for. The native service posts the same alert (same id) when + // its own deadline fires, because by then this process may be gone; a double + // post replaces rather than stacks. + static Future showDisconnectedAlert() async { + try { + await _channel.invokeMethod('showDisconnectedAlert'); + } catch (_) { + // Informational only - never worth failing a disconnect over. + } + } + /// Forces the next connect to re-post even if the countdown resumes on the /// same value. static void reset() => _lastText = null; diff --git a/lib/logic/session_timer.dart b/lib/logic/session_timer.dart index 035775d..c205da0 100644 --- a/lib/logic/session_timer.dart +++ b/lib/logic/session_timer.dart @@ -36,8 +36,6 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { static const FlutterSecureStorage _supportStorage = FlutterSecureStorage(); static const int _maxConsecutiveFailures = 3; - static const int _maxOfflineSeconds = 120; - int _offlineSeconds = 0; static const int _pollIntervalSeconds = 60; static const int _backgroundPollIntervalSeconds = 60; @@ -67,6 +65,17 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { int get usedBytes => _usedBytes; double get currentSpeedKBps => _currentSpeedKBps; + // True once the control plane has missed enough polls in a row to be worth + // telling the user about. It is a display state only: a tunnel that still + // carries traffic is never torn down because the API is unreachable (the + // native deadline and the server both still enforce expiry). + bool get serverUnreachable => _consecutiveFailures >= _maxConsecutiveFailures; + + // Why the last session ended, when the user did not end it themselves. + // Cleared on the next connect. Rendered by status_bar.dart. + String? _lastEndMessage; + String? get lastEndMessage => _lastEndMessage; + String get formatted { final h = (_remainingSeconds ~/ 3600).toString().padLeft(2, '0'); final m = ((_remainingSeconds % 3600) ~/ 60).toString().padLeft(2, '0'); @@ -124,11 +133,17 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { if (!hadActiveSession || _isDisconnecting) return; if (vpnConnection.status == VpnStatus.error) { - unawaited(_doDisconnect('VPN entered error state')); + unawaited(_doDisconnect( + 'VPN entered error state', + endedMessage: 'The tunnel stopped. You are not protected.', + )); return; } if (vpnConnection.status == VpnStatus.disconnected) { + // No alert here. The runtime going away covers both the native deadline + // (which posts the alert itself, from a process that outlives this one) + // and the notification's Disconnect action, which the user tapped. unawaited(_doDisconnect('VPN tunnel dropped')); } } @@ -145,9 +160,9 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { _tickCount = 0; _hasSyncedOnce = false; _consecutiveFailures = 0; - _offlineSeconds = 0; _isDisconnecting = false; _appBackgrounded = false; + _lastEndMessage = null; NotificationService.reset(); _supportStateEpoch++; @@ -169,16 +184,11 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { _reconcileElapsedTime(); } - if (_consecutiveFailures >= _maxConsecutiveFailures) { - _offlineSeconds++; - if (_offlineSeconds >= _maxOfflineSeconds) { - unawaited(_doDisconnect('Server unreachable')); - return; - } - } - if (_hasSyncedOnce && _remainingSeconds <= 0) { - unawaited(_doDisconnect('Session expired')); + unawaited(_doDisconnect( + 'Session expired', + endedMessage: 'Your session ended. You are not protected.', + )); return; } @@ -219,12 +229,17 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { await _doDisconnect(reason); } - Future _doDisconnect(String reason) async { + // endedMessage is the one sentence the UI shows after an end the user did + // not ask for, and its presence is also what posts the "not protected" + // notification. Both exist so nobody is left on their real IP without being + // told. A user-requested disconnect passes nothing. + Future _doDisconnect(String reason, {String? endedMessage}) async { if (_isDisconnecting) return; _isDisconnecting = true; _sessionEpoch++; debugPrint('[Timer] Disconnecting: $reason'); + _lastEndMessage = endedMessage; _timer?.cancel(); _timer = null; _currentSpeedKBps = 0.0; @@ -237,6 +252,9 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { notifyListeners(); await vpnConnection.disconnect(); + if (endedMessage != null) { + unawaited(NotificationService.showDisconnectedAlert()); + } _isDisconnecting = false; notifyListeners(); @@ -282,7 +300,11 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { return; } if (!activeValue) { - await _doDisconnect('Server ended session'); + await _doDisconnect( + 'Server ended session', + endedMessage: + 'The server ended your session. You are not protected.', + ); return; } @@ -313,7 +335,10 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { _sinceLastSuccessfulSync = Stopwatch()..start(); if (data['cap_exhausted'] == true) { - await _doDisconnect('Data cap reached'); + await _doDisconnect( + 'Data cap reached', + endedMessage: 'Data limit reached. You are not protected.', + ); return; } @@ -322,12 +347,15 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { await vpnConnection.setNativeSessionDeadline(_remainingAtLastSync); } catch (e) { debugPrint('[Timer] Failed to arm native session deadline: $e'); - await _doDisconnect('Native session deadline unavailable'); + await _doDisconnect( + 'Native session deadline unavailable', + endedMessage: + 'Could not arm the session timer. You are not protected.', + ); return; } if (epoch != _sessionEpoch || _isDisconnecting) return; _consecutiveFailures = 0; - _offlineSeconds = 0; _hasSyncedOnce = true; notifyListeners(); } else { diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt index 68b694e..bedb116 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt @@ -16,6 +16,7 @@ import android.util.Log import com.github.tfox.flutter_vless.xray.core.XrayCoreManager import com.github.tfox.flutter_vless.xray.dto.XrayConfig import com.github.tfox.flutter_vless.xray.utils.AppConfigs +import com.github.tfox.flutter_vless.xray.utils.RevoltAlerts import org.json.JSONObject import java.io.File @@ -66,6 +67,14 @@ class XrayVPNService : VpnService() { return START_NOT_STICKY } + // Must stay above the command handling below: an intent carrying no + // COMMAND falls through to the final else and stops a live tunnel - in + // this case five minutes early, which is what it warns about. + if (intent.getBooleanExtra(EXTRA_SESSION_WARNING, false)) { + handleSessionWarningAlarm(intent.getStringExtra("RUNTIME_TOKEN").orEmpty()) + return START_NOT_STICKY + } + val command = if (Build.VERSION.SDK_INT >= 33) { intent.getSerializableExtra("COMMAND", AppConfigs.V2RAY_SERVICE_COMMANDS::class.java) } else { @@ -121,6 +130,7 @@ class XrayVPNService : VpnService() { XrayCoreManager.stopCore(this) } cleanup(clearDeadline = true) + RevoltAlerts.cancelAll(this) shuttingDownIntentionally = false currentConfig = config @@ -451,17 +461,81 @@ class XrayVPNService : VpnService() { return } + armExpiryWarning(config.RUNTIME_TOKEN, epochDeadline) + deadlineHandler.removeCallbacks(sessionDeadlineRunnable) if (delayMs == 0L) deadlineHandler.post(sessionDeadlineRunnable) else deadlineHandler.postDelayed(sessionDeadlineRunnable, delayMs) } + // Schedules the five-minute warning off the same deadline the expiry alarm + // holds. Unlike the deadline this is advisory: a warning that cannot be + // scheduled must never stop a working tunnel, so nothing here fails closed. + // Dart re-pushes the deadline on every sync, so this runs about once a minute. + private fun armExpiryWarning(runtimeToken: String, expiresAtEpochMs: Long) { + cancelSessionWarningAlarm() + if (runtimeToken.isEmpty()) return + + val warnAt = expiresAtEpochMs - RevoltAlerts.WARNING_LEAD_MS + // Deadline already inside the warning window (or past): either the alarm + // has fired and its notification should stay up, or this is the short + // bootstrap deadline at connect, which must not warn at all. + if (warnAt <= System.currentTimeMillis()) return + + // More than the lead away, so any warning on screen belongs to an older + // deadline - a support top-up just pushed it out. + RevoltAlerts.cancelExpiryWarning(this) + + try { + val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager + val pendingIntent = sessionWarningPendingIntent(runtimeToken) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + // Inexact on purpose: minute-level slop is fine for a warning, + // and it keeps this off the SCHEDULE_EXACT_ALARM path. + alarmManager.setAndAllowWhileIdle( + AlarmManager.RTC_WAKEUP, + warnAt, + pendingIntent, + ) + } else { + alarmManager.set(AlarmManager.RTC_WAKEUP, warnAt, pendingIntent) + } + } catch (e: Exception) { + Log.w(TAG, "Failed to schedule session-expiry warning", e) + } + } + + private fun handleSessionWarningAlarm(alarmToken: String) { + val config = currentConfig + if (config == null) { + // The alarm woke a service process with no live runtime; there is + // no session left to warn about. + stopSelf() + return + } + if (alarmToken.isEmpty() || alarmToken != config.RUNTIME_TOKEN) { + Log.w(TAG, "Ignoring session warning for stale runtime generation") + return + } + + val deadline = sessionDeadlineElapsed ?: return + val remaining = deadline - SystemClock.elapsedRealtime() + if (remaining <= 0L || remaining > RevoltAlerts.WARNING_LEAD_MS + WARNING_SLACK_MS) { + Log.w(TAG, "Ignoring session warning outside the warning window") + return + } + + RevoltAlerts.postExpiryWarning(this) + } + private fun clearSessionDeadline() { deadlineHandler.removeCallbacks(sessionDeadlineRunnable) sessionDeadlineElapsed = null sessionDeadlineToken = null clearPersistedDeadline() cancelSessionExpiryAlarm() + cancelSessionWarningAlarm() + RevoltAlerts.cancelExpiryWarning(this) } private fun enforceSessionDeadline() { @@ -476,6 +550,10 @@ class XrayVPNService : VpnService() { } Log.w(TAG, "Native session deadline expired; stopping runtime fail-closed") stopAll(token) + // Only the deadline paths post this natively. A STOP_SERVICE command + // cannot tell a user tap from a Dart-side session end, so Dart posts for + // its own reasons; the shared id means a double post just replaces. + RevoltAlerts.postDisconnected(this) } private fun updateSessionDeadline(intent: Intent) { @@ -561,9 +639,12 @@ class XrayVPNService : VpnService() { } else { clearPersistedDeadline() cancelSessionExpiryAlarm() + cancelSessionWarningAlarm() + RevoltAlerts.cancelExpiryWarning(this) stopForeground(true) stopSelf() } + RevoltAlerts.postDisconnected(this) } private fun scheduleSessionExpiryAlarm(runtimeToken: String, expiresAtEpochMs: Long): Boolean { @@ -607,6 +688,27 @@ class XrayVPNService : VpnService() { } } + private fun cancelSessionWarningAlarm() { + try { + val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager + alarmManager.cancel(sessionWarningPendingIntent("")) + } catch (e: Exception) { + Log.w(TAG, "Failed to cancel session-warning alarm", e) + } + } + + // A PendingIntent is identified by component plus request code, not extras, + // so the warning needs its own code or it would overwrite - and later + // cancel - the expiry alarm. + private fun sessionWarningPendingIntent(runtimeToken: String): PendingIntent { + val intent = Intent(this, XrayVPNService::class.java) + .putExtra(EXTRA_SESSION_WARNING, true) + .putExtra("RUNTIME_TOKEN", runtimeToken) + val flags = PendingIntent.FLAG_UPDATE_CURRENT or + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0 + return PendingIntent.getService(this, SESSION_WARNING_REQUEST_CODE, intent, flags) + } + private fun sessionExpiryPendingIntent(runtimeToken: String): PendingIntent { val intent = Intent(this, XrayVPNService::class.java) .putExtra(EXTRA_SESSION_EXPIRED, true) @@ -681,6 +783,11 @@ class XrayVPNService : VpnService() { private const val PREF_RUNTIME_TOKEN = "runtime_token" private const val PREF_EXPIRES_AT_MS = "expires_at_ms" private const val EXTRA_SESSION_EXPIRED = "SESSION_EXPIRED" + private const val EXTRA_SESSION_WARNING = "SESSION_WARNING" private const val SESSION_EXPIRY_REQUEST_CODE = 1001 + private const val SESSION_WARNING_REQUEST_CODE = 1002 + // An idle-capable alarm can run late; accept that much drift before + // treating a warning as belonging to a deadline that has moved. + private const val WARNING_SLACK_MS = 60_000L } } diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt new file mode 100644 index 0000000..fc085fa --- /dev/null +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt @@ -0,0 +1,143 @@ +package com.github.tfox.flutter_vless.xray.utils + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import android.util.Log + +// local_packages/.../xray/utils/RevoltAlerts.kt +// +// The two user-facing session alerts, built in one place because two processes +// post them: XrayVPNService (:RunSoLibXrayDaemon) owns the native deadline and +// can still warn when the UI process is gone, while MainActivity posts the +// "not protected" alert for session ends only Dart can see (cap exhausted, +// server ended the session, VPN error). Both use the same ids, so whichever +// posts second just replaces the first notification instead of stacking. +// +// These are deliberately NOT the foreground-service notification (id 1, +// channel REVOLT_VPN_SERVICE, IMPORTANCE_LOW): an alert the user must notice +// needs its own high-importance channel, and must be dismissible. +object RevoltAlerts { + + const val CHANNEL_ID = "REVOLT_VPN_ALERTS" + const val WARNING_NOTIFICATION_ID = 2 + const val DISCONNECTED_NOTIFICATION_ID = 3 + + // How long before the session deadline the warning fires. + const val WARNING_LEAD_MS = 5 * 60 * 1000L + + private const val TAG = "RevoltAlerts" + private const val LAUNCH_REQUEST_CODE = 2001 + + fun postExpiryWarning(context: Context) { + post( + context, + WARNING_NOTIFICATION_ID, + "Revolt VPN disconnects in 5 minutes", + "Watch an ad to extend your session.", + ) + } + + fun postDisconnected(context: Context) { + post( + context, + DISCONNECTED_NOTIFICATION_ID, + "Revolt VPN disconnected", + "Your traffic is no longer protected. Tap to reconnect.", + ) + } + + fun cancelExpiryWarning(context: Context) = cancel(context, WARNING_NOTIFICATION_ID) + + fun cancelDisconnected(context: Context) = cancel(context, DISCONNECTED_NOTIFICATION_ID) + + fun cancelAll(context: Context) { + cancelExpiryWarning(context) + cancelDisconnected(context) + } + + private fun cancel(context: Context, id: Int) { + try { + manager(context)?.cancel(id) + } catch (e: Exception) { + Log.w(TAG, "Failed to cancel alert $id", e) + } + } + + private fun post(context: Context, id: Int, title: String, text: String) { + if (!canPost(context)) { + Log.w(TAG, "POST_NOTIFICATIONS not granted; dropping alert $id") + return + } + + try { + val manager = manager(context) ?: return + ensureChannel(manager) + + val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + Notification.Builder(context, CHANNEL_ID) + } else { + @Suppress("DEPRECATION") + Notification.Builder(context).setPriority(Notification.PRIORITY_HIGH) + } + + val icon = context.resources + .getIdentifier("notification_icon", "drawable", context.packageName) + .takeIf { it != 0 } ?: android.R.drawable.ic_dialog_info + + builder + .setContentTitle(title) + .setContentText(text) + .setStyle(Notification.BigTextStyle().bigText(text)) + .setSmallIcon(icon) + .setAutoCancel(true) + .setOngoing(false) + + launchIntent(context)?.let { builder.setContentIntent(it) } + + manager.notify(id, builder.build()) + } catch (e: Exception) { + Log.w(TAG, "Failed to post alert $id", e) + } + } + + private fun canPost(context: Context): Boolean { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return true + return context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) == + PackageManager.PERMISSION_GRANTED + } + + private fun manager(context: Context): NotificationManager? = + context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager + + // Importance is fixed when the channel is first created, so this asks for + // HIGH up front — a session alert the user never sees is the whole bug + // these notifications exist to fix. + private fun ensureChannel(manager: NotificationManager) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + if (manager.getNotificationChannel(CHANNEL_ID) != null) return + val channel = NotificationChannel( + CHANNEL_ID, + "Session alerts", + NotificationManager.IMPORTANCE_HIGH, + ) + channel.description = "Warns before a session ends and when protection stops." + manager.createNotificationChannel(channel) + } + + private fun launchIntent(context: Context): PendingIntent? { + val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) + ?: return null + intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or + Intent.FLAG_ACTIVITY_CLEAR_TOP or + Intent.FLAG_ACTIVITY_NEW_TASK + val flags = PendingIntent.FLAG_UPDATE_CURRENT or + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0 + return PendingIntent.getActivity(context, LAUNCH_REQUEST_CODE, intent, flags) + } +} From dd1082c8de4ae2cca23ed5cdbfe4b5df7b679ab4 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 00:22:26 +0300 Subject: [PATCH 03/17] fix(session): repair the expiry warning and the gaps the review found Review of 742f376 (Fable). Three defects made the feature not work for the case it exists for: - armExpiryWarning() cancelled the alarm before its own early return. Dart re-pushes the deadline every 60 s with no dedupe (rule 93's ">5 s" dedupe does not exist), so the first sync after the warning came due deleted the armed alarm and never re-armed it. Cancel now happens only on the branch that re-arms. - cancelSessionWarningAlarm() built its PendingIntent with FLAG_UPDATE_CURRENT, rewriting the live alarm's RUNTIME_TOKEN to "" so a delivery in flight was dropped as a stale generation. It now looks the existing PendingIntent up with FLAG_NO_CREATE. - SOCKS5 mode never requested POST_NOTIFICATIONS (requestPermission() is TUN-only because it also raises the VPN consent dialog), so on Android 13+ both alerts were dropped. New plugin method requests it on its own. Also: - the native deadline wins the expiry race against the 1 s Dart tick, so the commonest session end reached _onVpnConnectionChanged as a bare tunnel drop with no message. It now reconciles and sets the expiry text, with postAlert false since the native side already posted. - a resume reconnect no longer resets the support-ad claim: it re-attaches to the same server session, where the top-up has already been spent. - RevoltAlerts sets setOnlyAlertOnce so a replacing post does not re-sound. - AGENTS.md rule 93 described a setSessionExpiry/SESSION_EXPIRES_AT_MS path that no longer exists, dedupe included. Corrected; that stale text is what the warning bug was written against. - CHANGELOG no longer claims the alert covers the tunnel stopping on its own. flutter analyze clean; debug APK builds. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 9 ++-- lib/logic/session_timer.dart | 42 ++++++++++++++----- lib/logic/vpn_connection.dart | 12 ++++++ .../settings/in_settings/connection_mode.dart | 2 +- .../tfox/flutter_vless/FlutterVlessPlugin.kt | 25 +++++++++++ .../xray/service/XrayVPNService.kt | 21 ++++++++-- .../flutter_vless/xray/utils/RevoltAlerts.kt | 3 ++ 7 files changed, 96 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ca2eae..370e878 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,9 +11,12 @@ Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH - **Five-minute warning before a session ends.** The VPN service schedules it off the same deadline it already enforces, so the warning still arrives when the app is closed, and a support top-up moves it with the deadline. -- **"Disconnected — not protected" notification** whenever a session ends for - any reason other than you tapping disconnect: expiry, the data limit, the - server ending the session, or the tunnel stopping on its own. +- **"Disconnected — not protected" notification** when a session ends without + you asking: the 2-hour expiry, the data limit, the server ending the session, + or the tunnel reporting an error. +- **SOCKS5 mode now asks for the notification permission.** It never did, + because it never raises the VPN consent dialog, so on Android 13+ these + alerts would have been dropped before they were shown. - **The app now shows what went wrong.** Connect errors, the reason a session ended, and progress while connecting appear under the status bar instead of the button silently going back to idle. diff --git a/lib/logic/session_timer.dart b/lib/logic/session_timer.dart index c205da0..a7cfa3c 100644 --- a/lib/logic/session_timer.dart +++ b/lib/logic/session_timer.dart @@ -141,14 +141,28 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { } if (vpnConnection.status == VpnStatus.disconnected) { - // No alert here. The runtime going away covers both the native deadline - // (which posts the alert itself, from a process that outlives this one) - // and the notification's Disconnect action, which the user tapped. - unawaited(_doDisconnect('VPN tunnel dropped')); + // The native deadline fires on the exact second while this 1 s tick is + // in arbitrary phase, so expiry almost always arrives here rather than + // at the countdown check in _tick - without this, the commonest session + // end left the UI with nothing to say. + _reconcileElapsedTime(); + final expired = _hasSyncedOnce && _remainingSeconds <= 2; + // postAlert is false either way: the native side already posted for its + // own deadline, and the notification's Disconnect action is the user + // asking, which must never raise a "not protected" alert. + unawaited(_doDisconnect( + 'VPN tunnel dropped', + endedMessage: + expired ? 'Your session ended. You are not protected.' : null, + postAlert: false, + )); } } - Future start() async { + // resetSupportClaim is false when re-attaching to a session the device + // already holds: the support top-up is once per server session, and the + // claim flag is the only thing enforcing that. + Future start({bool resetSupportClaim = true}) async { _sessionEpoch++; _remainingSeconds = 0; _remainingAtLastSync = 0; @@ -165,10 +179,12 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { _lastEndMessage = null; NotificationService.reset(); - _supportStateEpoch++; - _supportRewardClaimed = false; - _supportRewardStateLoaded = true; - unawaited(_persistSupportRewardState(false)); + if (resetSupportClaim) { + _supportStateEpoch++; + _supportRewardClaimed = false; + _supportRewardStateLoaded = true; + unawaited(_persistSupportRewardState(false)); + } _timer?.cancel(); _timer = Timer.periodic(const Duration(seconds: 1), _tick); @@ -233,7 +249,11 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { // not ask for, and its presence is also what posts the "not protected" // notification. Both exist so nobody is left on their real IP without being // told. A user-requested disconnect passes nothing. - Future _doDisconnect(String reason, {String? endedMessage}) async { + Future _doDisconnect( + String reason, { + String? endedMessage, + bool postAlert = true, + }) async { if (_isDisconnecting) return; _isDisconnecting = true; _sessionEpoch++; @@ -252,7 +272,7 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { notifyListeners(); await vpnConnection.disconnect(); - if (endedMessage != null) { + if (endedMessage != null && postAlert) { unawaited(NotificationService.showDisconnectedAlert()); } diff --git a/lib/logic/vpn_connection.dart b/lib/logic/vpn_connection.dart index 44d0e30..78150d2 100644 --- a/lib/logic/vpn_connection.dart +++ b/lib/logic/vpn_connection.dart @@ -224,6 +224,18 @@ class VpnConnection extends ChangeNotifier { return false; } + // SOCKS5 mode skips requestPermission below (it would raise the VPN + // consent dialog for an interface it never creates), so ask for the + // notification permission on its own - the session alerts need it. + if (!kIsWeb && _activeMode == ConnectionMode.proxy) { + try { + await _nativeControl.invokeMethod('requestNotificationPermission'); + } catch (e) { + debugPrint('[VPN] Notification permission request failed: $e'); + } + if (!_isCurrentConnect(connectEpoch)) return false; + } + if (!kIsWeb && _activeMode == ConnectionMode.tun) { final ok = await _vless.requestPermission(); if (!_isCurrentConnect(connectEpoch)) return false; diff --git a/lib/screens/settings/in_settings/connection_mode.dart b/lib/screens/settings/in_settings/connection_mode.dart index c638e66..0d5e879 100644 --- a/lib/screens/settings/in_settings/connection_mode.dart +++ b/lib/screens/settings/in_settings/connection_mode.dart @@ -82,7 +82,7 @@ class _ConnectionModeTileState extends State { if (!mounted) return; if (await vpn.connect(resume: true)) { if (!mounted) return; - await timer.start(); + await timer.start(resetSupportClaim: false); } } finally { if (mounted) { diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/FlutterVlessPlugin.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/FlutterVlessPlugin.kt index 35cc1f7..e71c891 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/FlutterVlessPlugin.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/FlutterVlessPlugin.kt @@ -240,6 +240,31 @@ class FlutterVlessPlugin : FlutterPlugin, ActivityAware, PluginRegistry.Activity } } + // POST_NOTIFICATIONS on its own, without VpnService.prepare: SOCKS5 + // mode never establishes a VPN interface, so it never called + // requestPermission and both session alerts were dropped unasked + // for on Android 13+. + "requestNotificationPermission" -> { + val currentActivity = activity + if (currentActivity == null) { + result.error("NO_ACTIVITY", "Activity is not attached", null) + return + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + ActivityCompat.checkSelfPermission( + currentActivity, + Manifest.permission.POST_NOTIFICATIONS, + ) != PackageManager.PERMISSION_GRANTED + ) { + ActivityCompat.requestPermissions( + currentActivity, + arrayOf(Manifest.permission.POST_NOTIFICATIONS), + REQUEST_CODE_POST_NOTIFICATIONS, + ) + } + result.success(null) + } + "requestPermission" -> { val currentActivity = activity if (currentActivity == null) { diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt index bedb116..9ef07e0 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt @@ -473,15 +473,18 @@ class XrayVPNService : VpnService() { // scheduled must never stop a working tunnel, so nothing here fails closed. // Dart re-pushes the deadline on every sync, so this runs about once a minute. private fun armExpiryWarning(runtimeToken: String, expiresAtEpochMs: Long) { - cancelSessionWarningAlarm() if (runtimeToken.isEmpty()) return val warnAt = expiresAtEpochMs - RevoltAlerts.WARNING_LEAD_MS // Deadline already inside the warning window (or past): either the alarm // has fired and its notification should stay up, or this is the short - // bootstrap deadline at connect, which must not warn at all. + // bootstrap deadline at connect, which must not warn at all. Nothing is + // cancelled here - Dart re-pushes the same deadline every 60 s with no + // dedupe, so cancelling on this branch would reliably delete the armed + // warning on the first sync after it came due and never re-arm it. if (warnAt <= System.currentTimeMillis()) return + cancelSessionWarningAlarm() // More than the lead away, so any warning on screen belongs to an older // deadline - a support top-up just pushed it out. RevoltAlerts.cancelExpiryWarning(this) @@ -691,12 +694,24 @@ class XrayVPNService : VpnService() { private fun cancelSessionWarningAlarm() { try { val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager - alarmManager.cancel(sessionWarningPendingIntent("")) + // Look the existing PendingIntent up instead of building one: with + // FLAG_UPDATE_CURRENT, constructing it to cancel rewrites the live + // alarm's RUNTIME_TOKEN to "" first, and a delivery already in + // flight would then be dropped as a stale generation. + existingSessionWarningPendingIntent()?.let { alarmManager.cancel(it) } } catch (e: Exception) { Log.w(TAG, "Failed to cancel session-warning alarm", e) } } + private fun existingSessionWarningPendingIntent(): PendingIntent? { + val intent = Intent(this, XrayVPNService::class.java) + .putExtra(EXTRA_SESSION_WARNING, true) + val flags = PendingIntent.FLAG_NO_CREATE or + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0 + return PendingIntent.getService(this, SESSION_WARNING_REQUEST_CODE, intent, flags) + } + // A PendingIntent is identified by component plus request code, not extras, // so the warning needs its own code or it would overwrite - and later // cancel - the expiry alarm. diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt index fc085fa..48ada2e 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt @@ -97,6 +97,9 @@ object RevoltAlerts { .setSmallIcon(icon) .setAutoCancel(true) .setOngoing(false) + // Both processes can post the disconnected alert; the second + // post replaces the first and must not sound again. + .setOnlyAlertOnce(true) launchIntent(context)?.let { builder.setContentIntent(it) } From 34722c751b92d79fdc13ea2a69a155af5780fff9 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 00:25:17 +0300 Subject: [PATCH 04/17] fix(session): recognise expiry after device sleep by wall clock _reconcileElapsedTime() runs off a Dart Stopwatch, which is CLOCK_MONOTONIC and does not advance while the device is suspended - exactly the state an RTC_WAKEUP expiry alarm fires in. The "did this drop happen at the deadline" test therefore came out false after any sleep, and the screen-off expiry (the common one) still showed no reason in the UI. Each successful sync now records an absolute DateTime deadline, and the tunnel-dropped branch compares against that instead. Co-Authored-By: Claude Opus 5 --- lib/logic/session_timer.dart | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/logic/session_timer.dart b/lib/logic/session_timer.dart index a7cfa3c..fb59bf4 100644 --- a/lib/logic/session_timer.dart +++ b/lib/logic/session_timer.dart @@ -42,6 +42,11 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { int _lastUsedBytes = 0; Stopwatch? _sinceLastSuccessfulSync; + // Wall-clock deadline, kept alongside the Stopwatch because they answer + // different questions. The Stopwatch is CLOCK_MONOTONIC: it does not advance + // while the device is suspended, which is exactly when an RTC_WAKEUP expiry + // alarm fires, so it cannot be used to recognise an expiry after sleep. + DateTime? _deadlineAt; double _currentSpeedKBps = 0.0; SessionTimer({required this.vpnConnection}) { @@ -145,8 +150,12 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { // in arbitrary phase, so expiry almost always arrives here rather than // at the countdown check in _tick - without this, the commonest session // end left the UI with nothing to say. - _reconcileElapsedTime(); - final expired = _hasSyncedOnce && _remainingSeconds <= 2; + final deadline = _deadlineAt; + final expired = _hasSyncedOnce && + deadline != null && + DateTime.now().isAfter( + deadline.subtract(const Duration(seconds: 5)), + ); // postAlert is false either way: the native side already posted for its // own deadline, and the notification's Disconnect action is the user // asking, which must never raise a "not protected" alert. @@ -170,6 +179,7 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { _lastUsedBytes = 0; _sinceLastSuccessfulSync?.stop(); _sinceLastSuccessfulSync = null; + _deadlineAt = null; _currentSpeedKBps = 0.0; _tickCount = 0; _hasSyncedOnce = false; @@ -260,6 +270,7 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { debugPrint('[Timer] Disconnecting: $reason'); _lastEndMessage = endedMessage; + _deadlineAt = null; _timer?.cancel(); _timer = null; _currentSpeedKBps = 0.0; @@ -340,6 +351,9 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { final elapsedMs = _sinceLastSuccessfulSync?.elapsedMilliseconds; _remainingAtLastSync = expiresValue.toInt(); _remainingSeconds = _remainingAtLastSync; + _deadlineAt = DateTime.now().add( + Duration(seconds: _remainingAtLastSync), + ); _usedBytes = _readNonNegativeInt(data['used_bytes'], _usedBytes); final deltaBytes = _usedBytes - _lastUsedBytes; From d1ea13b01a7a4f9660e7823fbb3c9e241a1ff334 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 00:38:08 +0300 Subject: [PATCH 05/17] fix(session): clamp the countdown to wall clock, correct two doc claims Second review pass (Fable) cleared all six fixes; these are its leftovers. - _reconcileElapsedTime() runs off the same suspend-blind Stopwatch, so after a long device sleep the countdown over-reports - and with the API unreachable nothing corrects it, which is precisely the state the app now stays in instead of disconnecting. It now takes the lesser of the Stopwatch value and the wall-clock deadline; the minimum, so a clock set backwards cannot extend a session. - CHANGELOG claimed the alert covers "the tunnel reporting an error". It cannot: AppConfigs.V2RAY_STATES has no error state and the plugin's stateName when() ends in else -> "DISCONNECTED", so VpnStatus.error is unreachable from the status stream on Android. - AGENTS.md file map still listed a setSessionExpiry bridge in power_settings.dart; no such symbol exists. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 4 ++-- lib/logic/session_timer.dart | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 370e878..ece4ba2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,8 +12,8 @@ Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH off the same deadline it already enforces, so the warning still arrives when the app is closed, and a support top-up moves it with the deadline. - **"Disconnected — not protected" notification** when a session ends without - you asking: the 2-hour expiry, the data limit, the server ending the session, - or the tunnel reporting an error. + you asking: the 2-hour expiry, the data limit, or the server ending the + session. - **SOCKS5 mode now asks for the notification permission.** It never did, because it never raises the VPN consent dialog, so on Android 13+ these alerts would have been dropped before they were shown. diff --git a/lib/logic/session_timer.dart b/lib/logic/session_timer.dart index fb59bf4..9e8b138 100644 --- a/lib/logic/session_timer.dart +++ b/lib/logic/session_timer.dart @@ -426,6 +426,20 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { final elapsed = clock.elapsed.inSeconds; _remainingSeconds = (_remainingAtLastSync - elapsed).clamp(0, 1 << 31).toInt(); + + // The Stopwatch is CLOCK_MONOTONIC and stops while the device is + // suspended, so after a long sleep it over-reports - and with the server + // unreachable no sync arrives to correct it, which is exactly the state + // the app now stays in rather than disconnecting. Take whichever is + // smaller, never the wall clock alone: a clock set backwards must not be + // able to extend a session. + final deadline = _deadlineAt; + if (deadline != null) { + final byWallClock = deadline.difference(DateTime.now()).inSeconds; + if (byWallClock < _remainingSeconds) { + _remainingSeconds = byWallClock.clamp(0, 1 << 31).toInt(); + } + } } @override From 8ba3b6c5433f89c40af01c99dcb2fc8c3c8c0a36 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 00:44:51 +0300 Subject: [PATCH 06/17] fix(session): alert on every unsolicited native stop, not just the deadline Second review pass found that VpnStatus.error is unreachable mid-session: AppConfigs.V2RAY_STATES has no error state and the plugin's stateName when() ends in else -> "DISCONNECTED", so Dart's unknown -> error mapping is dead code on Android. Every native stop therefore arrived as a plain disconnect, and anything other than the expiry deadline - an Xray or TUN setup failure, a mid-session fail-closed deadline arm - left the user on their real IP with no notification and no message. That is the exact hole this feature exists to close. stopAll() is the single funnel for every native stop, so the alert moves there: it fires when the stop interrupted a live tunnel and the user did not ask for it. isRunning is captured before cleanup() clears it, which keeps a failed connect silent - it never had a tunnel to interrupt. STOP_SERVICE (the notification's Disconnect action) and onRevoke pass userRequested: in the revoke case the user switched VPNs or withdrew consent themselves, and may well be protected by the app that took over. Also from the pass: - re-arming now needs the deadline to move by more than 15 s, so round-trip jitter cannot cancel and re-post a warning that is already on screen - a warning delivered with under a minute left is dropped rather than announcing "5 minutes"; the disconnected alert follows anyway - the _doDisconnect comment no longer claims endedMessage posts the alert - CHANGELOG: the alert does now cover the tunnel stopping unexpectedly flutter analyze clean; debug APK builds with the Kotlin recompiled. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 4 +- lib/logic/session_timer.dart | 7 ++-- .../xray/service/XrayVPNService.kt | 38 ++++++++++++++----- pubspec.lock | 18 ++++----- 4 files changed, 43 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ece4ba2..dcfdacd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,8 +12,8 @@ Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH off the same deadline it already enforces, so the warning still arrives when the app is closed, and a support top-up moves it with the deadline. - **"Disconnected — not protected" notification** when a session ends without - you asking: the 2-hour expiry, the data limit, or the server ending the - session. + you asking: the 2-hour expiry, the data limit, the server ending the + session, or the tunnel stopping unexpectedly. - **SOCKS5 mode now asks for the notification permission.** It never did, because it never raises the VPN consent dialog, so on Android 13+ these alerts would have been dropped before they were shown. diff --git a/lib/logic/session_timer.dart b/lib/logic/session_timer.dart index 9e8b138..a7729a3 100644 --- a/lib/logic/session_timer.dart +++ b/lib/logic/session_timer.dart @@ -256,9 +256,10 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { } // endedMessage is the one sentence the UI shows after an end the user did - // not ask for, and its presence is also what posts the "not protected" - // notification. Both exist so nobody is left on their real IP without being - // told. A user-requested disconnect passes nothing. + // not ask for; postAlert independently decides whether to raise the "not + // protected" notification, which the native service already posts for every + // stop it sees. Both exist so nobody is left on their real IP without being + // told. A user-requested disconnect passes neither. Future _doDisconnect( String reason, { String? endedMessage, diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt index 9ef07e0..d57796c 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt @@ -91,7 +91,7 @@ class XrayVPNService : VpnService() { Log.w(TAG, "Ignoring STOP_SERVICE without matching runtime generation") return START_NOT_STICKY } - stopAll(requestedToken) + stopAll(requestedToken, userRequested = true) return START_NOT_STICKY } @@ -428,14 +428,25 @@ class XrayVPNService : VpnService() { } } - private fun stopAll(confirmationToken: String = currentConfig?.RUNTIME_TOKEN.orEmpty()) { + // userRequested marks the two stops the user drove themselves. Everything + // else that reaches here while a tunnel is live - the expiry deadline, an + // Xray or TUN failure, a fail-closed deadline arm - took protection away + // without being asked, and must say so. isRunning is read before cleanup() + // clears it, which is also what keeps a failed connect silent: it never had + // a live tunnel to interrupt. + private fun stopAll( + confirmationToken: String = currentConfig?.RUNTIME_TOKEN.orEmpty(), + userRequested: Boolean = false, + ) { if (shuttingDownIntentionally) return + val alertUser = isRunning && !userRequested shuttingDownIntentionally = true cleanup(clearDeadline = true) currentConfig = null XrayCoreManager.stopCore(this, confirmationToken) stopForeground(true) stopSelf() + if (alertUser) RevoltAlerts.postDisconnected(this) } private fun armSessionDeadline(config: XrayConfig, remainingSeconds: Long) { @@ -482,7 +493,7 @@ class XrayVPNService : VpnService() { // cancelled here - Dart re-pushes the same deadline every 60 s with no // dedupe, so cancelling on this branch would reliably delete the armed // warning on the first sync after it came due and never re-arm it. - if (warnAt <= System.currentTimeMillis()) return + if (warnAt <= System.currentTimeMillis() + WARNING_REARM_GRACE_MS) return cancelSessionWarningAlarm() // More than the lead away, so any warning on screen belongs to an older @@ -523,7 +534,12 @@ class XrayVPNService : VpnService() { val deadline = sessionDeadlineElapsed ?: return val remaining = deadline - SystemClock.elapsedRealtime() - if (remaining <= 0L || remaining > RevoltAlerts.WARNING_LEAD_MS + WARNING_SLACK_MS) { + if (remaining < WARNING_FLOOR_MS || + remaining > RevoltAlerts.WARNING_LEAD_MS + WARNING_SLACK_MS + ) { + // Too late to be a five-minute warning, or for a deadline that has + // moved. Saying "5 minutes" with seconds left is worse than silence; + // the disconnected alert follows either way. Log.w(TAG, "Ignoring session warning outside the warning window") return } @@ -553,10 +569,6 @@ class XrayVPNService : VpnService() { } Log.w(TAG, "Native session deadline expired; stopping runtime fail-closed") stopAll(token) - // Only the deadline paths post this natively. A STOP_SERVICE command - // cannot tell a user tap from a Dart-side session end, so Dart posts for - // its own reasons; the shared id means a double post just replaces. - RevoltAlerts.postDisconnected(this) } private fun updateSessionDeadline(intent: Intent) { @@ -646,8 +658,9 @@ class XrayVPNService : VpnService() { RevoltAlerts.cancelExpiryWarning(this) stopForeground(true) stopSelf() + // This arm does not go through stopAll, so it posts for itself. + RevoltAlerts.postDisconnected(this) } - RevoltAlerts.postDisconnected(this) } private fun scheduleSessionExpiryAlarm(runtimeToken: String, expiresAtEpochMs: Long): Boolean { @@ -745,7 +758,7 @@ class XrayVPNService : VpnService() { } override fun onRevoke() { - stopAll() + stopAll(userRequested = true) super.onRevoke() } @@ -804,5 +817,10 @@ class XrayVPNService : VpnService() { // An idle-capable alarm can run late; accept that much drift before // treating a warning as belonging to a deadline that has moved. private const val WARNING_SLACK_MS = 60_000L + // Don't re-arm (and so re-post) for a deadline that only moved by the + // jitter in a network round trip. + private const val WARNING_REARM_GRACE_MS = 15_000L + // Below this the warning has lost its point; stay quiet instead. + private const val WARNING_FLOOR_MS = 60_000L } } diff --git a/pubspec.lock b/pubspec.lock index 2af4fa8..b734022 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -299,10 +299,10 @@ packages: dependency: transitive description: name: matcher - sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 url: "https://pub.dev" source: hosted - version: "0.12.20" + version: "0.12.19" material_color_utilities: dependency: transitive description: @@ -315,10 +315,10 @@ packages: dependency: transitive description: name: meta - sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" + sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" url: "https://pub.dev" source: hosted - version: "1.19.0" + version: "1.18.0" nested: dependency: transitive description: @@ -560,10 +560,10 @@ packages: dependency: transitive description: name: test_api - sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" + sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" url: "https://pub.dev" source: hosted - version: "0.7.12" + version: "0.7.11" typed_data: dependency: transitive description: @@ -648,10 +648,10 @@ packages: dependency: transitive description: name: vector_math - sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47 + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b url: "https://pub.dev" source: hosted - version: "2.4.2" + version: "2.2.0" vm_service: dependency: transitive description: @@ -725,5 +725,5 @@ packages: source: hosted version: "3.1.3" sdks: - dart: ">=3.11.0-0 <4.0.0" + dart: ">=3.10.3 <4.0.0" flutter: ">=3.38.4" From 66789d49c11dfa5b2b735ea9b91522e80ff2c3e9 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 00:47:23 +0300 Subject: [PATCH 07/17] revert: restore pubspec.lock to main Builds run with Flutter 3.47.2 rewrote the lockfile, downgrading five transitive packages and the Dart SDK constraint. Unrelated to this branch's work and swept in by git add -A. Co-Authored-By: Claude Opus 5 --- pubspec.lock | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/pubspec.lock b/pubspec.lock index b734022..2af4fa8 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -299,10 +299,10 @@ packages: dependency: transitive description: name: matcher - sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.19" + version: "0.12.20" material_color_utilities: dependency: transitive description: @@ -315,10 +315,10 @@ packages: dependency: transitive description: name: meta - sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "1.18.0" + version: "1.19.0" nested: dependency: transitive description: @@ -560,10 +560,10 @@ packages: dependency: transitive description: name: test_api - sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" url: "https://pub.dev" source: hosted - version: "0.7.11" + version: "0.7.12" typed_data: dependency: transitive description: @@ -648,10 +648,10 @@ packages: dependency: transitive description: name: vector_math - sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47 url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.4.2" vm_service: dependency: transitive description: @@ -725,5 +725,5 @@ packages: source: hosted version: "3.1.3" sdks: - dart: ">=3.10.3 <4.0.0" + dart: ">=3.11.0-0 <4.0.0" flutter: ">=3.38.4" From 30d96a4049876d951e6e74f9e998961a07395f59 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 00:50:36 +0300 Subject: [PATCH 08/17] style: cut the comments down Co-Authored-By: Claude Opus 5 --- .../kotlin/com/paladinvpn/app/MainActivity.kt | 5 +- lib/components/status_bar.dart | 11 +--- lib/logic/ad_manager.dart | 12 ++-- lib/logic/hivemind_service.dart | 13 ++-- lib/logic/notification_service.dart | 7 +-- lib/logic/session_timer.dart | 44 ++++--------- lib/logic/vpn_connection.dart | 5 +- .../settings/in_settings/connection_mode.dart | 6 +- .../tfox/flutter_vless/FlutterVlessPlugin.kt | 5 +- .../xray/service/XrayVPNService.kt | 61 +++++++------------ .../flutter_vless/xray/utils/RevoltAlerts.kt | 22 ++----- 11 files changed, 59 insertions(+), 132 deletions(-) diff --git a/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt b/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt index ac30ff4..662b60a 100644 --- a/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt +++ b/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt @@ -70,10 +70,7 @@ class MainActivity : FlutterActivity() { updateVpnNotification(title, text, action) result.success(null) } - // Session ends only Dart can see (cap exhausted, server - // ended the session, VPN error). The VPN service posts the - // same alert for its own deadline, where this process may - // already be gone. RevoltAlerts owns both. + // Session ends only Dart sees; the service posts the rest. "showDisconnectedAlert" -> { RevoltAlerts.postDisconnected(this) result.success(null) diff --git a/lib/components/status_bar.dart b/lib/components/status_bar.dart index a539648..9727151 100644 --- a/lib/components/status_bar.dart +++ b/lib/components/status_bar.dart @@ -5,9 +5,7 @@ import 'package:revoltvpn/logic/app_colors.dart'; import 'package:revoltvpn/logic/session_timer.dart'; import 'package:revoltvpn/logic/vpn_connection.dart'; -// Nothing rendered the connection's own messages, so they are collected here -// in one place: whatever the user most needs to know right now, and whether it -// is a problem (red) or just progress (dim). +// The one line worth showing right now, and whether it is a problem. class _StatusDetail { const _StatusDetail(this.text, {this.isProblem = false}); @@ -26,8 +24,7 @@ _StatusDetail? _detail(VpnConnection vpn, SessionTimer timer) { return _StatusDetail(vpn.statusMessage); } - // The tunnel still carries traffic; only the control plane is missing, so - // this is a warning, not a disconnect (review #2). + // Control plane only - the tunnel still carries traffic. if (vpn.status == VpnStatus.connected && timer.serverUnreachable) { return const _StatusDetail( 'Can\'t reach the server — still connected', @@ -136,9 +133,7 @@ class StatusBar extends StatelessWidget { ], ), ), - // Until this existed, a failed connect, an expired session and a - // cap kill all just turned the button back to idle - the user - // could not tell protected from unprotected (review #3). + // Errors and session-end reasons used to render nowhere. if (detail != null) Padding( padding: const EdgeInsets.only(top: 6), diff --git a/lib/logic/ad_manager.dart b/lib/logic/ad_manager.dart index 7e0d225..307919a 100644 --- a/lib/logic/ad_manager.dart +++ b/lib/logic/ad_manager.dart @@ -96,18 +96,14 @@ class AdManager extends ChangeNotifier { // ── Show ad (or debug bypass) ───────────────────────────────────── - // Returns the nonce carried in the SSV custom_data when the reward was - // earned, null otherwise. The main flow passes it to vpn.connect(adNonce:) - // so the client waits for the session this ad created — minting a second - // nonce there is what broke every connect once ads were on. + // Returns the nonce put in the SSV custom_data, null if unrewarded. connect() + // must reuse it: minting a second nonce there rejects the ad's own session. Future showAd(String adType) async { if (!adsEnabled) { - // Main connect: no ad to show — HivemindService.fetchConfigDirectly() - // fires the server-gated bypass itself (rule 87). + // Main connect fires its own bypass in fetchConfigDirectly (rule 87). if (adType != 'support' || !kDebugMode) return null; - // Debug bypass: fire fake AdMob callback so support ads work in dev. - // The server's ADMOB_BYPASS must be True for this to succeed. + // Needs ADMOB_BYPASS=True server-side. final deviceId = await CryptoService.getDeviceId(); final nonce = HivemindService.newNonce(); try { diff --git a/lib/logic/hivemind_service.dart b/lib/logic/hivemind_service.dart index ac1daea..007bd71 100644 --- a/lib/logic/hivemind_service.dart +++ b/lib/logic/hivemind_service.dart @@ -81,15 +81,10 @@ class HivemindService { _expectedNonce = null; } - // Fetches this device's VLESS URL. Three ways in: - // adNonce != null — a real rewarded ad was watched; its SSV custom_data - // carried this nonce, so wait for a session holding it. - // Google's SSV callback can lag, so poll longer. - // resume == true — re-attach to the session already granted (mode-switch - // reconnect in connection_mode.dart). No ad, no bypass, - // any nonce accepted — device_id already owns it. - // neither — ads disabled: mint a nonce and fire the server-gated - // ADMOB_BYPASS callback (rule 87). + // Fetches this device's VLESS URL. + // adNonce — wait for the session that ad created (SSV can lag, so poll longer) + // resume — re-attach to the session already held; any nonce accepted + // neither — ads off: mint a nonce and fire the bypass (rule 87) static Future fetchConfigDirectly({ void Function(int attempt, int total)? onAttempt, String? adNonce, diff --git a/lib/logic/notification_service.dart b/lib/logic/notification_service.dart index c22a04a..bf830d2 100644 --- a/lib/logic/notification_service.dart +++ b/lib/logic/notification_service.dart @@ -32,15 +32,12 @@ class NotificationService { } } - // Posts the "disconnected - not protected" alert for a session end the user - // did not ask for. The native service posts the same alert (same id) when - // its own deadline fires, because by then this process may be gone; a double - // post replaces rather than stacks. + // Same id as the service's own alert, so a double post replaces. static Future showDisconnectedAlert() async { try { await _channel.invokeMethod('showDisconnectedAlert'); } catch (_) { - // Informational only - never worth failing a disconnect over. + // Informational only. } } diff --git a/lib/logic/session_timer.dart b/lib/logic/session_timer.dart index a7729a3..f5196da 100644 --- a/lib/logic/session_timer.dart +++ b/lib/logic/session_timer.dart @@ -42,10 +42,8 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { int _lastUsedBytes = 0; Stopwatch? _sinceLastSuccessfulSync; - // Wall-clock deadline, kept alongside the Stopwatch because they answer - // different questions. The Stopwatch is CLOCK_MONOTONIC: it does not advance - // while the device is suspended, which is exactly when an RTC_WAKEUP expiry - // alarm fires, so it cannot be used to recognise an expiry after sleep. + // Wall clock, because the Stopwatch is CLOCK_MONOTONIC and stops across + // device suspend - exactly when the RTC_WAKEUP expiry alarm fires. DateTime? _deadlineAt; double _currentSpeedKBps = 0.0; @@ -70,14 +68,10 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { int get usedBytes => _usedBytes; double get currentSpeedKBps => _currentSpeedKBps; - // True once the control plane has missed enough polls in a row to be worth - // telling the user about. It is a display state only: a tunnel that still - // carries traffic is never torn down because the API is unreachable (the - // native deadline and the server both still enforce expiry). + // Display state only - an unreachable API never tears down a live tunnel. bool get serverUnreachable => _consecutiveFailures >= _maxConsecutiveFailures; - // Why the last session ended, when the user did not end it themselves. - // Cleared on the next connect. Rendered by status_bar.dart. + // Why the last session ended, if the user did not end it. Cleared on connect. String? _lastEndMessage; String? get lastEndMessage => _lastEndMessage; @@ -146,19 +140,15 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { } if (vpnConnection.status == VpnStatus.disconnected) { - // The native deadline fires on the exact second while this 1 s tick is - // in arbitrary phase, so expiry almost always arrives here rather than - // at the countdown check in _tick - without this, the commonest session - // end left the UI with nothing to say. + // The native deadline beats the 1 s tick, so expiry lands here, not in + // _tick. postAlert is false: the service already posted, and a + // notification-Disconnect tap is the user asking. final deadline = _deadlineAt; final expired = _hasSyncedOnce && deadline != null && DateTime.now().isAfter( deadline.subtract(const Duration(seconds: 5)), ); - // postAlert is false either way: the native side already posted for its - // own deadline, and the notification's Disconnect action is the user - // asking, which must never raise a "not protected" alert. unawaited(_doDisconnect( 'VPN tunnel dropped', endedMessage: @@ -168,9 +158,8 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { } } - // resetSupportClaim is false when re-attaching to a session the device - // already holds: the support top-up is once per server session, and the - // claim flag is the only thing enforcing that. + // resetSupportClaim is false when re-attaching to a session already held: + // the top-up is once per server session and this flag is what enforces it. Future start({bool resetSupportClaim = true}) async { _sessionEpoch++; _remainingSeconds = 0; @@ -255,11 +244,8 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { await _doDisconnect(reason); } - // endedMessage is the one sentence the UI shows after an end the user did - // not ask for; postAlert independently decides whether to raise the "not - // protected" notification, which the native service already posts for every - // stop it sees. Both exist so nobody is left on their real IP without being - // told. A user-requested disconnect passes neither. + // endedMessage is what the UI shows; postAlert raises the notification. + // A user-requested disconnect passes neither. Future _doDisconnect( String reason, { String? endedMessage, @@ -428,12 +414,8 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { _remainingSeconds = (_remainingAtLastSync - elapsed).clamp(0, 1 << 31).toInt(); - // The Stopwatch is CLOCK_MONOTONIC and stops while the device is - // suspended, so after a long sleep it over-reports - and with the server - // unreachable no sync arrives to correct it, which is exactly the state - // the app now stays in rather than disconnecting. Take whichever is - // smaller, never the wall clock alone: a clock set backwards must not be - // able to extend a session. + // The Stopwatch over-reports after device suspend. Take the smaller of + // the two, never the wall clock alone - a backward clock must not extend. final deadline = _deadlineAt; if (deadline != null) { final byWallClock = deadline.difference(DateTime.now()).inSeconds; diff --git a/lib/logic/vpn_connection.dart b/lib/logic/vpn_connection.dart index 78150d2..788b8cf 100644 --- a/lib/logic/vpn_connection.dart +++ b/lib/logic/vpn_connection.dart @@ -224,9 +224,8 @@ class VpnConnection extends ChangeNotifier { return false; } - // SOCKS5 mode skips requestPermission below (it would raise the VPN - // consent dialog for an interface it never creates), so ask for the - // notification permission on its own - the session alerts need it. + // Proxy mode skips requestPermission below (VPN consent it never needs), + // so it has to ask for POST_NOTIFICATIONS on its own. if (!kIsWeb && _activeMode == ConnectionMode.proxy) { try { await _nativeControl.invokeMethod('requestNotificationPermission'); diff --git a/lib/screens/settings/in_settings/connection_mode.dart b/lib/screens/settings/in_settings/connection_mode.dart index 0d5e879..0f0fe32 100644 --- a/lib/screens/settings/in_settings/connection_mode.dart +++ b/lib/screens/settings/in_settings/connection_mode.dart @@ -67,10 +67,8 @@ class _ConnectionModeTileState extends State { widget.onChanged?.call(next); } - // Recovers from an orphaned proxy: tear the runtime down and re-attach to - // the session this device already holds (connect(resume: true)), so a - // readable set of credentials exists again. No rewarded ad and no new - // session — the user is repairing a connection they already paid for. + // Recovers an orphaned proxy: tear the runtime down and re-attach to the + // session already held. No ad, no new session. Future _reconnect() async { if (_reconnecting) return; final vpn = context.read(); diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/FlutterVlessPlugin.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/FlutterVlessPlugin.kt index e71c891..57ea27c 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/FlutterVlessPlugin.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/FlutterVlessPlugin.kt @@ -240,10 +240,7 @@ class FlutterVlessPlugin : FlutterPlugin, ActivityAware, PluginRegistry.Activity } } - // POST_NOTIFICATIONS on its own, without VpnService.prepare: SOCKS5 - // mode never establishes a VPN interface, so it never called - // requestPermission and both session alerts were dropped unasked - // for on Android 13+. + // POST_NOTIFICATIONS without VpnService.prepare, for proxy mode. "requestNotificationPermission" -> { val currentActivity = activity if (currentActivity == null) { diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt index d57796c..44675e1 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt @@ -67,9 +67,8 @@ class XrayVPNService : VpnService() { return START_NOT_STICKY } - // Must stay above the command handling below: an intent carrying no - // COMMAND falls through to the final else and stops a live tunnel - in - // this case five minutes early, which is what it warns about. + // Must stay above the command dispatch: an intent with no COMMAND + // falls through to the final else and stops the tunnel. if (intent.getBooleanExtra(EXTRA_SESSION_WARNING, false)) { handleSessionWarningAlarm(intent.getStringExtra("RUNTIME_TOKEN").orEmpty()) return START_NOT_STICKY @@ -428,12 +427,8 @@ class XrayVPNService : VpnService() { } } - // userRequested marks the two stops the user drove themselves. Everything - // else that reaches here while a tunnel is live - the expiry deadline, an - // Xray or TUN failure, a fail-closed deadline arm - took protection away - // without being asked, and must say so. isRunning is read before cleanup() - // clears it, which is also what keeps a failed connect silent: it never had - // a live tunnel to interrupt. + // Anything that stops a live tunnel unasked must say so. isRunning is read + // before cleanup() clears it, which keeps a failed connect silent. private fun stopAll( confirmationToken: String = currentConfig?.RUNTIME_TOKEN.orEmpty(), userRequested: Boolean = false, @@ -479,33 +474,26 @@ class XrayVPNService : VpnService() { else deadlineHandler.postDelayed(sessionDeadlineRunnable, delayMs) } - // Schedules the five-minute warning off the same deadline the expiry alarm - // holds. Unlike the deadline this is advisory: a warning that cannot be - // scheduled must never stop a working tunnel, so nothing here fails closed. - // Dart re-pushes the deadline on every sync, so this runs about once a minute. + // Advisory, unlike the deadline itself: nothing here fails closed. Dart + // re-pushes the deadline every sync, so this runs about once a minute. private fun armExpiryWarning(runtimeToken: String, expiresAtEpochMs: Long) { if (runtimeToken.isEmpty()) return val warnAt = expiresAtEpochMs - RevoltAlerts.WARNING_LEAD_MS - // Deadline already inside the warning window (or past): either the alarm - // has fired and its notification should stay up, or this is the short - // bootstrap deadline at connect, which must not warn at all. Nothing is - // cancelled here - Dart re-pushes the same deadline every 60 s with no - // dedupe, so cancelling on this branch would reliably delete the armed - // warning on the first sync after it came due and never re-arm it. + // Inside the window already (or the short bootstrap deadline). Cancel + // nothing here: with no dedupe on the re-push, cancelling on this + // branch deletes the armed warning and never re-arms it. if (warnAt <= System.currentTimeMillis() + WARNING_REARM_GRACE_MS) return cancelSessionWarningAlarm() - // More than the lead away, so any warning on screen belongs to an older - // deadline - a support top-up just pushed it out. + // A warning on screen now belongs to an older deadline (top-up). RevoltAlerts.cancelExpiryWarning(this) try { val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager val pendingIntent = sessionWarningPendingIntent(runtimeToken) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - // Inexact on purpose: minute-level slop is fine for a warning, - // and it keeps this off the SCHEDULE_EXACT_ALARM path. + // Inexact on purpose - keeps this off SCHEDULE_EXACT_ALARM. alarmManager.setAndAllowWhileIdle( AlarmManager.RTC_WAKEUP, warnAt, @@ -522,8 +510,7 @@ class XrayVPNService : VpnService() { private fun handleSessionWarningAlarm(alarmToken: String) { val config = currentConfig if (config == null) { - // The alarm woke a service process with no live runtime; there is - // no session left to warn about. + // Woke a process with no live runtime; nothing to warn about. stopSelf() return } @@ -537,9 +524,8 @@ class XrayVPNService : VpnService() { if (remaining < WARNING_FLOOR_MS || remaining > RevoltAlerts.WARNING_LEAD_MS + WARNING_SLACK_MS ) { - // Too late to be a five-minute warning, or for a deadline that has - // moved. Saying "5 minutes" with seconds left is worse than silence; - // the disconnected alert follows either way. + // Too late, or the deadline moved. Saying "5 minutes" with + // seconds left is worse than silence. Log.w(TAG, "Ignoring session warning outside the warning window") return } @@ -707,10 +693,8 @@ class XrayVPNService : VpnService() { private fun cancelSessionWarningAlarm() { try { val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager - // Look the existing PendingIntent up instead of building one: with - // FLAG_UPDATE_CURRENT, constructing it to cancel rewrites the live - // alarm's RUNTIME_TOKEN to "" first, and a delivery already in - // flight would then be dropped as a stale generation. + // Look it up rather than build it: FLAG_UPDATE_CURRENT would + // rewrite the live alarm's RUNTIME_TOKEN to "" before cancelling. existingSessionWarningPendingIntent()?.let { alarmManager.cancel(it) } } catch (e: Exception) { Log.w(TAG, "Failed to cancel session-warning alarm", e) @@ -725,9 +709,8 @@ class XrayVPNService : VpnService() { return PendingIntent.getService(this, SESSION_WARNING_REQUEST_CODE, intent, flags) } - // A PendingIntent is identified by component plus request code, not extras, - // so the warning needs its own code or it would overwrite - and later - // cancel - the expiry alarm. + // Identity is component + request code, not extras, so the warning needs + // its own code or it clobbers the expiry alarm. private fun sessionWarningPendingIntent(runtimeToken: String): PendingIntent { val intent = Intent(this, XrayVPNService::class.java) .putExtra(EXTRA_SESSION_WARNING, true) @@ -814,13 +797,11 @@ class XrayVPNService : VpnService() { private const val EXTRA_SESSION_WARNING = "SESSION_WARNING" private const val SESSION_EXPIRY_REQUEST_CODE = 1001 private const val SESSION_WARNING_REQUEST_CODE = 1002 - // An idle-capable alarm can run late; accept that much drift before - // treating a warning as belonging to a deadline that has moved. + // Drift allowed before a warning is treated as belonging elsewhere. private const val WARNING_SLACK_MS = 60_000L - // Don't re-arm (and so re-post) for a deadline that only moved by the - // jitter in a network round trip. + // Don't re-arm for a deadline that moved by round-trip jitter alone. private const val WARNING_REARM_GRACE_MS = 15_000L - // Below this the warning has lost its point; stay quiet instead. + // Below this the warning has lost its point. private const val WARNING_FLOOR_MS = 60_000L } } diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt index 48ada2e..05c998a 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt @@ -12,23 +12,16 @@ import android.util.Log // local_packages/.../xray/utils/RevoltAlerts.kt // -// The two user-facing session alerts, built in one place because two processes -// post them: XrayVPNService (:RunSoLibXrayDaemon) owns the native deadline and -// can still warn when the UI process is gone, while MainActivity posts the -// "not protected" alert for session ends only Dart can see (cap exhausted, -// server ended the session, VPN error). Both use the same ids, so whichever -// posts second just replaces the first notification instead of stacking. -// -// These are deliberately NOT the foreground-service notification (id 1, -// channel REVOLT_VPN_SERVICE, IMPORTANCE_LOW): an alert the user must notice -// needs its own high-importance channel, and must be dismissible. +// The two session alerts. Both XrayVPNService (:RunSoLibXrayDaemon) and +// MainActivity post them, sharing ids so a second post replaces. Separate from +// the foreground-service notification (id 1, IMPORTANCE_LOW): these must be +// noticed, and must be dismissible. object RevoltAlerts { const val CHANNEL_ID = "REVOLT_VPN_ALERTS" const val WARNING_NOTIFICATION_ID = 2 const val DISCONNECTED_NOTIFICATION_ID = 3 - // How long before the session deadline the warning fires. const val WARNING_LEAD_MS = 5 * 60 * 1000L private const val TAG = "RevoltAlerts" @@ -97,8 +90,7 @@ object RevoltAlerts { .setSmallIcon(icon) .setAutoCancel(true) .setOngoing(false) - // Both processes can post the disconnected alert; the second - // post replaces the first and must not sound again. + // A replacing post must not sound again. .setOnlyAlertOnce(true) launchIntent(context)?.let { builder.setContentIntent(it) } @@ -118,9 +110,7 @@ object RevoltAlerts { private fun manager(context: Context): NotificationManager? = context.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager - // Importance is fixed when the channel is first created, so this asks for - // HIGH up front — a session alert the user never sees is the whole bug - // these notifications exist to fix. + // Importance is fixed at creation, so ask for HIGH up front. private fun ensureChannel(manager: NotificationManager) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return if (manager.getNotificationChannel(CHANNEL_ID) != null) return From 4e5c7a02db06127b4b7fb0e90c788e0036aa0652 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 15:37:29 +0300 Subject: [PATCH 09/17] fix(runtime): make Xray core recovery work, and stop it leaking a core per try Core recovery could never succeed, and every attempt left a live libxray.so behind. startCore() calls startTimer(), which builds a CountDownTimer and so a Handler on the calling thread. handleXrayCoreExit() runs recovery on a bare Thread, so the constructor threw "Can't create handler inside thread ... that has not called Looper.prepare()" and took the whole restart down with it. The catch then deleted the ephemeral config and returned false without killing the process pb.start() had already started, so each retry stranded another core. Measured on an emulator by killing the live core: before 1 -> 5 -> 6 -> 8 processes over 120 s, never recovers after "Xray core recovered without dropping TUN" on attempt 1, exactly 1 process startTimer now posts to the main looper, re-checking RUNTIME_TOKEN inside the post so a stop that lands while it is queued cannot leave a timer running for a dead generation. stopTimer posts too, so the countDownTimer field is only touched from one thread. The catch clears xrayProcess before destroying it, so the monitor thread's `xrayProcess === process` guard fails and recovery is not re-entered for a core being killed here. Pre-existing on main; reachable whenever the core exits. Co-Authored-By: Claude Opus 5 --- .../xray/core/XrayCoreManager.kt | 40 +++++++++++++++++-- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/core/XrayCoreManager.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/core/XrayCoreManager.kt index 54975b6..e7deba1 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/core/XrayCoreManager.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/core/XrayCoreManager.kt @@ -11,6 +11,8 @@ import android.content.pm.PackageManager import android.graphics.Color import android.os.Build import android.os.CountDownTimer +import android.os.Handler +import android.os.Looper import android.util.Log import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat @@ -383,6 +385,18 @@ object XrayCoreManager { } catch (e: Exception) { Log.e(TAG, "Failed to start Xray process", e) + // The process may already be running: pb.start() succeeds before + // anything below it can throw. Leaving it alive leaked one live + // core per recovery attempt. Clear the field BEFORE destroying so + // the monitor thread's `xrayProcess === process` guard fails and + // recovery is not re-entered for a core we are killing here. + val orphan = xrayProcess + xrayProcess = null + try { + orphan?.destroy() + } catch (destroyError: Exception) { + Log.w(TAG, "Failed to destroy partially started Xray process", destroyError) + } deleteEphemeralConfigOnFailure(configFilesDir) return false } @@ -429,7 +443,25 @@ object XrayCoreManager { AppConfigs.V2RAY_STATE == AppConfigs.V2RAY_STATES.V2RAY_CONNECTING } + // CountDownTimer builds a Handler, so it only constructs on a looper thread. + // Core recovery runs on a bare Thread (XrayVPNService.handleXrayCoreExit), + // where this threw "Can't create handler inside thread ... that has not + // called Looper.prepare()" and took the whole restart down with it. + private val mainHandler = Handler(Looper.getMainLooper()) + + private fun runOnMain(block: () -> Unit) { + if (Looper.myLooper() == Looper.getMainLooper()) block() else mainHandler.post(block) + } + private fun startTimer(context: Context) { + // Captured now: a stop that lands while the post is queued must not + // leave a timer ticking for a generation that is already gone. + val token = AppConfigs.V2RAY_CONFIG?.RUNTIME_TOKEN + runOnMain { startTimerOnMain(context, token) } + } + + private fun startTimerOnMain(context: Context, token: String?) { + if (AppConfigs.V2RAY_CONFIG?.RUNTIME_TOKEN != token) return countDownTimer?.cancel() seconds = 0 countDownTimer = object : CountDownTimer(Long.MAX_VALUE, 1000) { @@ -454,9 +486,11 @@ object XrayCoreManager { } private fun stopTimer() { - countDownTimer?.cancel() - countDownTimer = null - seconds = 0 + runOnMain { + countDownTimer?.cancel() + countDownTimer = null + seconds = 0 + } } fun sendStatusBroadcast(context: Context, config: XrayConfig) { From e7ef251882b95d77d168c54b2b82d3278911da64 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 15:37:29 +0300 Subject: [PATCH 10/17] fix(runtime): keep Xray's startup output so a failed core can be diagnosed The monitor thread read the core's merged stdout/stderr and dropped every line: process.inputStream.bufferedReader().use { reader -> reader.forEachLine { _ -> } } so the only trace of a core that died at startup was "Xray process exited with code 23", with nothing to say why. That exit is real and intermittent - it showed up on both a handset and an emulator - and was undiagnosable in the field. Keep at most 40 lines, and only from the core's first 10 seconds, then log them when the exit code is non-zero. A core up longer than that may be carrying traffic and its log can name destinations, which must never reach the device log (rule 95), so past the window the buffer is dropped rather than kept. Co-Authored-By: Claude Opus 5 --- .../xray/core/XrayCoreManager.kt | 30 +++++++++++++++++-- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/core/XrayCoreManager.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/core/XrayCoreManager.kt index e7deba1..16a4348 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/core/XrayCoreManager.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/core/XrayCoreManager.kt @@ -39,6 +39,13 @@ object XrayCoreManager { private const val NOTIFICATION_ID = 1 private const val TAG = "XrayCoreManager" + + // The core's output is kept only for its first seconds, and only to explain + // a non-zero exit. A core that has been up longer than this may be carrying + // traffic, and its log can name destinations, which must never reach the + // device log (rule 95) - so past the window the buffer is dropped. + private const val STARTUP_LOG_WINDOW_MS = 10_000L + private const val STARTUP_LOG_MAX_LINES = 40 private var xrayProcess: Process? = null private var countDownTimer: CountDownTimer? = null private var seconds = 0 @@ -349,12 +356,29 @@ object XrayCoreManager { // Monitor process in a separate thread to detect crash Thread { try { + val startedAt = System.currentTimeMillis() + val startupLog = ArrayDeque() process.inputStream.bufferedReader().use { reader -> - reader.forEachLine { _ -> } + reader.forEachLine { line -> + if (System.currentTimeMillis() - startedAt <= STARTUP_LOG_WINDOW_MS) { + if (startupLog.size >= STARTUP_LOG_MAX_LINES) startupLog.removeFirst() + startupLog.addLast(line) + } else if (startupLog.isNotEmpty()) { + startupLog.clear() + } + } } - + val exitCode = process.waitFor() - Log.e(TAG, "Xray process exited with code $exitCode") + if (exitCode != 0 && startupLog.isNotEmpty()) { + Log.e( + TAG, + "Xray process exited with code $exitCode; startup output:\n" + + startupLog.joinToString("\n") + ) + } else { + Log.e(TAG, "Xray process exited with code $exitCode") + } if (xrayProcess === process && AppConfigs.V2RAY_CONFIG?.RUNTIME_TOKEN == config.RUNTIME_TOKEN && (AppConfigs.V2RAY_STATE == AppConfigs.V2RAY_STATES.V2RAY_CONNECTED || From eab43b04207a2f88106389c01c988f036a0cc8e9 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 16:14:48 +0300 Subject: [PATCH 11/17] fix(session): deliver the expiry warning when the app is closed The five-minute warning did not arrive in the one case it exists for. The deadline is enforced by two things - a main-looper Handler and an alarm - while the warning had only the alarm, and that alarm is inexact on purpose so the app can stay off SCHEDULE_EXACT_ALARM. Doze defers an inexact alarm freely, and with the app closed it deferred this one past the end of the session it was warning about. Measured on an emulator, app swiped from recents and its process killed, screen off, deviceidle forced to IDLE, 7-minute session: before warning never fired; request code 1002 never delivered and handleSessionWarningAlarm never ran. Expiry was still punctual (16:00:55 against a 16:00:54 deadline) because the deadline has its Handler. after warning posted as the session crossed 300 s remaining, app still closed and device still IDLE; expiry unchanged. So give the warning the same backstop that already makes the deadline reliable. postDelayed runs on uptimeMillis, so a genuinely suspended device still fires it late - handleSessionWarningAlarm then drops it on the existing window check instead of claiming "5 minutes" with seconds left. The alarm stays for the case where the process was restarted and no Handler callback survives. Note this does not make the warning punctual under true suspend; only SCHEDULE_EXACT_ALARM would, and that permission is deliberately not declared. Co-Authored-By: Claude Opus 5 --- .../xray/service/XrayVPNService.kt | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt index 44675e1..67a6e4e 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/service/XrayVPNService.kt @@ -45,6 +45,14 @@ class XrayVPNService : VpnService() { private var sessionDeadlineToken: String? = null private val sessionDeadlineRunnable = Runnable { enforceSessionDeadline() } + // The warning's own backstop, mirroring the deadline's. The alarm alone is + // not enough: it is inexact on purpose (no SCHEDULE_EXACT_ALARM), and with + // the app closed on a dozing device it was measured never arriving at all, + // while the deadline's Handler fired within a second of its target. + private val sessionWarningRunnable = Runnable { + handleSessionWarningAlarm(sessionDeadlineToken.orEmpty()) + } + override fun onCreate() { super.onCreate() } @@ -505,6 +513,17 @@ class XrayVPNService : VpnService() { } catch (e: Exception) { Log.w(TAG, "Failed to schedule session-expiry warning", e) } + + // postDelayed runs on uptimeMillis, so a truly suspended device still + // fires this late - handleSessionWarningAlarm then rejects it on the + // window check rather than claiming "5 minutes" with seconds left. + // Whenever the process is merely backgrounded, which is the common + // case, this is what actually delivers the warning. + val warnDelay = warnAt - System.currentTimeMillis() + deadlineHandler.removeCallbacks(sessionWarningRunnable) + if (warnDelay > 0L) { + deadlineHandler.postDelayed(sessionWarningRunnable, warnDelay) + } } private fun handleSessionWarningAlarm(alarmToken: String) { @@ -691,6 +710,7 @@ class XrayVPNService : VpnService() { } private fun cancelSessionWarningAlarm() { + deadlineHandler.removeCallbacks(sessionWarningRunnable) try { val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager // Look it up rather than build it: FLAG_UPDATE_CURRENT would From 296b087db66caeddb677f4855c4e5417b917c8b7 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 16:26:41 +0300 Subject: [PATCH 12/17] fix(session): take down the countdown notification when the tunnel stops Disconnecting the VPN from Android's own settings left "Revolt VPN 00:28:13" in the shade, frozen, for as long as the phone stayed up - a notification claiming a protected session over a tunnel that was gone. updateTimer() re-posts notification id 1 as ongoing and non-dismissible from the UI process, every tick. The service cancels its own foreground copy when it stops, but a tick landing just after that re-creates it as an ordinary notification nobody owns, and nothing ever cancelled it: NotificationService.reset() only clears the dedupe cache. AGENTS.md rule 31 describes the cancel this restores. _doDisconnect now cancels it, after vpnConnection.disconnect() so the service is already down - cancelling while it is still in the foreground would be swallowed by the platform. Verified on an emulator, revoking via Settings -> VPN -> Disconnect: before countdown stranded at 00:28:13 indefinitely after no live notifications User disconnect still posts no alert, and expiry still posts "Revolt VPN disconnected" with the countdown gone. Co-Authored-By: Claude Opus 5 --- .../kotlin/com/paladinvpn/app/MainActivity.kt | 12 ++++++++++++ lib/logic/notification_service.dart | 15 +++++++++++++++ lib/logic/session_timer.dart | 4 ++++ 3 files changed, 31 insertions(+) diff --git a/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt b/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt index 662b60a..d3cbfb3 100644 --- a/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt +++ b/android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt @@ -75,6 +75,18 @@ class MainActivity : FlutterActivity() { RevoltAlerts.postDisconnected(this) result.success(null) } + // The countdown re-post is ongoing and non-dismissible, so + // whoever posted it last has to take it down. A tick that + // lands after the service cancelled its own foreground + // notification otherwise strands a frozen countdown that + // claims a protected session forever. Harmless while the + // service is still in the foreground - the platform keeps + // its notification regardless. + "cancelNotification" -> { + (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) + .cancel(NOTIFICATION_ID) + result.success(null) + } else -> result.notImplemented() } } diff --git a/lib/logic/notification_service.dart b/lib/logic/notification_service.dart index bf830d2..e3ee070 100644 --- a/lib/logic/notification_service.dart +++ b/lib/logic/notification_service.dart @@ -41,6 +41,21 @@ class NotificationService { } } + /// Takes down the countdown notification. + /// + /// [updateTimer] re-posts an ongoing, non-dismissible notification, so a tick + /// that lands after the VPN service has cancelled its own foreground copy + /// leaves a frozen countdown on screen that nobody owns. Call this once the + /// tunnel is actually down. + static Future cancelTimer() async { + _lastText = null; + try { + await _channel.invokeMethod('cancelNotification'); + } catch (_) { + // Cosmetic. + } + } + /// Forces the next connect to re-post even if the countdown resumes on the /// same value. static void reset() => _lastText = null; diff --git a/lib/logic/session_timer.dart b/lib/logic/session_timer.dart index f5196da..d55ee1c 100644 --- a/lib/logic/session_timer.dart +++ b/lib/logic/session_timer.dart @@ -270,6 +270,10 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { notifyListeners(); await vpnConnection.disconnect(); + // After the service is down, so the cancel is not swallowed by a still + // foreground notification. Without it a revoke leaves the countdown on + // screen, frozen, claiming a session that no longer protects anything. + await NotificationService.cancelTimer(); if (endedMessage != null && postAlert) { unawaited(NotificationService.showDisconnectedAlert()); } From 00b84dde61c2693317a662e309f812a75a6e2e1f Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 16:26:41 +0300 Subject: [PATCH 13/17] fix(session): stop the expiry warning promising a time and an ad it cannot honour The warning said "Revolt VPN disconnects in 5 minutes" / "Watch an ad to extend your session." Both can be wrong. handleSessionWarningAlarm accepts the warning anywhere between WARNING_FLOOR_MS and WARNING_LEAD_MS + WARNING_SLACK_MS remaining, so it can say "5 minutes" with just over one left. And the ad is a dead end in a release build: AdManager.showAd('support') is still kDebugMode-gated (rule 87), so the support button does nothing there - and nothing at all in a build shipped with ads off. Say neither. The comment records what has to change for the number and the ad to come back. Co-Authored-By: Claude Opus 5 --- .../tfox/flutter_vless/xray/utils/RevoltAlerts.kt | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt index 05c998a..d014dc3 100644 --- a/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt +++ b/local_packages/flutter_vless_android-1.1.5/android/src/main/kotlin/com/github/tfox/flutter_vless/xray/utils/RevoltAlerts.kt @@ -27,12 +27,19 @@ object RevoltAlerts { private const val TAG = "RevoltAlerts" private const val LAUNCH_REQUEST_CODE = 2001 + // Neither line names a number or a mechanism, because this notification + // cannot honour either. The caller accepts it anywhere from WARNING_FLOOR_MS + // to WARNING_LEAD_MS + WARNING_SLACK_MS remaining, so "5 minutes" can be + // off by four of them; and "watch an ad" is a dead end in a release build, + // where the support bypass is still kDebugMode-gated (rule 87). Put the + // number back once the warning is punctual, and the ad back once the + // support button works without a debug build. fun postExpiryWarning(context: Context) { post( context, WARNING_NOTIFICATION_ID, - "Revolt VPN disconnects in 5 minutes", - "Watch an ad to extend your session.", + "Revolt VPN disconnects soon", + "Open the app to extend your session.", ) } From e67f0b93eeff08b9f184d764519b3c76713e917b Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 16:31:51 +0300 Subject: [PATCH 14/17] feat(session): hand the session back when the user disconnects The client never called /session/stop - the string appears nowhere in lib/ or local_packages/, on this branch or on main - while the server has implemented the route all along (hivemind/api.py:237) and AGENTS.md rule 33 documents its ordering. Across a full device test session, two user disconnects and several expiries, the control plane logged zero calls. So a disconnect left the VLESS client provisioned in the Reality inbound and the session dict in memory and sessions.json until its window ran out. Anyone holding that UUID could keep tunnelling for the remainder. Users were not locked out of their quota - _handle_main replaces the session with a fresh full-length one on the next connect - so this is hygiene rather than a user-facing bug. Only SessionTimer.disconnect() calls it, which is reached only from the connect button. Expiry, the hard cap and a server-ended session are already gone server-side, and the route takes nothing but a device_id as proof of ownership, so no error path may reach it. Unawaited and capped at 3 s, so an unreachable API cannot delay the teardown, and every failure is swallowed: the session expires on its own regardless. Verified against a mock control plane: user disconnect POST /api/session/stop -> session removed expiry no call; alert still posted Co-Authored-By: Claude Opus 5 --- lib/logic/hivemind_service.dart | 65 +++++++++++++++++++++++++++++++++ lib/logic/session_timer.dart | 4 ++ 2 files changed, 69 insertions(+) diff --git a/lib/logic/hivemind_service.dart b/lib/logic/hivemind_service.dart index 007bd71..81111df 100644 --- a/lib/logic/hivemind_service.dart +++ b/lib/logic/hivemind_service.dart @@ -76,6 +76,71 @@ class HivemindService { } } + static Future controlPost( + Uri uri, + Map body, { + Duration timeout = const Duration(seconds: 5), + }) async { + final client = http.Client(); + final request = http.Request('POST', uri) + ..headers['User-Agent'] = _ua + ..headers['Content-Type'] = 'application/json' + ..body = jsonEncode(body) + ..followRedirects = false; + + Future send() async { + final streamed = await client.send(request); + final declaredLength = streamed.contentLength; + if (declaredLength != null && declaredLength > _maxControlResponseBytes) { + throw const FormatException('Control response is too large.'); + } + + final bytes = []; + await for (final chunk in streamed.stream) { + if (bytes.length + chunk.length > _maxControlResponseBytes) { + throw const FormatException('Control response is too large.'); + } + bytes.addAll(chunk); + } + + return http.Response.bytes(bytes, streamed.statusCode, + headers: streamed.headers, request: request); + } + + try { + return await send().timeout( + timeout, + onTimeout: () { + client.close(); + throw TimeoutException('Control request timed out.', timeout); + }, + ); + } finally { + client.close(); + } + } + + // Hands the session back so the server can drop the VLESS client instead of + // leaving it provisioned until the window runs out. + // + // Only the user-initiated disconnect calls this. An expiry, a hard cap or a + // server-ended session is already gone server-side, and /session/stop takes + // nothing but a device_id as proof (hivemind/api.py notes this), so a + // transient client error must never be allowed to destroy a live session. + // Best effort throughout: the session expires on its own regardless. + static Future releaseSession() async { + try { + final deviceId = await CryptoService.getDeviceId(); + await controlPost( + _publicUrl('/session/stop'), + {'device_id': deviceId}, + timeout: const Duration(seconds: 3), + ); + } catch (_) { + // Nothing to recover: the server expires the session anyway. + } + } + static void cancel() { _currentCallId++; _expectedNonce = null; diff --git a/lib/logic/session_timer.dart b/lib/logic/session_timer.dart index d55ee1c..44e54e7 100644 --- a/lib/logic/session_timer.dart +++ b/lib/logic/session_timer.dart @@ -241,6 +241,10 @@ class SessionTimer extends ChangeNotifier with WidgetsBindingObserver { } Future disconnect({String reason = 'User requested'}) async { + // Only here, not in _doDisconnect: this is the one path the user actually + // asked for. Unawaited so a slow or unreachable API never holds up the + // teardown. + unawaited(HivemindService.releaseSession()); await _doDisconnect(reason); } From 437d998663ddc0e150137ca5126c0c6d02dae3c1 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 16:35:53 +0300 Subject: [PATCH 15/17] docs(changelog): record the session-end fixes, and correct a claim The Unreleased entry said the five-minute warning "still arrives when the app is closed". Device testing showed it did not: it was scheduled only on an inexact alarm, which Doze deferred past the end of the session it was warning about. That is now true rather than aspirational, and the entry no longer promises an exact number of minutes, because the warning can legitimately arrive anywhere inside its window. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dcfdacd..ba67678 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,9 +8,11 @@ Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH ## [Unreleased] ### Added -- **Five-minute warning before a session ends.** The VPN service schedules it - off the same deadline it already enforces, so the warning still arrives when - the app is closed, and a support top-up moves it with the deadline. +- **A warning before a session ends.** The VPN service schedules it off the same + deadline it already enforces, so it still arrives when the app is closed, and + a support top-up moves it with the deadline. It does not promise an exact + number of minutes: on a sleeping phone Android may hold it back, and the app + would rather say "soon" than say "5 minutes" with one left. - **"Disconnected — not protected" notification** when a session ends without you asking: the 2-hour expiry, the data limit, the server ending the session, or the tunnel stopping unexpectedly. @@ -38,6 +40,22 @@ Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH - **SOCKS5 "Reconnect" re-attaches to the current session** instead of requesting a new one, so repairing a lost proxy no longer needs (or grants) a fresh session. +- **The end-of-session warning now actually arrives when the app is closed.** + It was scheduled only on an inexact alarm, and a sleeping phone could hold + that alarm back past the end of the session it was warning about — so in the + one case the warning exists for, it never came. It now also runs off the VPN + service's own timer, the same one that already ends the session on time. +- **Disconnecting from Android's VPN settings no longer leaves a countdown in + the notification shade.** It used to sit there frozen, showing time remaining + on a tunnel that was already gone. +- **The VPN reconnects itself after the tunnel core stops.** Recovery never + worked: every attempt failed on the same internal error, and each one left + another copy of the core running in the background. One restart now brings it + back without dropping the connection. +- **Disconnecting now releases your session on the server** instead of leaving + it open until it expires on its own. +- **A core that fails to start now says why.** Its output was being thrown + away, so the only trace was an exit code. --- From 52e8cd8ca17648aa22d165a81daf0c0ad25e0179 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 16:37:41 +0300 Subject: [PATCH 16/17] test: pin the session-lifecycle fixes against silent regression Source assertions, in the style of the existing release-verification test. Every behaviour here was found broken on a device and fixed today; none can be covered by an ordinary Dart test, because they live in the vendored Android runtime or need a live tunnel. They all regress silently, and each one looks like tidying when it does - inlining a CountDownTimer, dropping a Handler callback, restoring a friendlier notification string. Checked that they fail without the fixes, not just that they pass with them: restoring the "disconnects in 5 minutes" wording and moving releaseSession() out of disconnect() both turn them red. Co-Authored-By: Claude Opus 5 --- test/session_lifecycle_regression_test.dart | 134 ++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 test/session_lifecycle_regression_test.dart diff --git a/test/session_lifecycle_regression_test.dart b/test/session_lifecycle_regression_test.dart new file mode 100644 index 0000000..e282042 --- /dev/null +++ b/test/session_lifecycle_regression_test.dart @@ -0,0 +1,134 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +// Source assertions, in the style of release_verification_regression_test.dart. +// The behaviours below were all found broken on a device and fixed on +// 2026-10-17 (internal/DEVICE_TEST_2026-10-17.md). None of them can be covered +// by a Dart unit test - they live in the vendored Android runtime, and the one +// that does not needs a live tunnel - but every one of them regresses silently +// and looks like tidying when it does. Pin the shape instead of the behaviour. + +const _runtime = 'local_packages/flutter_vless_android-1.1.5/android/src/main/' + 'kotlin/com/github/tfox/flutter_vless/xray'; + +void main() { + test('Xray core recovery survives running off a bare thread', () { + final core = File('$_runtime/core/XrayCoreManager.kt').readAsStringSync(); + + // startTimer builds a CountDownTimer, which builds a Handler. Recovery runs + // on a plain Thread, so constructing it inline threw Looper.prepare() and + // killed every restart attempt. + expect(core, contains('Handler(Looper.getMainLooper())')); + expect(core, contains('runOnMain')); + expect( + core, + contains('runOnMain { startTimerOnMain(context, token) }'), + reason: 'startTimer must not construct the CountDownTimer inline', + ); + + // The post must not outlive the generation that scheduled it. + expect(core, contains('if (AppConfigs.V2RAY_CONFIG?.RUNTIME_TOKEN != token) return')); + + // pb.start() succeeds before the throw, so the catch has to kill the + // process or each retry strands another live core. + expect(core, contains('val orphan = xrayProcess')); + expect( + core.indexOf('xrayProcess = null'), + lessThan(core.indexOf('orphan?.destroy()')), + reason: 'clear the field before destroying, so the monitor thread\'s ' + 'identity guard fails and recovery is not re-entered', + ); + }); + + test('a failed Xray core still reports why, without logging destinations', () { + final core = File('$_runtime/core/XrayCoreManager.kt').readAsStringSync(); + + expect(core, contains('STARTUP_LOG_WINDOW_MS')); + expect(core, contains('STARTUP_LOG_MAX_LINES')); + expect( + core, + isNot(contains('reader.forEachLine { _ -> }')), + reason: 'discarding the core output leaves exit 23 undiagnosable', + ); + // Rule 95: a core that has been up long enough to carry traffic must not + // have its log retained. + expect(core, contains('startupLog.clear()')); + }); + + test('the expiry warning has the same backstop as the deadline', () { + final service = File('$_runtime/service/XrayVPNService.kt').readAsStringSync(); + + // The alarm alone is inexact on purpose (no SCHEDULE_EXACT_ALARM) and Doze + // deferred it past the end of the session it was warning about. + expect(service, contains('sessionWarningRunnable')); + expect( + service, + contains('deadlineHandler.postDelayed(sessionWarningRunnable, warnDelay)'), + reason: 'without this the warning never arrives when the app is closed', + ); + expect( + service, + contains('deadlineHandler.removeCallbacks(sessionWarningRunnable)'), + reason: 'a cancelled warning must drop its Handler callback too', + ); + expect(service, isNot(contains('SCHEDULE_EXACT_ALARM"'))); + }); + + test('the warning promises neither a number of minutes nor an ad', () { + final alerts = File('$_runtime/utils/RevoltAlerts.kt').readAsStringSync(); + + // It is accepted anywhere from WARNING_FLOOR_MS to LEAD + SLACK remaining, + // so a figure can be off by minutes; and the support bypass is still + // kDebugMode-gated (rule 87), so an ad is a dead end in release. + expect(alerts, isNot(contains('disconnects in 5 minutes'))); + expect(alerts, isNot(contains('Watch an ad'))); + expect(alerts, contains('Revolt VPN disconnects soon')); + }); + + test('the countdown notification is taken down when the tunnel stops', () { + final service = File('lib/logic/notification_service.dart').readAsStringSync(); + final timer = File('lib/logic/session_timer.dart').readAsStringSync(); + final activity = + File('android/app/src/main/kotlin/com/paladinvpn/app/MainActivity.kt') + .readAsStringSync(); + + // updateTimer re-posts an ongoing, non-dismissible notification every tick, + // so a tick after the service stops strands a frozen countdown. + expect(service, contains('cancelTimer')); + expect(activity, contains('"cancelNotification"')); + expect(timer, contains('await NotificationService.cancelTimer()')); + + // Must run after the service is down, or the platform swallows the cancel. + expect( + timer.indexOf('await vpnConnection.disconnect();'), + lessThan(timer.indexOf('await NotificationService.cancelTimer()')), + ); + }); + + test('only a user-requested disconnect hands the session back', () { + final timer = File('lib/logic/session_timer.dart').readAsStringSync(); + final hivemind = File('lib/logic/hivemind_service.dart').readAsStringSync(); + + expect(hivemind, contains('releaseSession')); + expect(hivemind, contains("_publicUrl('/session/stop')")); + + // /session/stop takes a device_id as its only proof of ownership, so it + // must never be reachable from an error path. disconnect() is called only + // by the connect button; _doDisconnect is every other ending. + final disconnectEntry = timer.indexOf('Future disconnect('); + final doDisconnect = timer.indexOf('Future _doDisconnect('); + final release = timer.indexOf('HivemindService.releaseSession()'); + expect(release, greaterThan(disconnectEntry)); + expect( + release, + lessThan(doDisconnect), + reason: 'releaseSession belongs in disconnect(), not _doDisconnect', + ); + expect( + 'HivemindService.releaseSession()'.allMatches(timer).length, + 1, + reason: 'exactly one call site', + ); + }); +} From 550402a66394377d40b0628b74c0317298e42057 Mon Sep 17 00:00:00 2001 From: esefxdz Date: Sat, 17 Oct 2026 16:46:49 +0300 Subject: [PATCH 17/17] chore(release): 3.3.7 Version and changelog together (rule 24). The in-app updater compares PackageInfo.version against the GitHub tag, so the tag and this must agree or an update is offered forever. Co-Authored-By: Claude Opus 5 --- CHANGELOG.md | 2 +- pubspec.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ba67678..8c6e9b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH --- -## [Unreleased] +## [3.3.7] — 2026-10-17 ### Added - **A warning before a session ends.** The VPN service schedules it off the same diff --git a/pubspec.yaml b/pubspec.yaml index 52a3186..4d9c1d0 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,7 +15,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html -version: 3.3.6+32 +version: 3.3.7+33 environment: sdk: ">=3.0.0 <4.0.0"