97 Commits
Author SHA1 Message Date
esefxdzandClaude Opus 5 f28379f73f Merge branch 'docs/privacy-policy-accuracy'
Android CI / android (push) Canceled after 0s
Co-Authored-By: Claude Opus 5 <[email protected]>
2026-10-18 13:47:36 +03:00
esefxdzandClaude Opus 5 8260c7cc0a docs(privacy): correct the policy the app actually links to
The sidebar opens this file, so it is the copy users read, and it had
drifted from the service it describes.

- the device ID is stored on the phone and reused between sessions; the
  policy implied it was per-session
- "we do not sell or share any data with third parties" sat in the same
  document as the AdMob section that explains Google collects data for
  ad delivery; narrowed to what is true
- dropped the service name and journalctl invocation from the log
  paragraph; operational detail nobody reading a privacy policy needs

Now byte-identical to the copy on the website.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-10-18 13:41:57 +03:00
esefxdzandClaude Opus 5 62e968f133 fix(app): stop probing the control plane while disconnected
Android CI / android (push) Canceled after 0s
VpnConnection._init() started a 30 s /health poll from the constructor
with no lifecycle gating, so it ran for the life of the app process -
backgrounded, and whether or not the user ever connected. The app is
excluded from its own tunnel, so those requests left in the clear. A
periodic request that fires while the user is deliberately not connected
is an avoidable fingerprint, and rule 60 already ruled probes out:
reachability is meant to be passive.

All it bought was the status dot before the first connect, and it got
that wrong in both directions - "Offline" on a transient resolver
failure against a server that was fine.

Reachability now comes from a session sync that succeeded. serverHealthy
is isConnected && hasSyncedOnce, so a green dot means a working session
rather than a check made beforehand; while disconnected the bar reads
"Ready" and claims nothing either way.

checkHealth() goes with it. Nothing calls it, and leaving a probe helper
in place invites its reuse.

Pinned in test/session_lifecycle_regression_test.dart so it cannot come
back as a tidy-up. flutter analyze clean, 10/10 tests pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-10-17 21:17:17 +03:00
esefxdzandClaude Opus 5 571c07bca8 feat(session): every reconnect starts a fresh session
Android CI / android (push) Canceled after 0s
SOCKS5 Reconnect re-attached to the session the device already held. It
was the only path where a session began without an ad and without a
nonce binding it to one, and supporting it cost three parameters -
resume, release, resetSupportClaim - plus a carve-out in rule 4 that let
_fetchActiveSession accept whatever nonce the server happened to return.

It also wasn't the kindness it looked like. _handle_main calls
create_or_replace with a fresh full window, so a new session hands the
user *more* time, not less; re-attaching only preserved the remainder of
a session whose proxy had just died.

Reconnect now disconnects and connects again exactly as the button does,
ad included. All four special cases are deleted and the nonce check is
unconditional.

Costs one rewarded ad to repair an orphaned proxy once ads are enabled.
esef's call, and it buys a single way to start a session.

Also fixes the 3.3.7 regression where Reconnect released the session and
then asked for it back: there is no longer a path that does either.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-10-17 18:53:42 +03:00
esefxdzandClaude Opus 5 73d76c04f2 docs(changelog): correct 3.3.7, which advertised behaviour it does not have
Android CI / android (push) Canceled after 0s
A Fable review checked every entry against the commits in the release and
found the SOCKS5 Reconnect bullet is false for the shipped binary: tag
v3.3.7 contains e67f0b9 (/session/stop) but not e751a9d (the fix), so in
that build Reconnect ends the session instead of re-attaching. The public
changelog promised the opposite. It now carries a Known issue box naming
the symptom and the workaround.

Also corrected, same review:

- The warning's "now actually arrives when the app is closed" named the
  sleeping-phone case and claimed to fix it. It does not: the backstop is
  Handler.postDelayed on uptimeMillis, which stalls under true suspend,
  and a late delivery is then dropped by the window check - so the
  failure mode there is no warning, not a late one. The evidence was an
  emulator under forced idle, which never suspends the CPU. Dropped the
  Fixed entry (the feature is new in 3.3.7 anyway, so it fixed no
  released bug) and let the honest Added bullet carry it.
- /session/stop fires only from the app's own disconnect button, not on
  expiry, cap, revoke or a kill. Scoped the claim.
- The ad entry moved to Groundwork: ads are off in this build and the
  path was reviewed, never exercised against a real SSV callback.
- "One restart now brings it back" rested on one emulator run killing a
  warm core, and the cold-start exit-23 is unfixed. Softened.
- Core recovery "says why" -> logs why; no user sees it.
- Added the two countdown fixes from d1ea13b and 34722c7, which were
  user-visible and had no entry at all.
- Dropped "the tunnel stopping unexpectedly": that path never reaches
  stopAll, so no alert is posted for it.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-10-17 18:22:19 +03:00
esefxdzandClaude Opus 5 e751a9d6e4 fix(session): don't release the session on a SOCKS5 Reconnect
Android CI / android (push) Canceled after 0s
Regression from e67f0b9, shipped in 3.3.7.

Reconnect repairs an orphaned proxy by tearing the runtime down and
re-attaching to the session the device already holds. It does that
through SessionTimer.disconnect(), which e67f0b9 taught to hand the
session back to the server - so it destroyed the very session the
following connect(resume: true) then asked for. Unawaited, so it raced:
the resume either found the session already gone or removed moments
later, surfacing as "Session not activated".

disconnect() now takes release, and the Reconnect path passes false.
Every other caller still hands the session back.

Narrow in practice: SOCKS5 mode only, only the Settings Reconnect
button, and the main-screen connect was unaffected because it mints a
new session anyway.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-10-17 17:17:29 +03:00
esefxdz c8617835b1 Merge branch 'fix/device-test-findings'
Android CI / android (push) Canceled after 0s
2026-10-17 16:47:29 +03:00
esefxdzandClaude Opus 5 550402a663 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 <[email protected]>
2026-10-17 16:46:49 +03:00
esefxdzandClaude Opus 5 52e8cd8ca1 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 <[email protected]>
2026-10-17 16:37:41 +03:00
esefxdzandClaude Opus 5 437d998663 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 <[email protected]>
2026-10-17 16:35:53 +03:00
esefxdzandClaude Opus 5 e67f0b93ee 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 <[email protected]>
2026-10-17 16:31:51 +03:00
esefxdzandClaude Opus 5 00b84dde61 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 <[email protected]>
2026-10-17 16:26:41 +03:00
esefxdzandClaude Opus 5 296b087db6 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 <[email protected]>
2026-10-17 16:26:41 +03:00
esefxdzandClaude Opus 5 eab43b0420 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 <[email protected]>
2026-10-17 16:14:48 +03:00
esefxdzandClaude Opus 5 e7ef251882 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 <[email protected]>
2026-10-17 15:37:29 +03:00
esefxdzandClaude Opus 5 4e5c7a02db 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 <[email protected]>
2026-10-17 15:37:29 +03:00
esefxdzandClaude Opus 5 30d96a4049 style: cut the comments down
Co-Authored-By: Claude Opus 5 <[email protected]>
2026-10-17 00:50:36 +03:00
esefxdzandClaude Opus 5 66789d49c1 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 <[email protected]>
2026-10-17 00:47:23 +03:00
esefxdzandClaude Opus 5 8ba3b6c543 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 <[email protected]>
2026-10-17 00:44:51 +03:00
esefxdzandClaude Opus 5 d1ea13b01a 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 <[email protected]>
2026-10-17 00:38:08 +03:00
esefxdzandClaude Opus 5 34722c751b 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 <[email protected]>
2026-10-17 00:25:17 +03:00
esefxdzandClaude Opus 5 dd1082c8de 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 <[email protected]>
2026-10-17 00:22:26 +03:00
esefxdzandClaude Opus 5 742f37683e 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 <[email protected]>
2026-10-17 00:02:20 +03:00
esefxdzandClaude Opus 5 37753c6396 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 <[email protected]>
2026-10-16 23:51:19 +03:00
esefxdzandClaude Opus 5.5 e14e900276 chore(release): prepare 3.3.6
- fix(app): Test Local SOCKS forces a round trip instead of trusting the CONNECT reply
- changelog: notification icon + SOCKS test fixes

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-08 13:20:52 +03:00
esefxdz 6d8a923475 notification fixed 2026-09-06 13:07:37 +03:00
esefxdz 4718a5912a build(android): pin Windows aapt2 checksum for local release builds 2026-09-06 12:37:20 +03:00
esefxdz 5d2683f354 chore(release): prepare 3.3.5 2026-09-06 12:09:20 +03:00
esefxdz 08b21dc5d9 docs(contributing): drop server/xray/nginx scopes 2026-09-06 12:09:20 +03:00
esefxdz bbc83ea425 chore(app): lint cleanups (const constructors, local function) 2026-09-06 12:09:16 +03:00
esefxdzandClaude Opus 5 9d67679fa8 fix(app): do not throw from ConnectionSettings.initialize
The migration write is best-effort again. `_mode` is already the safe TUN
default in memory by the time it runs, so a failed write leaves nothing
insecure -- it only means the migration is retried on the next launch.

Throwing there was a startup brick rather than a fail-closed guard.
`initialize()` is awaited from `main()` at lib/main.dart:19, before
`runApp()`, with no try/catch and no `runZonedGuarded`; `FlutterError.onError`
and `PlatformDispatcher.onError` are installed later and would not catch it
either. The branch also runs on every fresh install, since `storedMode` is null
and `null != 'tun'`. A `setString` returning false would therefore have meant a
black screen with no error UI, repeating every launch, in exchange for no
security benefit.

Also restores two comments this PR removed from code it does not otherwise
touch -- the `_reconnect` note on why the repair path shows no rewarded ad, and
the explanation of how an orphaned proxy outlives the app process -- and drops
a stray 'ass' from the legacy-values comment.

The `setMode` half of the PR is unchanged: persisting before mutating memory
and surfacing failures to the UI is the right behaviour.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019HT2x2JvJNg7XNsJubfHFf
2026-09-06 11:51:52 +03:00
Naveax 3f7aead263 fix(app): fail closed on invalid connection mode state
Restore SOCKS5 only from the current proxy value and keep UI state unchanged when persistence fails.
2026-09-06 11:51:52 +03:00
Naveax b6ed976346 fix(app): harden Hivemind control-plane trust boundaries (#8)
Bound and nonce-bind control responses, reject redirects, and pin session tunnel coordinates so control-plane compromise cannot redirect VPN traffic.
2026-09-06 11:34:06 +03:00
esefxdzandClaude Opus 5 bd41a3c693 refactor(app): drop Dart wrappers whose native handlers no longer exist
#17 removed the `setSessionExpiry` and `isVpnRuntimeAlive` MethodChannel
handlers from MainActivity, and #18 removed their last callers. The Dart
wrappers stayed behind.

Both swallow their errors, so a future caller would not fail loudly — it would
get a silent no-op from `setSessionExpiry` and a permanent
`processAlive: false` from `runtimeState()`, which previously read as "the
tunnel is dead". Deleting them keeps that trap out of the codebase.

`VpnRuntimeState` goes with them; runtime liveness now arrives through the
native status stream, which is generation-scoped. The battery-optimisation
methods are untouched and still used by background_reliability.dart.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019HT2x2JvJNg7XNsJubfHFf
2026-09-06 11:28:52 +03:00
esefxdzandClaude Opus 5 061bd41920 Merge pull request #19 from Naveax/pr/add-android-supply-chain-ci
build: add reproducible Android release verification

Resolved a conflict in android/app/build.gradle.kts. #19 was written against
the pre-#10 file and re-added the pub-cache patch tasks that #10 deleted; only
`sha256Hex()` was kept from that block, since `verifyReleaseAppConfig` needs it.

Also restored `import java.io.File`, which #10 removed along with the patch
tasks. #19's `sha256Hex(file: File)` names the type in its signature, and
Kotlin does not auto-import `java.io.File`, so the release build would have
failed at Gradle configuration without it.

Verified after resolution: no orphaned references to `projectRootDir`,
`localProperties`, `flutterSdkPath` or `patchFlutterVless`; both tests in
test/release_verification_regression_test.dart pass; `flutter analyze` reports
no errors or warnings.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019HT2x2JvJNg7XNsJubfHFf
2026-09-06 11:27:28 +03:00
Naveax ba89e35442 fix(app): harden session runtime lifecycle (#18)
Scope asynchronous connect, disconnect, sync, and reattachment work to the active session so stale work cannot mutate newer VPN state.
2026-09-06 11:24:03 +03:00
Naveax 321bbae44d fix(app): align Android VPN runtime integration (#17)
Remove obsolete UI-process runtime plumbing and reuse the native service-owned notification and generation-scoped control path.
2026-09-06 11:23:55 +03:00
Naveax 5f851f3485 build: vendor pinned flutter_vless Android runtime (#10)
Replace build-time pub-cache mutation with a repository-owned pinned runtime so reviewed native source is the source compiled into the app.
2026-09-06 11:23:48 +03:00
esefxdzandClaude Opus 5 e818d54b0e build(config): delete orphaned assets instead of narrowing the manifest
#16 replaced the `assets/` wildcard with three explicit paths. That is correct
today but makes the failure mode for a forgotten registration an `Unable to load
asset` exception at runtime rather than at build time, which neither
`flutter analyze` nor the build would catch.

Restore the wildcard and delete the three files it was working around instead.
All are unreferenced in tracked source: `logo.png` has no callers and no
`flutter_launcher_icons` config, while `notification_icon.png` and
`notification_banner.png` are stale copies of the real Android drawables in
`android/app/src/main/res/`, which the notification reaches via
`R.drawable.notification_status_icon` and never through the Flutter bundle.

Same APK-size win, no hand-maintained list, and the dead files leave the repo.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_019HT2x2JvJNg7XNsJubfHFf
2026-09-06 11:20:08 +03:00
Naveax 74e522e982 build(config): remove unused Flutter dependencies (#16)
Remove dependencies and asset declarations that are no longer referenced so the resolved package graph stays smaller and easier to verify.
2026-09-06 11:18:43 +03:00
Naveax d2283c07cc fix(app): enforce authenticated ephemeral local SOCKS5 (#9)
Require the active per-session loopback SOCKS credentials and remove unauthenticated fallback behavior from the client diagnostic path.
2026-09-06 11:18:35 +03:00
Naveax ecdf6e549f refactor(app): remove unsupported server selector state (#6)
Remove UI and provider state that does not control the authoritative tunnel destination while preserving the existing connection-health status behavior.
2026-09-06 11:18:28 +03:00
Naveax 6da601b565 fix(app): persist disclosure acknowledgement after acceptance (#5)
Write the disclosure preference only after explicit confirmation so failed persistence does not create a false accepted state.
2026-09-06 11:18:24 +03:00
Naveax 14403e1d76 fix(app): make ConnectButton listener lifecycle-safe (#4)
Keep the exact VpnConnection instance used for listener registration so lifecycle cleanup does not depend on a deactivated BuildContext.
2026-09-06 11:17:19 +03:00
Naveax 915f8260d5 build: add reproducible Android release verification
Pin Gradle inputs and dependency metadata, then enforce analyze, lint, build, R8, immutability, and focused regression gates in CI.
2026-09-04 02:01:21 +03:00
esefxdz 9ac236a981 feat(app): OS session-expiry enforcement, session persistence, support sync
Enforce session expiry at the OS level (AlarmManager + handler) so the tunnel dies even if the UI process is killed; persist the session so a START_STICKY restart re-establishes it; sync immediately after a support top-up; slow the session beacon 5s/30s -> 60s/60s; drop the Always-on-VPN deep-link and the legacy 'ass' migration. Docs: CHANGELOG 3.3.4, privacy-policy log disclosure, README.
2026-09-02 20:33:33 +03:00
esefxdzandClaude Opus 5 dfeb7f161c fix(app): resume the session clock when attaching to a live tunnel
The clock sat at 00:00:00 on a connected tunnel, and the notification
countdown froze with it.

SessionTimer is built lazily, so when the app reattaches to a tunnel that
outlived its UI process, VpnConnection had already reported CONNECTED
before the timer existed. A change listener does not replay events it was
not present for, so the timer never learned it should be running. The
notification text is pushed by that same timer, which is why the countdown
froze at the same moment -- one cause, both symptoms.

The timer now evaluates the current connection state once at construction
rather than waiting for a transition, and is created eagerly alongside
VpnConnection so it is listening from the start.

Resuming also no longer requires adoptedRunningRuntime or a previous
successful sync. Both are false in a freshly started process, which is
exactly the case that needed to work. A connected tunnel with a stopped
clock is now always resumed.

Version 3.3.3+29.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-01 00:39:22 +03:00
esefxdzandClaude Opus 5 186dc906da feat(app): keep the tunnel alive via the OS, drop the workarounds
3.3.1 could display "connected" against a tunnel that was no longer
running, with a frozen countdown and no traffic. Three causes, and the
fix for each removes more code than it adds.

Liveness was read from getConnectedServerDelay(), which measures through
AppConfigs.V2RAY_CONFIG?.LOCAL_SOCKS5_PORT ?: 10807. AppConfigs lives in
the :RunSoLibXrayDaemon process, so from the UI process it is always null
and the port always fell back to 10807 -- accidentally correct while the
SOCKS port was fixed, permanently wrong once 3.3.1 made it ephemeral.
Liveness now comes from the OS: is our service process running, and is a
VPN transport actually present.

The foreground notification (id 1) is owned by XrayVPNService via
startForeground, but MainActivity was posting to the same id from the UI
process. When that process died its notification stayed on screen with
nothing left to update it. MainActivity now refuses to post for a dead
runtime and clears the stale notification instead.

Nothing ever asked Android for permission to stay alive. Adds the
battery-optimisation exemption prompt and a deep link to Always-on VPN --
the two sanctioned mechanisms for background survival, each needing one
user tap.

Removes Standard/Extreme resilience and the runtime-restart machinery:
recovery ran off a disconnect broadcast delivered to the app process, so
it could never fire when Android killed that process. Removes startup
restoration and the config-snapshot rebuild along with it; with the OS
keeping the tunnel up there is nothing to restore.

Version 3.3.2+28.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-01 00:16:05 +03:00
esefxdzandClaude Opus 5 ac52681452 docs(changelog): rewrite 3.3.1 against the shipped tree
The notes described PR #2 as opened, not what is being merged. Removed the
entries for per-app routing, the installed-apps bridge and the app picker
-- all dropped in the debloat -- and moved the rationale to a Removed
section. Replaced the overstated validation claims with measured ones, and
documented the startup-restoration fixes.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-31 23:31:51 +03:00
esefxdzandClaude Opus 5 ebaa2fc516 chore(test): remove the regression test suite
Removed at the maintainer's request. The four tests covered the auto->tun
and ass->proxy preference migrations, secure SOCKS session generation, and
the patched Xray SOCKS authentication schema.

Note that nothing now guards the build-time patchers against schema drift;
their fail-closed anchors are the only remaining check.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-31 23:31:51 +03:00
esefxdzandClaude Opus 5 6fcde9dd7b refactor(app): debloat 3.3.1 and fix startup restoration
Maintainer changes on top of PR #2 (Naveax). Reduces the release to two
deliberate connection modes and resolves the issues found in review:

- Lock-screen privacy: move VISIBILITY_PRIVATE and a generic publicVersion
  into MainActivity.updateVpnNotification. The PR's fix lived in an
  unreferenced class and never reached the live notification.
- Haptics: restore the default to off, and reduce HapticSettings to a
  single success() on connect/disconnect via the native channel.
- SOCKS5: make it a real proxyOnly local-proxy mode rather than a TUN
  connection under a different label. TUN stays the default.
- Health probe: restore the idle-only guard so /health is no longer polled
  every 30s while connected.
- Recovery: add a _connectionEpoch counter so connect() aborts an
  in-flight Extreme recovery.
- Startup restoration: rebuild the recovery snapshot from the still-active
  session after an app-process restart (TUN), and surface an honest
  orphaned state with a Reconnect action in proxy mode.

Drops per-app routing entirely. It only ever functioned in TUN --
addDisallowedApplication lives inside the VPN-interface setup that
proxyOnly skips -- and its allowlist half had no Dart caller.

Also removes flutter_local_notifications, the global tap-haptic surface,
and unused runtime telemetry.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-08-31 23:31:51 +03:00
esef a71161e7e5 Merge pull request #2 from Naveax/release/3.3.1
feat(app): release 3.3.1 with secure routing and runtime resilience
2026-08-31 23:30:43 +03:00
Naveax da82a833cb docs: document 3.3.1 release changes
Document the client routing, secure SOCKS5, runtime resilience, lifecycle, notification and migration changes so reviewers can compare the 3.3.1 release against 3.3.0 without reconstructing the behavior from implementation commits.
2026-08-31 20:31:35 +03:00
Naveax 0ab008b80b fix(app): hide session metadata from public lock screen
Keep the ongoing VPN notification visible while marking its timer and speed content private so Android does not expose session metadata in public lock-screen previews.
2026-08-31 20:24:04 +03:00
Naveax f7f425517c build(config): increase gradle heap for release builds
Raise the Gradle heap to 4 GB and cap workers at two so Jetifier and Kotlin release compilation do not exhaust memory while processing Flutter engine artifacts.
2026-08-31 20:22:05 +03:00
Naveax 76bf84453f build(config): bump app version to 3.3.1
Set the release version to 3.3.1+27 for the upstream 3.3.0 follow-up release.
2026-08-31 19:47:23 +03:00
Naveax 6c99366602 test(app): cover routing and secure socks migrations
Cover legacy Auto and ASS preference migration, authenticated SOCKS session generation and the stock-runtime Xray SOCKS schema so future runtime changes cannot silently restore the old fixed-port/no-auth behavior.
2026-08-31 19:47:05 +03:00
Naveax 8ead3ff249 feat(app): add secure routing and runtime resilience
Add explicit TUN and SOCKS5 connection modes, app routing controls, authenticated per-session local SOCKS5, Android network monitoring, persistent haptics, resilient session recovery, notification hardening and client-side Hivemind cleanup.

Keep the hosted flutter_vless_android 1.1.5 runtime as the base and apply the Android compatibility/security patches at build time instead of restoring the unstable vendored runtime.
2026-08-31 19:31:12 +03:00
esefxdz 371db8da9f docs: make app_config.example github owner/repo placeholders unambiguous 2026-08-30 15:43:39 +03:00
esefxdz 8a89af3c62 docs: mark 3.3.0 as released in CHANGELOG 2026-08-30 15:30:14 +03:00
esefxdzandNaveax 62104d5730 chore: release 3.3.0 (sidebar nav fix, notification countdown, hardening)
Co-authored-by: Naveax <[email protected]>
2026-08-30 14:01:52 +03:00
esefxdz 4eb1fca666 Merge branch 'main' of https://github.com/esefxdz/ReVoltVPN 2026-08-22 11:34:39 +03:00
esefxdz 71468f7594 frontend polish and security review changes 2026-08-22 11:34:17 +03:00
esef 6adf03f920 Update README.md 2026-08-11 17:46:32 +03:00
esefxdz 5642b0b811 Merge branch 'main' of https://github.com/esefxdz/ReVoltVPN 2026-08-08 14:32:40 +03:00
esefxdz 096fbf5a97 docs: update privacy policy for V3 model and in-app disclosure 2026-08-08 14:31:54 +03:00
esef 6c137245fd Revise obfuscation details in README
Updated obfuscation description to generalize the TLS spoofing. because we no longer use github
2026-08-08 14:30:09 +03:00
esefxdz cc819abc41 chore: bump to 3.2.2+25 (discord link fix, apk release) 2026-08-08 14:23:13 +03:00
esefxdz d696bda63f discord link fixed 2026-08-08 14:21:53 +03:00
esefxdz 61c72b2200 feat: first-launch data disclosure dialog (v3.2.1+24) 2026-08-08 13:49:00 +03:00
esefxdz 54f949ca8e v3.2.0 — DPI hardening, notification consolidation, disconnect refactor
User-Agent spoofed to Chrome on Android (was Dart/3.x). Domain renamed to userevolt.app. Branding to Revolt VPN. Removed duplicate notification, patched flutter_vless for custom icon + dark background. Merged 5 disconnect paths into single idempotent gate, fixed stopVless timeout silently lying about state. Removed kDebugMode guard from AdMob bypass.
2026-08-08 13:06:19 +03:00
esefxdz cf50c3a01b chore: bump version to 3.1.0+22 2026-08-06 23:09:56 +03:00
esefxdz 04ec8ac5d1 feat: settings screen, haptic toggle, rain/lightning toggles, review docs 2026-08-06 23:08:26 +03:00
esefxdz 56ea53e73b fix: RenderFlex overflow, circular import, remove timer spinner 2026-08-06 22:09:14 +03:00
esefxdz 143f5f4eff Merge branch 'main' of https://github.com/esefxdz/ReVoltVPN 2026-08-06 21:48:18 +03:00
esefxdz abcb41fb06 splash screen and status bar color polish 2026-08-06 21:47:58 +03:00
esef e2359419bc Delete SERVER_DEPLOYMENT.md 2026-08-02 20:20:31 +03:00
esefxdz 2d0628c5bb docs: update SERVER_DEPLOYMENT.md for V2 domain-free architecture 2026-08-02 15:38:42 +03:00
esefxdz 4fde4a9217 v3.0.0: domain-free client, bootstrap tunnel, tunnel-internal API 2026-08-02 14:00:38 +03:00
esefxdz 75cf59f22c cleaning up 2026-08-02 00:56:55 +03:00
esefxdz c1ec77a075 http conversion through guides 2026-08-01 23:55:54 +03:00
esefxdz 1b8a67cecb less client things removal 2026-08-01 22:10:48 +03:00
esefxdz c5148e138d Merge branch 'main' of https://github.com/esefxdz/ReVoltVPN 2026-08-01 20:58:54 +03:00
esefxdz 832c2d0a2d privacy policy changed and gitignore updated 2026-08-01 20:58:36 +03:00
esef 7f40a82997 Update app_config.example.dart 2026-08-01 01:01:46 +03:00
esefxdz fd6b358929 clean up .gitignore: organize sections, add backups/ docs/ patterns, remove tracked server+backup files from repo 2026-07-31 22:53:50 +03:00
esefxdz 4555911ee8 fix compilation: revert AppConfig.enableAdBypass to kDebugMode, fix const Padding with dynamic version 2026-07-31 22:47:51 +03:00
esefxdz 54609a3119 audit #13: notification fix, sync guard, bypass gate, responsive layout, dynamic version, dart format, clock_display to backups, stats race fix, new locks, nginx swarm block 2026-07-31 22:41:29 +03:00
esefxdz e1c5d5b106 rain and lightning effects addded. 2026-07-30 23:54:02 +03:00
esefxdz adf6de5dc0 refactor(server): split hivemind monolith into modular package
- server_hivemind_5_0.py: 744-line monolith → 19-line entry point shim
- hivemind/ package (8 files, gitignored): config, sessions, xray,
  admob, management, api, main, README
- Encapsulated locks in classes (SessionStore, XrayManager,
  AdMobVerifier) — fixes 3 critical race conditions
- Added localhost-gated /api/swarm and /api/log with log ring buffer
- swarm_watch.py: Rich TUI monitor for local server dashboards
- Backed up original monolith to backups/hivemind_backup_2.py
2026-07-30 17:40:07 +03:00
esefxdz 81d0387612 update readme 2026-07-29 23:50:48 +03:00
esefxdz 33522dfeaf changelog: bump to v2.0.7 2026-07-29 23:46:04 +03:00
esefxdz f8abda9323 v2.0.7: security hardening, config sync, cleanup
- 6 new security audits (technical_debt_8 through 12)
- SNI rotation pool per session (5 sites)
- vless_ip pinned to hardcoded server IP
- TLS cert validation restored (domain-based)
- Swarm monitoring removed from public domain
- Xray routing blocks abuse ports (SMTP, NetBIOS, SSDP)
- flow: xtls-rprx-vision in add_vless_client
- TimerBox shows Connecting/Syncing spinner
- Outbound port blocking in Xray config
- Cleaned up comments, synced config templates
2026-07-29 23:43:47 +03:00
esefxdz f01a610182 v1.0.7: updater, website button, timer sync indicator, server flow fix
- App: manual update checker (GitHub API, Play Store redirect)
- App: website button in sidebar
- App: timer_box shows Connecting/Syncing spinner during handshake
- App: synced app_config.example.dart with app_config.dart
- Sidebar: 6 rows (added Website, Check for updates)
- Server: add_vless_client now includes flow xtls-rprx-vision
- Deps: added package_info_plus
- Version bump: 1.0.6+10 → 1.0.7+11
- CHANGELOG.md created
2026-07-29 20:37:33 +03:00
esefxdz d6c56e8345 paladinvpn replacement added 2026-07-28 21:58:02 +03:00
esefxdz 96584082cf changed licensing 2026-07-28 21:37:59 +03:00
esefxdz 66e89d8d28 contributing guide added 2026-07-28 21:35:44 +03:00
104 changed files with 18678 additions and 1782 deletions

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
* text=auto eol=lf
*.bat text eol=crlf
*.ps1 text eol=crlf
*.png binary
*.jpg binary
*.jpeg binary
*.webp binary
*.jks binary
*.keystore binary
*.jar binary
+135
View File
@@ -0,0 +1,135 @@
name: Android CI
on:
push:
branches:
- main
pull_request:
branches:
- main
permissions:
contents: read
jobs:
android:
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- name: Checkout
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- name: Set up Java 17
uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5
with:
distribution: temurin
java-version: '17'
- name: Verify Gradle supply chain
shell: bash
run: |
set -euo pipefail
test -x android/gradlew
test -f android/gradlew.bat
test -f android/gradle/wrapper/gradle-wrapper.jar
test -s android/gradle/verification-metadata.xml
test "$(sha256sum android/gradle/wrapper/gradle-wrapper.jar | awk '{print $1}')" = '7d3a4ac4de1c32b59bc6a4eb8ecb8e612ccd0cf1ae1e99f66902da64df296172'
grep -qx 'distributionSha256Sum=efe9a3d147d948d7528a9887fa35abcf24ca1a43ad06439996490f77569b02d1' android/gradle/wrapper/gradle-wrapper.properties
grep -q '<verify-metadata>true</verify-metadata>' android/gradle/verification-metadata.xml
./android/gradlew --version
- name: Set up Flutter
uses: subosito/flutter-action@1a449444c387b1966244ae4d4f8c696479add0b2 # v2
with:
flutter-version: '3.47.2'
channel: stable
cache: false
- name: Create CI app config
run: cp lib/logic/app_config.example.dart lib/logic/app_config.dart
- name: Resolve dependencies
run: flutter pub get
- name: Verify dependency lock is committed
run: git diff --exit-code -- pubspec.lock
- name: Verify vendored runtime provenance
if: ${{ hashFiles('local_packages/flutter_vless_android-1.1.5/UPSTREAM') != '' }}
shell: bash
run: |
set -euo pipefail
PKG='local_packages/flutter_vless_android-1.1.5'
test -f "$PKG/UPSTREAM"
grep -q 'Tag: v1.1.5' "$PKG/UPSTREAM"
grep -q 'path: local_packages/flutter_vless_android-1.1.5' pubspec.yaml
! grep -q 'patchFlutterVless' android/app/build.gradle.kts
- name: Analyze
run: flutter analyze
- name: Test
run: flutter test
- name: Android lint
working-directory: android
run: ./gradlew :app:lintDebug --no-daemon
- name: Verify production release config fails closed
shell: bash
working-directory: android
run: |
set -euo pipefail
set +e
output="$(./gradlew :app:verifyReleaseAppConfig --no-daemon 2>&1)"
status=$?
set -e
printf '%s\n' "$output"
test "$status" -ne 0
grep -Fq 'REVOLT_APP_CONFIG_SHA256 is required for production release builds' <<<"$output"
- name: Cold APK build
run: flutter build apk --debug
- name: Verify vendored native source stayed immutable
run: git diff --exit-code -- local_packages/flutter_vless_android-1.1.5
- name: Warm APK build
run: flutter build apk --debug
- name: Release R8 smoke build
env:
REVOLT_CI_RELEASE_SMOKE: 'true'
run: |
flutter build apk --release
test -f build/app/outputs/flutter-apk/app-release.apk
test -f build/app/outputs/mapping/release/mapping.txt
- name: Verify tracked build inputs stayed immutable
run: |
git diff --exit-code -- \
pubspec.yaml \
pubspec.lock \
local_packages/flutter_vless_android-1.1.5 \
android/app/build.gradle.kts \
android/app/proguard-rules.pro \
android/gradle/verification-metadata.xml \
android/gradle/wrapper/gradle-wrapper.properties \
android/gradle/wrapper/gradle-wrapper.jar \
android/gradlew \
android/gradlew.bat
- name: Upload APK
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: revoltvpn-debug-apk
if-no-files-found: error
path: build/app/outputs/flutter-apk/app-debug.apk
- name: Upload resolved lockfile
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: revoltvpn-resolved-lockfile
if-no-files-found: error
path: pubspec.lock
+72 -65
View File
@@ -1,38 +1,60 @@
# Miscellaneous # =============================================================================
*.class # ReVoltVPN — .gitignore
*.log #
*.pyc # Type-based by design. This repo ships Dart, Kotlin, XML and image assets;
*.swp # everything else is excluded by extension or directory rather than by being
.DS_Store # listed individually. A new file is therefore ignored by default instead of
.atom/ # needing to be named here, and this file does not enumerate what it protects.
.buildlog/
.history
.svn/
.java-version
# IntelliJ related # =============================================================================
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains configure files for the Visual Studio Code # ── Secrets ────────────────────────────────────────────────────────────────
# editor. Although we may keep it, we often ignore it. *.keystore
.vscode/ *.jks
android/key.properties
android/admob.properties
# Python cache & User files # Real IPs and IDs. app_config.example.dart is the committed template.
TECHNICAL_DEBT.md
RUNNING.md
__pycache__/
*.pyc
# App Config (Hide real IPs/IDs from GitHub)
lib/logic/app_config.dart lib/logic/app_config.dart
# Flutter/Dart/Pub related # ── File types the shipped app does not contain ────────────────────────────
**/doc/api/ *.py
**/ios/Flutter/.last_build_id *.pyc
*.json
*.conf
*.sh
*.txt
*.html
*.zip
*.log
*.class
# ── Documentation ──────────────────────────────────────────────────────────
# The published set is allow-listed; anything else, at any depth, is not.
# Leading slashes anchor these to the repo root so a same-named file in a
# subdirectory is NOT re-included by the negation.
*.md
!/README.md
!/CHANGELOG.md
!/CONTRIBUTING.md
!/PRIVACY_POLICY.md
# ── Working directories ────────────────────────────────────────────────────
# Material that is not part of the app. These need directory rules rather
# than type rules, because they can hold source-file types the rules above
# deliberately do not cover.
.local/
internal/
hivemind/
scraped/
backup/
backups/
lib/logic/backup/
server_files/
# ── Flutter / Dart build output ────────────────────────────────────────────
.dart_tool/ .dart_tool/
*.dart_tool/
.flutter-plugins .flutter-plugins
.flutter-plugins-dependencies .flutter-plugins-dependencies
.pub-cache/ .pub-cache/
@@ -41,50 +63,35 @@ build/
**/build/ **/build/
local_packages/*/build/ local_packages/*/build/
local_packages/*/.dart_tool/ local_packages/*/.dart_tool/
*.dart_tool/ **/doc/api/
**/ios/Flutter/.last_build_id
# Android related # ── Android build output ───────────────────────────────────────────────────
**/android/**/gradle-wrapper.jar
**/android/.gradle **/android/.gradle
**/android/.cxx/
**/android/app/build/
**/android/captures/ **/android/captures/
**/android/gradlew **/android/gradlew
**/android/gradlew.bat **/android/gradlew.bat
**/android/local.properties **/android/local.properties
**/android/**/gradle-wrapper.jar
**/android/**/GeneratedPluginRegistrant.java **/android/**/GeneratedPluginRegistrant.java
**/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java **/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
**/android/.cxx/
**/android/app/build/
# Keystore files
*.keystore
*.jks
# Crashlytics cache
**/android/app/crashlytics-build.properties **/android/app/crashlytics-build.properties
# Shell scripts (dev only, not for public) # ── Editors, tooling & OS ──────────────────────────────────────────────────
server_picture.sh .claude/
XRAY_CONFIG_REFERENCE.md .codewhale/
.idea/
.vscode/
.atom/
.history
.svn/
.java-version
.DS_Store
*.swp
__pycache__/
devtools_options.yaml
# Secrets #why are you even looking at this file? it's a secret. go away.
android/key.properties whatsthis
android/admob.properties
SECURITY_HARDENING.md
VLESS_APP_CONTRACT.md
AGENTS.md
SERVER_NOTES.md
lib/logic/backup/
00-FULL-REPORT.md
server full picture.txt
technical_debt_*.md
server_full_picture_2.txt
hivemind_backup.py
UI_POSITIONING.md
SERVER_SETUP.md
REALITY_MIGRATION_PLAN.md
xray_config_reality.json
SERVER_DEPLOYMENT.md
swarm_watch.py
nginx_hivemind_reality.conf
nginx_hivemind_reality.conf
nginx_hivemind_reality.conf
+561
View File
@@ -0,0 +1,561 @@
# Changelog
All notable changes to the ReVoltVPN Flutter app.
Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH
---
## [Unreleased]
### Removed
- **The background server check while disconnected.** The app no longer contacts
the server every 30 seconds while you are not connected to it. Nothing about
the connected session changes.
### Changed
- **The status bar no longer guesses whether the server is up.** It reads
"Ready" while disconnected and shows "Online" once a session has synced, so a
green dot now means a session that is actually working rather than a
reachability check made beforehand.
## [3.3.8] — 2026-10-17
### Changed
- **Reconnecting always starts a fresh session.** In SOCKS5 mode, the
**Reconnect** button used to re-attach to the session you already had. It now
ends that session and starts a new one, exactly as the connect button does —
one way to begin a session instead of two, and you get a full window back
rather than the remainder of a broken one.
### Fixed
- **SOCKS5 "Reconnect" works again.** In 3.3.7 it ended your session and then
asked for the session it had just ended, failing with "Session not activated".
---
## [3.3.7] — 2026-10-17
> **Known issue — fixed in 3.3.8.** In SOCKS5 mode, the **Reconnect**
> button in Settings ends your session instead of re-attaching to it, and then
> fails with "Session not activated". It only appears when a proxy session has
> been orphaned, and you lose the rest of that session rather than anything
> worse. Workaround: connect again from the main screen. The "SOCKS5 Reconnect"
> entry below describes the intended behaviour, which this build does not have.
### Added
- **A warning before a session ends.** The VPN service schedules it off the same
deadline it already enforces, so it arrives even with the app closed, and a
support top-up moves it with the deadline. It does not promise an exact number
of minutes: on a deeply sleeping phone Android can hold it back past the end
of the session, in which case it is skipped rather than shown late.
- **A "disconnected — not protected" notification** when a session ends without
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.
- **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, which keeps running regardless.
### Fixed
- **The countdown no longer over-reports after the phone sleeps**, and a clock
moved backwards can no longer stretch a session.
- **A session that expired while the phone was asleep is recognised on waking**,
by wall clock rather than by time the device spent awake.
- **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 recovers 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. It now usually comes back on the
first retry, without dropping the connection.
- **Disconnecting with the app's own button now releases your session on the
server** instead of leaving it open until it expires.
- **SOCKS5 "Reconnect" re-attaches to the current session** instead of
requesting a new one — see the known issue above; this does not work in 3.3.7.
- **A core that fails to start now logs why.** Its output was being discarded,
so the only trace was an exit code.
### Groundwork
- **Rewarded-ad plumbing.** Ads are switched off in this build, so none of this
is reachable yet: the ad's verification nonce is now carried through to the
connect call rather than being minted twice, and the client waits longer
(~36 s) for Google's callback. Reviewed, not yet exercised end to end.
## [3.3.6] — 2026-10-08
### Fixed
- **VPN service notification icon.** The ongoing notification now uses the
bundled `notification_icon` drawable instead of `notification_status_icon`,
and the vendored runtime resolves that drawable by name at runtime (falling
back to the platform icon only if it is missing), so the foreground-service
notification no longer shows the generic Android info icon.
- **"Test Local SOCKS" no longer claims an outbound it never tested.** Xray
answers a SOCKS `CONNECT` before it dials upstream, so trusting the `0x00`
reply reported success for unroutable addresses and for hostnames that can
never resolve — meaning the test said OK while the server was down, which is
exactly when it gets run. It now forces a request/response round trip through
the tunnel and reports distinctly when the outbound never replies, drops the
connection, or returns unexpected data.
---
## [3.3.5] — 2026-09-06
### Added
- **Reproducible release verification.** The release build pins the production
`app_config.dart` by SHA-256 and fails closed on any mismatch, so a release
APK cannot silently ship a template or wrong server config.
### Changed
- **Vendored Android runtime.** The pinned `flutter_vless` Android runtime is now
vendored in-tree instead of being patched in the pub cache at build time.
- **Harden the control-plane trust boundary.** `/session/status` fields are
strictly validated (nonce, destination IP, port, SNI, XHTTP path), control
responses are capped and never follow redirects, and the tunnel destination
is pinned to the compiled server — a compromised API can no longer redirect
user traffic.
- **Authenticated local SOCKS5 is now mandatory.** The ephemeral local proxy
replaces rather than filters inbounds, so only the authenticated SOCKS5
listener can exist.
- **Fail closed on connection-mode changes.** The mode is persisted before it is
applied, and a failed save leaves the UI and runtime unchanged instead of
silently selecting a weaker route.
### Fixed
- Connect button no longer leaks a listener into a disposed `AnimationController`
during teardown.
- Disclosure acknowledgement is only persisted once the user accepts it.
- Session countdown now uses a monotonic clock (cannot be extended by rolling the
device clock back) and a VPN error tears the tunnel down instead of freezing
the timer on a live session.
- The VPN-service notification's disconnect action and countdown re-post are
aligned with the vendored runtime.
### Removed
- Unsupported server-selector UI (single server today; design retained for
multi-server later).
- Unused Flutter dependencies and orphaned assets.
- Dead Dart wrappers whose native handlers no longer exist.
### Security & privacy
- IPv6 is captured by the VPN interface (`::/0` route), closing a leak where
IPv6 traffic could bypass the tunnel on IPv6-capable carriers.
---
## [3.3.4] — 2026-09-02
### Added
- **OS-level session-expiry enforcement.** The VPN service now holds an absolute
deadline and tears the tunnel down on its own clock — a main-looper handler
plus an `AlarmManager` exact alarm (falling back to an inexact alarm on
Android 13+ when exact alarms aren't granted). The app pushes
`now + expires_in_seconds` on each session sync, so a session ends even if the
UI process has been killed.
- **Session survival across process death.** The service persists the active
session and re-establishes it when Android restarts it (`START_STICKY`).
- **Support-ad extension reflected immediately.** A rewarded "Support us" ad now
forces an immediate server sync, so the countdown and expiry deadline update
without waiting for the next heartbeat.
### Changed
- **Session-status beacon slowed.** Foreground poll: 5 s → 60 s; background poll:
30 s → 60 s.
- **Background-reliability guidance.** The "Always-on VPN" settings deep-link was
removed; the battery-optimisation exemption remains, with expiry now enforced
by the service itself.
### Removed
- Legacy `ass` connection-mode migration — unrecognized persisted modes now
default to TUN.
### Security & privacy
- Session credentials and the per-user VLESS UUID are now held app-private on
disk (`active_session.bin`) for the session's lifetime and removed on
disconnect or expiry. Previously they were memory-only.
---
## [3.3.3] — 2026-09-01
### Fixed
- **The session clock stayed at 00:00:00 on a live tunnel, and the notification
countdown froze with it.** `SessionTimer` is built lazily, so when the app reattaches
to a tunnel that outlived its UI process, `VpnConnection` had already reported
"connected" before the timer existed — and a change listener does not replay events
it was not present for. The timer now evaluates the current connection state once at
construction instead of waiting for a transition, and is created eagerly alongside
`VpnConnection`. Because the timer is what pushes text to the foreground
notification, a stopped clock also meant a frozen countdown; both come from this.
- Resuming the clock no longer requires `adoptedRunningRuntime` or a previous
successful sync, both of which are false in a freshly started process. A connected
tunnel with a stopped clock is now always treated as something to resume.
## [3.3.2] — 2026-09-01
Background reliability. 3.3.1 could show "connected" against a tunnel that was no
longer running; this release fixes the cause rather than the symptom, and removes the
machinery that existed to work around it.
### Added
- **Background reliability settings.** Android stops background services of apps that
are not exempt from Doze, and tears down the process group when a task is swiped
away. Two OS mechanisms prevent that, and the app now surfaces both: a one-tap
**battery optimisation exemption**, and a deep link to Android's **Always-on VPN**
settings (with a note about "Block connections without VPN"). Neither can be enabled
programmatically — each needs a single user tap, once.
### Fixed
- **The app could report "connected" with no traffic flowing.** Startup state came from
`getConnectedServerDelay()`, which measures through
`AppConfigs.V2RAY_CONFIG?.LOCAL_SOCKS5_PORT ?: 10807`. `AppConfigs` lives in the VPN's
own process, so from the UI process it is always null and the port always fell back to
10807. That was accidentally correct while the SOCKS port was fixed; 3.3.1's
per-session ephemeral ports made it permanently wrong. Liveness is now determined from
the OS — whether our VPN service process is running, and whether a VPN transport is
actually present.
- **A frozen countdown could outlive the tunnel.** The foreground notification (id 1) is
owned by the VPN service via `startForeground`, but the UI process was posting to the
same id. When that process died, its notification stayed on screen with nothing left to
update it. The app no longer posts for a runtime that is not alive, and clears a stale
notification instead.
### Removed
- **Standard/Extreme resilience modes** and the runtime-restart machinery behind them.
Recovery ran off a disconnect broadcast delivered to the app process, so it could never
fire in the case that actually matters — Android killing that process. It was
complexity substituting for background persistence.
- **Startup restoration**, including the config-snapshot rebuild. With the tunnel kept
alive by the OS, there is nothing to restore; the app simply reports what is running.
- The `resilience_mode` preference and its settings tile.
## [3.3.1] — 2026-08-31
### Added
- **Explicit TUN and SOCKS5 connection modes.** The previous Auto mode is gone, so
routing is chosen deliberately instead of inferred at runtime. TUN is the default.
SOCKS5 runs a local authenticated proxy with no VPN interface, and therefore never
requests the Android VPN permission.
- **Authenticated per-session Local SOCKS5.** Every connection binds an ephemeral
loopback port and mints fresh 16-byte username / 32-byte password credentials.
Android loopback is reachable by every app on the device, so this authentication is
load-bearing rather than decorative. Credentials stay in memory. Imported
`socks`/`http` inbounds are dropped so no unauthenticated listener can survive
alongside the session one.
- **Network resilience profiles** — Standard and Extreme. Extreme restarts a failed
Xray/tun2socks runtime up to twice before giving up.
- **Android physical-network monitoring**, filtered on `NET_CAPABILITY_NOT_VPN` so the
VPN's own network cannot feed back a reconnect loop. Informational only; the active
transport (Wi-Fi / cellular / ethernet) now appears in the status bar.
- **Local SOCKS5 diagnostics.** "Test Local SOCKS" authenticates against the exact
active session over loopback — a readiness handshake plus a full CONNECT — instead
of checking whether a fixed port accepts connections.
- Native Android bridges for network state, haptic feedback and install-source
detection.
### Fixed
- **Extreme recovery now survives an app-process restart.** Android can kill the Dart
process while the VPN foreground service keeps running, leaving the app attached to
a live tunnel it holds no configuration for — so recovery had nothing to restart
from. In TUN mode the app rebuilds that snapshot from the still-active session,
without opening a new session, showing an ad, or interrupting traffic.
- **The proxy settings tile no longer misreports state after a process restart.** Its
credentials genuinely cannot be recovered — they are random, generated on device and
never transmitted — so instead of telling an already-connected user to "Connect", it
now says the credentials were lost and offers a Reconnect action.
- **The first tap on the connect button was ignored.** The debounce timestamp was
initialized to the current time instead of the epoch, so the first press was always
swallowed.
- **The health probe polled `/health` every 30 s even while connected.** Restored to
idle-only — a live tunnel already proves reachability, and the extra direct requests
were unwanted.
- **A user reconnect could race an in-flight Extreme recovery.** A connection
generation counter now aborts stale recovery attempts.
- Recoverable Xray/tun2socks startup and readiness failures no longer follow the
unstable self-stop path used during development.
- Returning from Android background state reconciles the session countdown against
elapsed wall-clock time and re-syncs immediately, reducing stale countdowns and false
`Syncing…` presentation after Dart throttling.
- Sidebar update checks retain valid navigator/messenger handles after the drawer
closes.
### Changed
- **The pinned `flutter_vless_android` 1.1.5 runtime is patched at build time** instead
of vendored. Three idempotent patchers are chained into `preBuild`, so a plain
`flutter build apk` behaves like CI rather than depending on a manual step against
the pub cache. They are fail-closed: an upstream change breaks the build loudly
instead of silently producing an unpatched runtime.
- Legacy `auto` preferences migrate to TUN; legacy `ass` preferences migrate to SOCKS5.
- Haptic feedback is a single confirmation on connect/disconnect, routed through the
native Android vibration channel, and **defaults to off**.
- The VPN notification uses a dedicated 24 dp status icon and stays ongoing/no-clear
while the foreground service is alive.
- Hivemind session parsing is split into typed validation steps; a malformed port now
fails instead of silently falling back.
- The update checker parses semver with prerelease ordering and validates release URLs
against an HTTPS host allowlist.
- The support button shows a claimed/disabled state once the session bonus is used.
- The status bar distinguishes `Ready` from `Syncing…` and folds in server
reachability.
- Gradle release heap raised to 4 GiB with `MaxMetaspaceSize=1g` and `workers.max=2`,
so Flutter/Jetifier transforms do not fail on the release classpath under constrained
runners.
- App version is now `3.3.1+27`.
### Removed
- **Per-app routing**, including the app picker, the installed-apps native bridge and
the blocked-apps mechanism. It only ever functioned in TUN — the underlying
`addDisallowedApplication` call lives inside the VPN-interface setup that SOCKS5 mode
skips entirely — and its allowlist half was never wired to any caller. Removed rather
than finished.
- The legacy `auto` connection mode.
- `flutter_local_notifications`, and the unused notification manager it backed.
- A global touch listener that fired a haptic on every tap.
- Unused runtime telemetry fields.
### Security & privacy
- **Session metadata is hidden from public lock-screen previews.** The live foreground
notification is built with `VISIBILITY_PRIVATE` plus a generic public version, so the
countdown and speed are visible only after unlock. *(An earlier attempt at this
landed in an unreferenced class and never took effect.)*
- Local SOCKS5 listens only on `127.0.0.1`, requires per-session authentication, and
its credentials are neither persisted nor logged.
- The app requests no package visibility at all. `QUERY_ALL_PACKAGES` was never used,
and the launcher-enumeration query was removed along with the app picker.
- Session nonces use `Random.secure()` and are never logged.
- Device UUIDs are validated as v4 and regenerated if corrupt, so tampered identifiers
cannot reach the API.
- `FOREGROUND_SERVICE_SPECIAL_USE` is declared for Android 14+; the merged service
declaration carries the `vpn` special-use subtype.
- Existing AdMob bypass/callback behavior is intentionally unchanged by this release.
- Server, nginx and Reality configuration are not modified by this client-side release.
### Validation
- `flutter analyze` — 0 errors, 0 warnings, 7 style infos (6 of them pre-existing).
- All three build-time patchers verified against a clean pub cache, including that each
applies independently of the others.
- **Not yet verified:** Android release Kotlin compilation and APK build.
## [3.3.0] — 2026-08-30
### Added
- Session countdown in the VPN notification, updated each second while connected.
### Fixed
- **Session-expiry desync** — the app could show "Online" with no internet after
the server ended the session. The countdown no longer freezes when a poll fails.
- **Notification Disconnect button** disappeared a second after connecting.
Re-posting the foreground notification replaces it wholesale, so the action,
colour and tap-intent flutter_vless sets are now rebuilt rather than dropped.
- **Speed readout** divided the byte delta by the nominal poll interval instead of
the real time between polls — wrong by up to 6x around every background switch.
- **Settings toggles** now apply at launch. Rain, lightning and haptics were only
read from disk when Settings mounted, so an effect turned off came back — ticker
and all — on every relaunch, and haptic feedback did nothing until Settings had
been opened at least once.
- **Haptic feedback** now fires `mediumImpact()` instead of `lightImpact()` (which
is imperceptible on many Android devices), wrapped best-effort so a platform
vibration failure cannot fail a connect/disconnect, with a preview tap when the
toggle is switched on.
- First-launch disclosure dialog said data was linked to "your account". It is
linked to a randomly generated device ID, and the policy is in the sidebar, not
on a website.
- Sidebar "Settings" and "Check for updates" used the drawer's context after
`Navigator.pop()` — a defunct context. They now capture the root navigator (and
messenger) before closing the drawer. *(Fix ported from Naveax's review.)*
### Performance
- Rain overlay ticks only while enabled, repaints through a scoped `Listenable`
instead of rebuilding every frame, and precomputes drop colours.
- Lightning no longer fires strikes while disabled.
- Connect button pulse pauses when backgrounded; brand image hoisted out of the
per-frame rebuild.
- Server poll drops to 30 s while backgrounded (5 s foreground), with an immediate
re-sync on resume. The 1 s countdown keeps running.
- Health probe runs only while disconnected, and pauses in the background.
- Speed and support widgets rebuild on value change instead of every second.
- Notification channel is created once per process, not once per second.
### Changed
- VLESS engine initializes under the splash screen; the intro waits on
`VpnConnection.ready` (8 s cap) before showing the main screen.
- AdMob SDK init moved off the blocking pre-`runApp()` path so startup cannot hang
on an unreachable Google endpoint.
- `app_config.example.dart` drops the dead bootstrap fields and documents
`hivemindApiPublic` in their place.
- `.gitignore` reorganized around type and directory rules; the enumerated
filename list is gone (redundant with the type rules) and `.claude/` is now
ignored.
### Security
- Update checker pins the release URL to this repo's path on `github.com`, not just
the host. Anything else falls back to the releases page.
- Notification timer updates are gated on a live tunnel, so a late tick cannot leave
an ongoing notification with no foreground service behind it.
- Dropped `READ_EXTERNAL_STORAGE`, which `flutter_vless` pulls in but the app never uses
(least privilege).
- Pinned the Gradle 8.14 distribution SHA-256; `validateDistributionUrl` enabled
(supply-chain integrity).
### Build & tooling (ported from Naveax)
- Removed the deprecated `android.enableR8` flag.
- Added `analysis_options.yaml` (flutter_lints, `local_packages/**` excluded, `avoid_print`).
- Added `.gitattributes` to pin LF line endings repo-wide.
- Credit: reviewed and ported from **Naveax**.
### Docs
- Privacy policy: disclosed that the server sees the connecting IP, corrected the
"stored in memory" claim, and documented consent being changeable from the sidebar.
## [3.2.2] — 2026-08-08
### Fixed
- Updated Discord invite link.
## [3.2.1] — 2026-08-08
### Google Play compliance
- Added first-launch data disclosure dialog ("Before you connect") explaining
that connection duration and data usage are logged for quota enforcement, and
that traffic content is never monitored.
## [3.2.0] — 2026-08-08
### DPI hardening
- Spoof Chrome-on-Android User-Agent on all API calls instead of `Dart/3.x`.
- Renamed domain from `getrevolt.app` to `userevolt.app`.
### Branding
- App name changed from "REVOLT VPN" to "Revolt VPN" across manifest, splash,
notification, and VLESS URL remark.
### Notification
- Removed duplicate `flutter_local_notifications` notification. Only the
Android VPN foreground-service notification remains — non-swipeable.
- Patched `flutter_vless` native code to use custom notification icon
(`@drawable/notification_icon`) with dark background (`#0D1117`).
### Connection reliability
- Merged five separate disconnect paths into a single idempotent
`_doDisconnect()` gate. Eliminated race between timer ticks and VPN
teardown where the countdown could briefly show -1.
- `stopVless()` timeout (5 s) now correctly shows an error instead of
silently pretending the VPN disconnected while the tunnel was still alive.
### AdMob bypass
- `kDebugMode` guard removed — the debug AdMob callback now fires in release
builds so release APKs can create sessions without real ads during testing.
The real gate is `ADMOB_BYPASS` on the server.
### Fixed
- **Notification icon:** Replaced five density-specific `ic_launcher.png`
files with `notification_icon.png`, then reverted to avoid changing the
home-screen icon. The custom icon is now injected through flutter_vless's
`initializeVless()` parameters.
## [3.1.0] — 2026-08-06
### Architecture — domain-free client
- **Zero domain strings in APK.** RKN has nothing to DNS-block. API calls go
through the Reality tunnel to `10.254.254.1:5000`, redirected to Flask by
Xray's `api` freedom outbound (`redirect: 127.0.0.1:5000`).
- **Bootstrap tunnel.** Bundled Reality config in APK → connect → fetch real
per-session VLESS URL from inside the tunnel → reconnect. Bootstrap client
permanently in `xray_config_reality.json`, restricted by Xray routing to
internal API only.
- `serverDomain` removed from `AppConfig`. `fetchConfigThroughTunnel()`
replaces `fetchConfigWithPolling()`. `connect()` rewritten.
### Protocol — TCP to XHTTP
- Transport: TCP → XHTTP (H2 stream-up with Reality). No more XTLS-Vision,
no `flow` field. Path-hidden behind `/revolt`.
### Fixed
- **RenderFlex overflow** — status bar text wrapped in `Flexible` with
`TextOverflow.ellipsis` to prevent overflow on narrow screens (≤360dp).
- **Circular import** — removed `import 'package:revoltvpn/main.dart'` from
`sidebar_drawer.dart`. `SidebarDrawer` converted to `StatefulWidget`;
version footer loaded via `PackageInfo.fromPlatform()`.
- Client hot-reload was silently broken — `xray api adi` no-op. Fixed:
`adu`/`rmu` commands per Xray HandlerService spec.
- Missing XHTTP `path` param in VLESS URL — now reads `xhttp_path` from
`/session/status`.
- `providerBundleIdentifier` was `com.revoltvpn.app` — must match
`com.paladinvpn.app` for VPN service registration.
- Reality keypair generated (was placeholder). Throttle `uplinkOnly`/`downlinkOnly`
corrected (seconds, not bytes/sec). Fallback rate limits removed (fingerprint).
### Added
- **Settings screen** — reached from a new sidebar row (between Website and
Check for updates). Slide-from-right navigation via `PageRouteBuilder`.
Folder: `lib/screens/settings/` with one file per feature in `in_settings/`.
- **Haptic feedback toggle** — on/off switch in Settings for `lightImpact()`
vibration on successful connect/disconnect. Default: off. Uses sync-bool
pattern (no await on tap, no SharedPreferences in connect button).
- **Rain/Lightning effect toggles** — two switches in Settings to control
the animated background effects. Default: on. Effects detect the toggle
within one frame (no Provider/notifier needed).
### Changed
- **Timer box spinner removed** — the "Connecting…"/"Syncing…" spinner under
the countdown was redundant with the connect button's spinner. Timer card
is now a clean countdown only (gray '00:00:00' when idle).
- **Sidebar** now has 7 rows (added Settings). `FRONTEND_POLISH_REVIEW.md`
fully triaged: 4 items fixed, 11 skipped.
### Server
- `api` outbound + 3 routing rules in `xray_config_reality.json` (bootstrap
isolation + API routing). Permanent bootstrap client. Hivemind unchanged.
- `xhttp_path` in `/session/status` response.
- Full deployment guide: `SERVER_DEPLOYMENT.md`.
---
## [2.0.7] — 2026-07-31
### Fixed
- **Notification bug** — `SessionTimer.stop()` now cancels the persistent
Android notification on user-initiated disconnect.
- **Concurrent sync guard** — `_syncInProgress` flag prevents duplicate
HTTP requests from overlapping in `_syncWithHivemind()`.
- **Debug bypass gate** — `AppConfig.enableAdBypass` replaces `kDebugMode`
for fake AdMob callback. Tree-shaken in release builds.
### Changed
- **Responsive layout** — main screen uses `LayoutBuilder` with proportional
fractions. Scales to any screen size.
- **Dynamic version** — sidebar footer reads from `PackageInfo` instead of
hardcoded string.
- **Swarm/log blocked** — nginx returns 404 for `/api/swarm` and `/api/log`.
Monitoring runs locally via `swarm_watch.py`.
### Added
- **Update checker** in sidebar — polls GitHub Releases API.
- **Website button** in sidebar → opens `https://userevolt.app`.
- **Timer syncing indicator** — spinner during handshake.
- Dependency: `package_info_plus`.
### Server
- `/session/stop` fetches stats BEFORE popping session (race fix).
- `XrayManager._stats_lock` for diagnostic counter thread safety.
- `ManagementLoop._start_lock` prevents TOCTOU on daemon startup.
---
## [1.0.6] — 2026-06
- Initial VLESS + Xray Reality tunnel
- 60 min session, 4 GB throttle, support top-up
- Server health dot, speed display, countdown timer
- Persistent Android notification
- Glass-morphism dark UI with yellow accent
- Right-edge sidebar with Ad Consent, Privacy, About, Discord
+82
View File
@@ -0,0 +1,82 @@
# Contributing to ReVoltVPN
We would love for you to contribute to ReVoltVPN and help make it even better than it is today!
As a contributor, here are the guidelines we would like you to follow:
## <a name="commit"></a> Commit Message Format
*This specification is inspired by the Angular commit message format.*
#### <a name="commit-header"></a>Commit Message Header
```
<type>(<scope>): <short summary>
│ │ │
│ │ └─⫸ Summary in present tense. Not capitalized. No period at the end.
│ │
│ └─⫸ Commit Scope: app|docs|config
│
└─⫸ Commit Type: build|ci|docs|feat|fix|perf|refactor|test
```
The `<type>` and `<summary>` fields are mandatory, the `(<scope>)` field is optional.
##### Type
Must be one of the following:
* **build**: Changes that affect the build system or external dependencies (example: Flutter, pub, Gradle)
* **ci**: Changes to CI configuration files and scripts
* **docs**: Documentation only changes (README, AGENTS.md, comments)
* **feat**: A new feature
* **fix**: A bug fix
* **perf**: A code change that improves performance
* **refactor**: A code change that neither fixes a bug nor adds a feature
* **test**: Adding missing tests or correcting existing tests
* **style**: Changes that do not affect the meaning of the code (formatting, whitespace)
##### Scope
The scope should be the part of the project affected:
* `app` — Flutter client (screens, components, logic)
* `docs` — documentation files
* `config` — app_config, .gitignore, pubspec
The `server`, `xray` and `nginx` components are not in this repository, so
contributions targeting them cannot be reviewed or tested here.
##### Summary
Use the summary field to provide a succinct description of the change:
* use the imperative, present tense: "change" not "changed" nor "changes"
* don't capitalize the first letter
* no dot (.) at the end
#### <a name="commit-body"></a>Commit Message Body
Just as in the summary, use the imperative, present tense: "fix" not "fixed" nor "fixes".
Explain the motivation for the change in the commit message body. This commit message should explain _why_ you are making the change.
You can include a comparison of the previous behavior with the new behavior in order to illustrate the impact of the change.
#### Examples
```
feat(app): add a server selector to the settings screen
Lists the available exit locations and persists the user's choice locally.
```
```
fix(app): remove dead _isThrottled field from session timer
Field was written but never read — throttle handled by port-swap now.
Also removed unreachable 404 branch in _syncWithHivemind.
```
```
docs: update README with correct quota and Reality protocol details
```
+686 -17
View File
@@ -1,21 +1,690 @@
MIT License ReVoltVPN — Copyright (C) 2026 esef
Copyright (c) 2026 esef This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Permission is hereby granted, free of charge, to any person obtaining a copy This program is distributed in the hope that it will be useful,
of this software and associated documentation files (the "Software"), to deal but WITHOUT ANY WARRANTY; without even the implied warranty of
in the Software without restriction, including without limitation the rights MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell GNU General Public License for more details.
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all You should have received a copy of the GNU General Public License
copies or substantial portions of the Software. along with this program. If not, see <https://www.gnu.org/licenses/>.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, GNU GENERAL PUBLIC LICENSE
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Version 3, 29 June 2007
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE Everyone is permitted to copy and distribute verbatim copies
SOFTWARE. of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+43 -15
View File
@@ -1,21 +1,49 @@
Privacy Policy # Privacy Policy
Last updated: July 2025
**Last updated:** October 2026
ReVoltVPN is a free VPN service built and operated by ReVolt Team. ReVoltVPN is a free VPN service built and operated by ReVolt Team.
What we collect
## In-app disclosure
When you first open the app, we show a brief summary of this policy before you connect. You can review this full policy at any time from the sidebar menu.
## What we collect
We collect the minimum required to operate the service: We collect the minimum required to operate the service:
A randomly generated device ID created on your phone. This is not linked to your identity in any way. - A randomly generated device ID created on your phone. It is stored on your device and reused between sessions, and it is not linked to your identity in any way.
Your active session status and data usage for the current session only. Sessions last up to 1 hour, then expire. All session data is stored in memory and deleted permanently when your session ends. - Your connection duration and data usage for the current session, linked to your device ID. This is used solely to enforce the per-session quota (see below).
What we do not collect ## What our server sees
We do not collect your name, email, or any personal information. To start, check, or refresh your session, the app contacts our API directly rather than through the VPN tunnel. Our server therefore sees the IP address you are connecting from, alongside your device ID, for as long as the app is running. This is a necessary consequence of how sessions are issued and kept alive — it is separate from your browsing traffic, which is carried inside the tunnel and is described below.
We do not log your internet traffic or browsing history.
We do not sell or share any data with third parties.
Ads & Consent ## Session quotas
ReVoltVPN uses Google AdMob to display rewarded video ads. On first launch, users in the European Economic Area (EEA) and United Kingdom are shown a consent dialog (provided by Google's User Messaging Platform) that lets them choose whether to allow personalized ads. This consent choice is stored on your device and can be changed at any time by reinstalling the app. Google may collect data as part of ad delivery. Please refer to Google's Privacy Policy for details.
Your traffic Each session lasts up to **2 hours** or **10 GB** of data — whichever comes first. When your session expires or hits the data cap, the tunnel disconnects. You can start a new session by watching another ad. Session records (duration and bytes transferred) are held on our server for the life of your session and removed when it ends.
Your internet traffic is routed through our server located in Finland. We do not inspect, log, or store your traffic.
Contact Support ads (the "Support us" button) extend an active session by 30 minutes and add extra data allowance.
If you have any questions, open an issue on the GitHub repository.
## Operational logs
Server logs are written to the system journal. These logs include truncated device IDs (first 8 characters only), session start/stop events, and error messages. Logs stay on the server and are accessible only to the server operator via local console; retention follows the server's journal settings. We also maintain an aggregate total of all data ever transferred (in GB) for capacity planning — this counter is not tied to any individual device.
## What we do not collect
- We do not collect your name, email, or any personal information.
- We do not log your internet traffic, browsing history, DNS queries, or destination IPs.
- We do not inspect or store the content of your traffic.
- We do not sell your data. We do not share it with anyone, apart from what Google's ad SDK collects for ad delivery — see “Ads & Consent” below.
## Ads & Consent
ReVoltVPN uses Google AdMob to display rewarded video ads. Where required — for users in the European Economic Area (EEA) and United Kingdom — a consent dialog provided by Google's User Messaging Platform is shown before the first ad is requested, letting you choose whether to allow personalized ads. This choice is stored on your device and can be reviewed at any time from the "Ad Consent" entry in the sidebar menu. Google may collect data as part of ad delivery. Please refer to Google's Privacy Policy for details.
## Your traffic
Your internet traffic is routed through our server located in Finland. We do not inspect, log, or store your traffic. We only track total bytes transferred per session for quota enforcement — no packet contents, no destination IPs, no DNS queries.
## Contact
If you have any questions, open an issue on the GitHub repository or join the Discord server.
+30 -26
View File
@@ -1,56 +1,60 @@
---
<p align="center"> <p align="center">
<img src="screenshots/feature_graphic.png" alt="ReVoltVPN banner" width="100%"/> <img src="screenshots/feature_graphic.png" alt="ReVoltVPN banner" width="100%"/>
</p> </p>
# ReVoltVPN # ReVoltVPN
A free VPN app built from scratch. I handle the Flutter app, Hivemind backend, and AdMob integration — the ReVolt team manages server security and VLESS/Xray infrastructure.
There are hundreds of free VPN apps on the Play Store. Most of them are fine honestly — some are genuinely good. But a lot of them are vague about how they work, who runs them, and what happens to your traffic. I wanted to build something where the answer to all of those questions is just... public. A free VPN app for Android. Open-source client, transparent infrastructure. Watch an ad, get 2 hours of full-speed traffic — no accounts, no logs, no subscriptions.
So here it is.
--- ---
## How it works ## How it works
You watch a short ad. You get 60 minutes and 4 GB of full-speed traffic. That's it. The ad pays for the server (actually not even enough). No accounts, no emails, no subscriptions.
When your data runs out you get throttled to 1.5 Mbps instead of getting cut off. A second Reality inbound on a different port handles throttled traffic — your client reconnects automatically, no ad required. 1. Watch a short rewarded ad
2. Server creates a temporary VLESS session (2 hours / 10 GB)
3. Your traffic routes through a single server in Finland at full speed
4. When time or data runs out, session ends — watch another ad to continue
5. No throttling, no slow lane, no mid-session punishment
No email. No password. No payment. The ad pays for the server.
--- ---
## The stack ## Protocol
- **App** — Flutter (Android only for now)
- **Server** — A single Debian box rented from Hetzner, located in Finland - **Transport** — VLESS over XHTTP (HTTP/2 multiplexed, path-hidden behind `/revolt`)
- **VPN protocol** — VLESS + Xray Reality (XTLS-Vision). Spoofs real TLS certificates (e.g. www.microsoft.com) so your tunnel looks like regular HTTPS. Great for bypassing DPI in countries that are aggressive with it. - **Obfuscation** — Xray Reality spoofs a real website's TLS. To any DPI box, your tunnel looks like a browser visiting that website
- **Backend** — Hivemind, a Python Flask server I wrote that manages sessions, data quotas, throttling, and live swarm monitoring. Entire server is open source — in this repo. - **Encryption** — TLS 1.3 with borrowed certificate (Reality). No certbot, no domain ownership required
- **Ads** — Google AdMob rewarded ads, verified server-side so fake callbacks don't work - **API** — Standard HTTPS to a separate domain. Tunnel destination is IP-pinned — domain compromise is DoS only
--- ---
## Limitations (being honest) ## Stack
- One server, one location (Finland). That's all I can afford right now (planning to escalate further)
- 2 cores and 4GB RAM. It will not handle thousands of concurrent users | Layer | Technology |
- iOS is not supported and probably won't be for a while |-------|-----------|
- The app is built by me in my free time — expect rough edges | App | Flutter (Android) |
| VPN | VLESS + Xray Reality + XHTTP |
| Backend | Python Flask ("Hivemind") — session management, quotas, stats |
| Ads | Google AdMob rewarded, verified server-side |
| Server | Debian, single Hetzner box in Finland |
--- ---
## Why I built this ## Limitations
Free time project. I wanted to learn how VPNs actually work under the hood. Ended up building the whole thing from scratch — the Flutter app, Hivemind backend, and AdMob integration are made by me, while server security and VLESS/Xray setup are handled by the ReVolt team. It took way longer than expected.
- One server, one location (Finland)
- 2 vCPU / 4 GB RAM — not built for thousands of concurrent users
- Android only
--- ---
## Privacy ## Privacy
Your traffic goes through my server in Finland. I don't log it, I don't sell it, I have no reason to. The session manager (Hivemind) only tracks whether your session is active and how much data you've used — nothing else.
Internet privacy at the cost of watching an ad. Honest business. Your traffic routes through Finland. We don't log it, inspect it, or sell it. Hivemind tracks only session liveness and byte counters for quota enforcement — no packet contents, no destination IPs, no DNS queries.
You can read the server code yourself, it's in this repo. Full privacy policy: [`PRIVACY_POLICY.md`](PRIVACY_POLICY.md)
--- ---
*ReVoltVPN is not affiliated with any VPN company.* *ReVoltVPN is not affiliated with any VPN company.*
---
+12
View File
@@ -0,0 +1,12 @@
include: package:flutter_lints/flutter.yaml
analyzer:
exclude:
- build/**
- android/**
- local_packages/**
- whatsthis/**
linter:
rules:
avoid_print: true
+76 -7
View File
@@ -1,13 +1,20 @@
import java.util.Properties import java.util.Properties
import java.io.File
import java.io.FileInputStream import java.io.FileInputStream
import java.security.MessageDigest
plugins { plugins {
id("com.android.application") id("com.android.application")
id("dev.flutter.flutter-gradle-plugin") id("dev.flutter.flutter-gradle-plugin")
} }
fun sha256Hex(file: File): String {
val digest = MessageDigest.getInstance("SHA-256").digest(file.readBytes())
return digest.joinToString("") { "%02x".format(it.toInt() and 0xff) }
}
android { android {
namespace = "com.revoltvpn.app" namespace = "com.paladinvpn.app"
compileSdk = flutter.compileSdkVersion compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion ndkVersion = flutter.ndkVersion
@@ -17,10 +24,6 @@ android {
targetCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17
} }
packaging {
resources.excludes.add("META-INF/**")
}
val keystorePropertiesFile = rootProject.file("key.properties") val keystorePropertiesFile = rootProject.file("key.properties")
val keystoreProperties = Properties() val keystoreProperties = Properties()
if (keystorePropertiesFile.exists()) { if (keystorePropertiesFile.exists()) {
@@ -33,8 +36,70 @@ android {
admobProperties.load(FileInputStream(admobPropertiesFile)) admobProperties.load(FileInputStream(admobPropertiesFile))
} }
// Explicit opt-in used only by GitHub Actions to exercise the real
// release/R8 graph. Production release signing and config pinning remain
// fail-closed outside that CI smoke path.
val ciReleaseSmoke =
System.getenv("GITHUB_ACTIONS") == "true" &&
System.getenv("REVOLT_CI_RELEASE_SMOKE") == "true"
val appConfigFile = rootProject.file("../lib/logic/app_config.dart")
val verifyReleaseAppConfig = tasks.register("verifyReleaseAppConfig") {
group = "verification"
description = "Verify the production Dart app config against REVOLT_APP_CONFIG_SHA256."
doLast {
if (ciReleaseSmoke) {
logger.lifecycle("Skipping production app-config pin for CI release smoke build")
return@doLast
}
val expected = System.getenv("REVOLT_APP_CONFIG_SHA256")?.trim()?.lowercase()
if (expected.isNullOrEmpty()) {
throw org.gradle.api.GradleException(
"REVOLT_APP_CONFIG_SHA256 is required for production release builds"
)
}
if (!Regex("[0-9a-f]{64}").matches(expected)) {
throw org.gradle.api.GradleException(
"REVOLT_APP_CONFIG_SHA256 must be exactly 64 lowercase hexadecimal characters"
)
}
if (!appConfigFile.isFile) {
throw org.gradle.api.GradleException(
"Production app config is missing: ${appConfigFile.absolutePath}"
)
}
val configText = appConfigFile.readText()
val templateMarkers = listOf(
"'0.0.0.0'",
"YOUR_DOMAIN",
"YOUR_GITHUB_USERNAME",
"YOUR_REPO_NAME",
"ca-app-pub-0000000000000000/0000000000",
)
val remainingMarker = templateMarkers.firstOrNull(configText::contains)
if (remainingMarker != null) {
throw org.gradle.api.GradleException(
"Production app config still contains template marker: $remainingMarker"
)
}
val actual = sha256Hex(appConfigFile)
if (actual != expected) {
throw org.gradle.api.GradleException(
"Production app config SHA-256 mismatch: expected $expected, got $actual"
)
}
}
}
tasks.matching { it.name == "preReleaseBuild" }.configureEach {
dependsOn(verifyReleaseAppConfig)
}
defaultConfig { defaultConfig {
applicationId = "com.revoltvpn.app" applicationId = "com.paladinvpn.app"
minSdk = flutter.minSdkVersion minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode versionCode = flutter.versionCode
@@ -53,7 +118,11 @@ android {
buildTypes { buildTypes {
release { release {
signingConfig = signingConfigs.getByName("release") signingConfig = if (ciReleaseSmoke) {
signingConfigs.getByName("debug")
} else {
signingConfigs.getByName("release")
}
isMinifyEnabled = true isMinifyEnabled = true
isShrinkResources = true isShrinkResources = true
proguardFiles( proguardFiles(
+2 -3
View File
@@ -1,4 +1,4 @@
# PaladinVPN ProGuard / R8 Rules # ReVoltVPN ProGuard / R8 Rules
# ============================================================================== # ==============================================================================
# These rules prevent R8 from stripping classes and methods that are accessed # These rules prevent R8 from stripping classes and methods that are accessed
# via JNI (Java Native Interface) or reflection, which would cause # via JNI (Java Native Interface) or reflection, which would cause
@@ -11,9 +11,8 @@
-keep class xray.** { *; } -keep class xray.** { *; }
# ── Flutter / Platform Channels ─────────────────────────────────────────────── # ── Flutter / Platform Channels ───────────────────────────────────────────────
# io.flutter.** already includes embedding and plugin subpackages.
-keep class io.flutter.** { *; } -keep class io.flutter.** { *; }
-keep class io.flutter.embedding.** { *; }
-keep class io.flutter.plugin.** { *; }
# ── Google Mobile Ads (AdMob) ───────────────────────────────────────────────── # ── Google Mobile Ads (AdMob) ─────────────────────────────────────────────────
-keep class com.google.android.gms.ads.** { *; } -keep class com.google.android.gms.ads.** { *; }
+18 -9
View File
@@ -1,11 +1,21 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/> <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<!-- VpnService provides its own system notification; SPECIAL_USE is not needed --> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"/>
<!-- Required by url_launcher on Android 11+ to open external browser --> <uses-permission android:name="android.permission.VIBRATE"/>
<!-- Doze/App Standby stop background services of non-exempt apps. A VPN
cannot stay up without this; Play allows it for VPN functionality. -->
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<!-- flutter_vless 1.1.5 declares this legacy permission. ReVolt never needs it. -->
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
tools:node="remove"/>
<queries> <queries>
<intent> <intent>
<action android:name="android.intent.action.VIEW"/> <action android:name="android.intent.action.VIEW"/>
@@ -14,13 +24,13 @@
</queries> </queries>
<application <application
android:label="REVOLT VPN" android:label="Revolt VPN"
android:name="${applicationName}" android:name="${applicationName}"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:usesCleartextTraffic="false" android:usesCleartextTraffic="false"
android:allowBackup="false"> android:allowBackup="false"
android:extractNativeLibs="true">
<!-- AdMob App ID — injected at build time from android/admob.properties -->
<meta-data <meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID" android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="${ADMOB_APP_ID}"/> android:value="${ADMOB_APP_ID}"/>
@@ -35,16 +45,15 @@
android:windowSoftInputMode="adjustResize"> android:windowSoftInputMode="adjustResize">
<meta-data <meta-data
android:name="io.flutter.embedding.android.NormalTheme" android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme" android:resource="@style/NormalTheme"/>
/>
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN"/> <action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/> <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter> </intent-filter>
</activity> </activity>
<meta-data <meta-data
android:name="flutterEmbedding" android:name="flutterEmbedding"
android:value="2"/> android:value="2"/>
</application> </application>
</manifest> </manifest>
@@ -0,0 +1,426 @@
package com.paladinvpn.app
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.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.os.VibrationEffect
import android.os.Vibrator
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
import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
private val installerChannel = "com.revoltvpn.app/installer"
private val notificationChannel = "com.revoltvpn.app/notification"
private val hapticsChannel = "com.revoltvpn.app/haptics"
private val networkChannel = "com.revoltvpn.app/network"
private val powerChannel = "com.revoltvpn.app/power"
private var notificationChannelReady = false
private var networkCallback: ConnectivityManager.NetworkCallback? = null
private var networkEvents: EventChannel.EventSink? = null
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, installerChannel)
.setMethodCallHandler { call, result ->
if (call.method == "getInstallerPackage") {
result.success(installerPackage())
} else {
result.notImplemented()
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, powerChannel)
.setMethodCallHandler { call, result ->
when (call.method) {
"isIgnoringBatteryOptimizations" ->
result.success(isIgnoringBatteryOptimizations())
"requestIgnoreBatteryOptimizations" ->
result.success(requestIgnoreBatteryOptimizations())
else -> result.notImplemented()
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, notificationChannel)
.setMethodCallHandler { call, result ->
when (call.method) {
"updateNotificationText" -> {
val text = call.argument<String>("text") ?: ""
val title = call.argument<String>("title") ?: "Revolt VPN"
val action = call.argument<String>("disconnectLabel") ?: "Disconnect"
updateVpnNotification(title, text, action)
result.success(null)
}
// Session ends only Dart sees; the service posts the rest.
"showDisconnectedAlert" -> {
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()
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, hapticsChannel)
.setMethodCallHandler { call, result ->
if (call.method == "impact") {
val kind = call.argument<String>("kind") ?: "tap"
result.success(performHaptic(kind))
} else {
result.notImplemented()
}
}
EventChannel(flutterEngine.dartExecutor.binaryMessenger, networkChannel)
.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
networkEvents = events
startNetworkMonitor()
}
override fun onCancel(arguments: Any?) {
networkEvents = null
stopNetworkMonitor()
}
})
}
override fun onDestroy() {
stopNetworkMonitor()
super.onDestroy()
}
private fun isIgnoringBatteryOptimizations(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true
return try {
val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
pm.isIgnoringBatteryOptimizations(packageName)
} catch (_: Exception) {
false
}
}
private fun requestIgnoreBatteryOptimizations(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true
if (isIgnoringBatteryOptimizations()) return true
return try {
startActivity(
Intent(
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
Uri.parse("package:$packageName"),
),
)
true
} catch (_: Exception) {
try {
startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS))
true
} catch (_: Exception) {
false
}
}
}
private fun updateVpnNotification(title: String, text: String, actionLabel: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) !=
PackageManager.PERMISSION_GRANTED
) {
return
}
ensureNotificationChannel()
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
} else {
PendingIntent.FLAG_UPDATE_CURRENT
}
val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
launchIntent?.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or
Intent.FLAG_ACTIVITY_CLEAR_TOP or
Intent.FLAG_ACTIVITY_NEW_TASK
// The VPN service owns the authoritative Disconnect PendingIntent and
// embeds the current runtime-generation token in it. Never recreate an
// unscoped STOP intent from the UI process: a stale notification could
// otherwise stop a newer tunnel. Reuse the live service action when the
// platform exposes it; on older Android versions omit the action rather
// than weaken generation scoping.
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val serviceStopAction = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.activeNotifications
.firstOrNull { it.id == NOTIFICATION_ID }
?.notification
?.actions
?.firstOrNull()
?.actionIntent
} else {
null
}
val publicVersion = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Revolt VPN")
.setContentText("VPN is active")
.build()
val builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(title)
.setContentText(text)
.setColorized(true)
.setColor(0xFF0D1117.toInt())
.setOngoing(true)
.setAutoCancel(false)
.setOnlyAlertOnce(true)
.setSilent(true)
.setShowWhen(false)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setPublicVersion(publicVersion)
if (serviceStopAction != null) {
builder.addAction(0, actionLabel, serviceStopAction)
}
if (launchIntent != null) {
builder.setContentIntent(PendingIntent.getActivity(this, 0, launchIntent, flags))
}
try {
val notification = builder.build()
notification.flags = notification.flags or
Notification.FLAG_ONGOING_EVENT or Notification.FLAG_NO_CLEAR
NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification)
} catch (_: Exception) {
// The native foreground notification may not be ready yet.
}
}
private fun ensureNotificationChannel() {
if (notificationChannelReady) return
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
"Revolt VPN Background Service",
NotificationManager.IMPORTANCE_LOW,
)
channel.setShowBadge(false)
manager.createNotificationChannel(channel)
}
notificationChannelReady = true
}
private fun startNetworkMonitor() {
if (networkCallback != null) return
val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val callback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
emitBestPhysicalNetwork(manager, "available")
}
override fun onLost(network: Network) {
emitBestPhysicalNetwork(manager, "lost")
}
override fun onCapabilitiesChanged(
network: Network,
capabilities: NetworkCapabilities,
) {
emitBestPhysicalNetwork(manager, "changed")
}
}
try {
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
.build()
manager.registerNetworkCallback(request, callback)
networkCallback = callback
emitBestPhysicalNetwork(manager, "initial")
} catch (e: Exception) {
networkEvents?.error("NETWORK_MONITOR", e.message, null)
}
}
private fun stopNetworkMonitor() {
val callback = networkCallback ?: return
val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
try {
manager.unregisterNetworkCallback(callback)
} catch (_: Exception) {
}
networkCallback = null
}
private fun emitBestPhysicalNetwork(
manager: ConnectivityManager,
reason: String,
) {
val best = manager.allNetworks
.mapNotNull { network ->
val capabilities = manager.getNetworkCapabilities(network)
?: return@mapNotNull null
if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
return@mapNotNull null
}
if (!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) ||
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
) {
return@mapNotNull null
}
Triple(network, capabilities, physicalNetworkScore(capabilities))
}
.maxByOrNull { it.third }
if (best == null) {
emitNetworkPayload(
mapOf<String, Any>(
"reason" to reason,
"transport" to "none",
"connected" to false,
"validated" to false,
"metered" to false,
"timestamp" to System.currentTimeMillis(),
),
)
return
}
emitNetworkState(best.first, best.second, reason)
}
private fun physicalNetworkScore(capabilities: NetworkCapabilities): Int {
var score = 0
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
) {
score += 100
}
score += when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> 40
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> 30
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> 20
else -> 10
}
return score
}
private fun emitNetworkState(
network: Network,
capabilities: NetworkCapabilities,
reason: String,
) {
val transport = when {
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> "ethernet"
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> "wifi"
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> "cellular"
else -> "other"
}
val validated = Build.VERSION.SDK_INT < Build.VERSION_CODES.M ||
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
val metered = !capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
emitNetworkPayload(
mapOf<String, Any>(
"reason" to reason,
"transport" to transport,
"connected" to true,
"validated" to validated,
"metered" to metered,
"timestamp" to System.currentTimeMillis(),
),
)
}
private fun emitNetworkPayload(payload: Map<String, Any>) {
runOnUiThread { networkEvents?.success(payload) }
}
private fun installerPackage(): String? = try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
packageManager.getInstallSourceInfo(packageName).installingPackageName
} else {
@Suppress("DEPRECATION")
packageManager.getInstallerPackageName(packageName)
}
} catch (_: Exception) {
null
}
private fun performHaptic(kind: String): Boolean {
return try {
val vibrator: Vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val manager =
getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
manager.defaultVibrator
} else {
@Suppress("DEPRECATION")
getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
}
if (!vibrator.hasVibrator()) {
false
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val effect = when (kind) {
"selection" -> VibrationEffect.EFFECT_TICK
"success" -> VibrationEffect.EFFECT_HEAVY_CLICK
else -> VibrationEffect.EFFECT_CLICK
}
vibrator.vibrate(VibrationEffect.createPredefined(effect))
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val durationMs = if (kind == "success") 24L else 14L
val amplitude = if (kind == "success") 110 else 70
vibrator.vibrate(VibrationEffect.createOneShot(durationMs, amplitude))
} else {
@Suppress("DEPRECATION")
vibrator.vibrate(if (kind == "success") 24L else 14L)
}
true
}
} catch (_: Exception) {
false
}
}
companion object {
private const val NOTIFICATION_ID = 1
private const val NOTIFICATION_CHANNEL_ID = "REVOLT_VPN_SERVICE"
}
}
@@ -1,5 +0,0 @@
package com.revoltvpn.app
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

After

Width:  |  Height:  |  Size: 174 KiB

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" <shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"> android:shape="rectangle">
<solid android:color="#0d1017" /> <solid android:color="@color/splash_bg" />
</shape> </shape>
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M12,1.5L21,5.2V11.1C21,16.7 17.4,21 12,22.5C6.6,21 3,16.7 3,11.1V5.2L12,1.5ZM12,5L6.5,7.2V11C6.5,14.8 8.7,17.8 12,19C15.3,17.8 17.5,14.8 17.5,11V7.2L12,5ZM10.8,9H13.2V13.8H10.8V9ZM10.8,15H13.2V17.4H10.8V15Z" />
</vector>
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowSplashScreenBackground">@color/splash_bg</item>
<item name="android:windowBackground">@color/splash_bg</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/splash_bg</item>
<item name="android:navigationBarColor">@color/splash_bg</item>
</style>
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@color/splash_bg</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/splash_bg</item>
<item name="android:navigationBarColor">@color/splash_bg</item>
</style>
</resources>
@@ -1,18 +1,15 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar"> <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item> <item name="android:windowBackground">@drawable/launch_background</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/splash_bg</item>
<item name="android:navigationBarColor">@color/splash_bg</item>
</style> </style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar"> <style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item> <item name="android:windowBackground">@color/splash_bg</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/splash_bg</item>
<item name="android:navigationBarColor">@color/splash_bg</item>
</style> </style>
</resources> </resources>
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowSplashScreenBackground">@color/splash_bg</item>
<item name="android:windowBackground">@color/splash_bg</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/splash_bg</item>
<item name="android:navigationBarColor">@color/splash_bg</item>
</style>
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@color/splash_bg</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/splash_bg</item>
<item name="android:navigationBarColor">@color/splash_bg</item>
</style>
</resources>
+1 -1
View File
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<color name="splash_bg">#0d1017</color> <color name="splash_bg">#0D1117</color>
</resources> </resources>
+6 -9
View File
@@ -1,18 +1,15 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<resources> <resources>
<!-- Theme applied to the Android Window while the process is starting -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar"> <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item> <item name="android:windowBackground">@drawable/launch_background</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/splash_bg</item>
<item name="android:navigationBarColor">@color/splash_bg</item>
</style> </style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar"> <style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@color/splash_bg</item> <item name="android:windowBackground">@color/splash_bg</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/splash_bg</item>
<item name="android:navigationBarColor">@color/splash_bg</item>
</style> </style>
</resources> </resources>
+3 -4
View File
@@ -1,8 +1,7 @@
org.gradle.jvmargs=-Xmx1536M org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8
android.enableR8=true org.gradle.workers.max=2
android.useAndroidX=true android.useAndroidX=true
android.enableJetifier=true android.enableJetifier=true
# This builtInKotlin flag was added automatically by Flutter migrator # These compatibility flags are managed by Flutter's Android toolchain.
android.builtInKotlin=false android.builtInKotlin=false
# This newDsl flag was added automatically by Flutter migrator
android.newDsl=false android.newDsl=false
File diff suppressed because it is too large. Load diff
Binary file not shown.
+3
View File
@@ -3,3 +3,6 @@ distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip
distributionSha256Sum=efe9a3d147d948d7528a9887fa35abcf24ca1a43ad06439996490f77569b02d1
networkTimeout=10000
validateDistributionUrl=true
Vendored Executable
+251
View File
@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 492 KiB

File renamed without changes.
-115
View File
@@ -1,115 +0,0 @@
// =============================================================================
// clock_display.dart — EDUCATIONAL REFERENCE (not used in production)
// =============================================================================
//
// This widget was the original combined timer + speed + syncing display.
// It was replaced by the separate TimerBox and SpeedBox widgets in the
// Reality-era UI refactor.
//
// What's worth studying here:
//
// 1. TEXT GLOW EFFECT — the yellow glow around the countdown timer:
// ```
// shadows: [Shadow(color: AppColors.accent50, blurRadius: 16)]
// ```
// This exact effect was ported to timer_box.dart and is what gives
// the countdown its signature pulsing-yellow look.
//
// 2. SYNCING PLACEHOLDER — conditional spinner + label when the first
// server poll hasn't returned yet. Shows "Syncing…" with a small
// CircularProgressIndicator instead of flashing 00:00:00.
//
// 3. COMBINED DISPLAY — clock + speed stacked in a Column inside a
// fixed 200×200 SizedBox. The modern UI split these into separate
// boxes for the stacked layout, but the stacking approach here is
// a good reference for compact combined displays.
//
// Kept in the repo for reference. Safe to delete if you're pruning.
// =============================================================================
// import 'package:flutter/material.dart';
// import 'package:provider/provider.dart';
// import 'package:revoltvpn/logic/app_colors.dart';
// import 'package:revoltvpn/logic/session_timer.dart';
// class ClockDisplay extends StatelessWidget {
// const ClockDisplay({super.key});
// @override
// Widget build(BuildContext context) {
// return Consumer<SessionTimer>(
// builder: (context, timer, _) {
// final bool showSyncing = !timer.hasSyncedOnce;
// return SizedBox(
// width: 200,
// height: 200,
// child: Stack(
// alignment: Alignment.center,
// children: [
// Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// if (showSyncing) ...[
// const SizedBox(
// width: 32,
// height: 32,
// child: CircularProgressIndicator(
// strokeWidth: 2,
// color: AppColors.accent50,
// ),
// ),
// const SizedBox(height: 10),
// const Text(
// 'Syncing…',
// style: TextStyle(
// fontSize: 16,
// fontWeight: FontWeight.w600,
// color: AppColors.accent60,
// letterSpacing: 1.5,
// ),
// ),
// ] else ...[
// Text(
// timer.formatted,
// style: const TextStyle(
// fontSize: 40,
// fontWeight: FontWeight.w800,
// color: AppColors.textWhite,
// letterSpacing: 2,
// shadows: [
// Shadow(
// color: AppColors.accent50,
// blurRadius: 16,
// ),
// ],
// ),
// ),
// const SizedBox(height: 6),
// Row(
// mainAxisSize: MainAxisSize.min,
// children: [
// const Icon(Icons.speed, color: AppColors.textDim, size: 14),
// const SizedBox(width: 4),
// Text(
// timer.currentSpeedKBps > 0.5
// ? '${timer.currentSpeedKBps.toStringAsFixed(1)} KB/s'
// : 'Idle',
// style: const TextStyle(
// fontSize: 12,
// color: AppColors.textDim,
// fontWeight: FontWeight.w500,
// ),
// ),
// ],
// ),
// ],
// ],
// ),
// ],
// ),
// );
// },
// );
// }
// }
+76 -41
View File
@@ -1,10 +1,10 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:revoltvpn/logic/app_colors.dart'; import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/logic/vpn_connection.dart'; import 'package:revoltvpn/logic/vpn_connection.dart';
import 'package:revoltvpn/logic/session_timer.dart'; import 'package:revoltvpn/logic/session_timer.dart';
import 'package:revoltvpn/logic/ad_manager.dart'; import 'package:revoltvpn/logic/ad_manager.dart';
import 'package:revoltvpn/logic/haptic_settings.dart';
class ConnectButton extends StatefulWidget { class ConnectButton extends StatefulWidget {
const ConnectButton({super.key}); const ConnectButton({super.key});
@@ -14,34 +14,47 @@ class ConnectButton extends StatefulWidget {
} }
class _ConnectButtonState extends State<ConnectButton> class _ConnectButtonState extends State<ConnectButton>
with SingleTickerProviderStateMixin { with SingleTickerProviderStateMixin, WidgetsBindingObserver {
bool _busy = false; bool _busy = false;
DateTime _lastTap = DateTime.now(); DateTime _lastTap = DateTime.fromMillisecondsSinceEpoch(0);
AnimationController? _pulse; AnimationController? _pulse;
Animation<double>? _pulseAnim; Animation<double>? _pulseAnim;
VpnConnection? _vpn;
double get _pulseValue => _pulseAnim?.value ?? 0.0; double get _pulseValue => _pulseAnim?.value ?? 0.0;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
final pulse = AnimationController(vsync: this, duration: const Duration(milliseconds: 2000)); final pulse = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 2000),
);
_pulse = pulse; _pulse = pulse;
_pulseAnim = Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation(parent: pulse, curve: Curves.easeInOut)); _pulseAnim = Tween(begin: 0.0, end: 1.0).animate(
CurvedAnimation(parent: pulse, curve: Curves.easeInOut),
);
WidgetsBinding.instance.addObserver(this);
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<VpnConnection>().addListener(_onVpnChanged); if (!mounted || _vpn != null) return;
final vpn = context.read<VpnConnection>();
_vpn = vpn;
vpn.addListener(_onVpnChanged);
_onVpnChanged();
}); });
} }
@override @override
void dispose() { void dispose() {
context.read<VpnConnection>().removeListener(_onVpnChanged); WidgetsBinding.instance.removeObserver(this);
_vpn?.removeListener(_onVpnChanged);
_pulse?.dispose(); _pulse?.dispose();
super.dispose(); super.dispose();
} }
void _onVpnChanged() { void _onVpnChanged() {
final vpn = context.read<VpnConnection>(); final vpn = _vpn;
if (vpn == null) return;
if (vpn.status == VpnStatus.connected) { if (vpn.status == VpnStatus.connected) {
_pulse?.repeat(reverse: true); _pulse?.repeat(reverse: true);
} else { } else {
@@ -50,41 +63,46 @@ class _ConnectButtonState extends State<ConnectButton>
} }
} }
Future<void> _handleTap() async { @override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (!mounted) return;
if (state != AppLifecycleState.resumed) {
_pulse?.stop();
return;
}
if (_vpn?.status == VpnStatus.connected) {
_pulse?.repeat(reverse: true);
}
}
Future<void> _handleTap() async {
final now = DateTime.now(); final now = DateTime.now();
if (now.difference(_lastTap).inMilliseconds < 1000) return; if (now.difference(_lastTap).inMilliseconds < 1000) return;
_lastTap = now; _lastTap = now;
HapticFeedback.lightImpact();
final vpn = context.read<VpnConnection>(); final vpn = context.read<VpnConnection>();
final timer = context.read<SessionTimer>(); final timer = context.read<SessionTimer>();
final ad = context.read<AdManager>(); final ad = context.read<AdManager>();
if (vpn.status == VpnStatus.connected || vpn.status == VpnStatus.connecting) { if (vpn.status == VpnStatus.connected || vpn.status == VpnStatus.connecting) {
_busy = false; _busy = false;
timer.stop(); // MUST stop timer BEFORE disconnect — prevents auto-reconnect await timer.disconnect();
await vpn.disconnect(); HapticSettings.success();
return; return;
} }
if (vpn.status == VpnStatus.disconnecting || _busy) return;
if (vpn.status == VpnStatus.disconnecting) return;
if (_busy) return;
setState(() => _busy = true); setState(() => _busy = true);
try { try {
final adWatched = await ad.showAd('main'); final adNonce = await ad.showAd('main');
if (!adWatched && AdManager.adsEnabled) { if (adNonce == null && AdManager.adsEnabled) return;
setState(() => _busy = false);
return; final ok = await vpn.connect(adNonce: adNonce);
if (ok) {
await timer.start();
HapticSettings.success();
} }
final ok = await vpn.connect();
if (ok) timer.start();
} finally { } finally {
if (mounted) setState(() => _busy = false); if (mounted) setState(() => _busy = false);
} }
@@ -103,20 +121,41 @@ class _ConnectButtonState extends State<ConnectButton>
child: _pulseAnim != null child: _pulseAnim != null
? AnimatedBuilder( ? AnimatedBuilder(
animation: _pulseAnim!, animation: _pulseAnim!,
builder: (_, __) => _buildCircle(isConnected, spinning, _pulseValue), child: _buildInner(spinning),
builder: (_, child) =>
_buildCircle(isConnected, _pulseValue, child),
) )
: _buildCircle(isConnected, spinning, 0), : _buildCircle(isConnected, 0, _buildInner(spinning)),
); );
}, },
); );
} }
Widget _buildCircle(bool isConnected, bool spinning, double pulse) { Widget _buildInner(bool spinning) {
if (spinning) {
return const Center(
child: SizedBox(
width: 36,
height: 36,
child: CircularProgressIndicator(
strokeWidth: 2.5,
color: AppColors.accent70,
),
),
);
}
return Padding(
padding: const EdgeInsets.all(14),
child: Image.asset('assets/brand.png', fit: BoxFit.contain),
);
}
Widget _buildCircle(bool isConnected, double pulse, Widget? child) {
final glowAlpha = isConnected ? ((0.3 + pulse * 0.25) * 255).round() : 0; final glowAlpha = isConnected ? ((0.3 + pulse * 0.25) * 255).round() : 0;
final glowRadius = isConnected ? 18.0 + (pulse * 14) : 0.0; final glowRadius = isConnected ? 18.0 + (pulse * 14) : 0.0;
return Container( return Container(
width: 260, // <-- CHANGE ME: circle size width: 260,
height: 260, height: 260,
decoration: BoxDecoration( decoration: BoxDecoration(
shape: BoxShape.circle, shape: BoxShape.circle,
@@ -126,21 +165,17 @@ class _ConnectButtonState extends State<ConnectButton>
width: isConnected ? 2.5 : 1.5, width: isConnected ? 2.5 : 1.5,
), ),
boxShadow: isConnected boxShadow: isConnected
? [BoxShadow(color: Color.fromARGB(glowAlpha, 255, 214, 0), blurRadius: glowRadius, spreadRadius: glowRadius * 0.3)] ? [
BoxShadow(
color: Color.fromARGB(glowAlpha, 255, 214, 0),
blurRadius: glowRadius,
spreadRadius: glowRadius * 0.3,
),
]
: [], : [],
), ),
clipBehavior: Clip.hardEdge, clipBehavior: Clip.hardEdge,
child: spinning child: child,
? const Center(
child: SizedBox(
width: 36, height: 36,
child: CircularProgressIndicator(strokeWidth: 2.5, color: AppColors.accent70),
),
)
: Padding(
padding: const EdgeInsets.all(14), // <-- CHANGE ME: brand.png padding from edge
child: Image.asset('assets/brand.png', fit: BoxFit.contain),
),
); );
} }
} }
+105
View File
@@ -0,0 +1,105 @@
// lib/components/data_disclosure_dialog.dart
// First-launch data disclosure dialog — Google Play Data safety section requirement.
// Shows once per install; preference persisted in SharedPreferences.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:revoltvpn/logic/app_colors.dart';
class DataDisclosureDialog {
DataDisclosureDialog._();
static const _key = 'data_disclosure_accepted';
/// Shows the disclosure dialog if the user hasn't accepted it yet.
/// Call once after the main screen is mounted (post-frame callback).
static Future<void> showIfFirstLaunch(BuildContext context) async {
final prefs = await SharedPreferences.getInstance();
if (prefs.getBool(_key) == true) return; // Already accepted.
if (!context.mounted) return;
final accepted = await showDialog<bool>(
context: context,
barrierDismissible: false, // Must tap Continue — no tap-outside dismiss.
builder: (_) => const _DisclosureDialog(),
);
if (accepted != true) return;
// Persist only after the user action is complete. If storage fails, do not
// invent an accepted state; the disclosure will simply reappear later.
try {
final saved = await prefs.setBool(_key, true);
if (!saved) {
debugPrint('[Disclosure] Preference write was rejected');
}
} catch (e) {
debugPrint('[Disclosure] Failed to persist acknowledgement: $e');
}
}
}
class _DisclosureDialog extends StatelessWidget {
const _DisclosureDialog();
@override
Widget build(BuildContext context) {
return Dialog(
backgroundColor: AppColors.bgCard,
insetPadding: const EdgeInsets.symmetric(horizontal: 28, vertical: 40),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.fromLTRB(24, 28, 24, 20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Before you connect',
style: TextStyle(
color: AppColors.textWhite,
fontSize: 20,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 16),
const Text(
'Revolt VPN creates a secure VPN tunnel to protect your '
'traffic. To enforce your data/time quota, we log your '
'connection duration and data usage, linked to a randomly '
'generated device ID — not to your identity. We do not log '
'or monitor the content of your traffic. We do not share '
'your data with third parties. The full policy is in the '
'sidebar menu under "Privacy Policy".',
style: TextStyle(
color: AppColors.textMuted,
fontSize: 14,
height: 1.5,
),
),
const SizedBox(height: 24),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
style: ElevatedButton.styleFrom(
backgroundColor: AppColors.accent,
foregroundColor: AppColors.bgDeep,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
textStyle: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
),
),
child: const Text('Continue'),
),
),
],
),
),
);
}
}
+248
View File
@@ -0,0 +1,248 @@
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/screens/settings/in_settings/lightning.dart';
/// 2D lightning bolt — a jagged yellow line from top to bottom with glow.
class LightningEffect extends StatefulWidget {
final int minIntervalSec;
final int maxIntervalSec;
final double doubleChance;
const LightningEffect({
super.key,
this.minIntervalSec = 2,
this.maxIntervalSec = 10,
this.doubleChance = 0.2,
});
@override
State<LightningEffect> createState() => _LightningEffectState();
}
class _LightningEffectState extends State<LightningEffect>
with SingleTickerProviderStateMixin {
late final AnimationController _ctrl;
Timer? _timer;
final _random = Random();
LightningBolt? _bolt;
@override
void initState() {
super.initState();
_ctrl = AnimationController(vsync: this, duration: const Duration(milliseconds: 400));
lightningEnabled.addListener(_onEnabledChanged);
if (lightningEnabled.value) _scheduleNext();
}
void _onEnabledChanged() {
if (lightningEnabled.value) {
_scheduleNext();
} else {
_timer?.cancel();
_ctrl.stop();
_bolt = null;
}
if (mounted) setState(() {});
}
@override
void dispose() {
lightningEnabled.removeListener(_onEnabledChanged);
_timer?.cancel();
_ctrl.dispose();
super.dispose();
}
void _scheduleNext() {
final secs = widget.minIntervalSec +
_random.nextInt(widget.maxIntervalSec - widget.minIntervalSec + 1);
_timer = Timer(Duration(seconds: secs), _strike);
}
void _strike() {
if (!mounted || !lightningEnabled.value) return;
_bolt = LightningBolt.random(_random);
_ctrl.forward(from: 0.0);
if (_random.nextDouble() < widget.doubleChance) {
Future.delayed(const Duration(milliseconds: 120), () {
if (mounted && lightningEnabled.value) {
_bolt = LightningBolt.random(_random);
_ctrl.forward(from: 0.0);
}
});
}
_scheduleNext();
}
/// Sharp flash curve: quick on, quick off. No slow fade.
double _opacity(double t) {
if (t < 0.08) return t / 0.08; // fast ramp
return 1.0 - ((t - 0.08) / 0.92); // linear decay
}
@override
Widget build(BuildContext context) {
if (!lightningEnabled.value) return const SizedBox.shrink();
return AnimatedBuilder(
animation: _ctrl,
builder: (_, child) {
final raw = _opacity(_ctrl.value);
if (raw <= 0.02 || _bolt == null) return const SizedBox.shrink();
return IgnorePointer(
child: LayoutBuilder(
builder: (ctx, constraints) {
final sz = Size(constraints.maxWidth, constraints.maxHeight);
return CustomPaint(
size: sz,
painter: _LightningPainter(
bolt: _bolt!,
opacity: raw,
),
);
},
),
);
},
);
}
}
/// A single bolt defined by a list of 2D points (0.0–1.0 in width×height space).
class LightningBolt {
final List<Offset> mainPath;
final List<List<Offset>> branches; // 0–2 forks off the main path
const LightningBolt({required this.mainPath, this.branches = const []});
/// Generate a random bolt. The path always starts near the top-center
/// and ends near the bottom, zigzagging left/right along the way.
factory LightningBolt.random(Random rng) {
final points = <Offset>[];
// Start: top, slight horizontal offset
double x = 0.5 + (rng.nextDouble() - 0.5) * 0.15;
points.add(Offset(x, 0.0));
// Zigzag down — 6–10 segments
final segments = 6 + rng.nextInt(5);
for (int i = 1; i < segments; i++) {
final y = i / segments;
// Random horizontal offset — each segment adds jitter
x += (rng.nextDouble() - 0.5) * 0.25;
x = x.clamp(0.05, 0.95); // stay on screen
points.add(Offset(x, y));
}
// End: bottom
points.add(Offset(x.clamp(0.1, 0.9), 1.0));
// Branches — 0–2 forks from random points along the main path
final branches = <List<Offset>>[];
final branchCount = rng.nextInt(3);
for (int b = 0; b < branchCount; b++) {
final branch = <Offset>[];
final startIdx = 1 + rng.nextInt(points.length - 2);
final start = points[startIdx];
branch.add(start);
double bx = start.dx;
double by = start.dy;
final branchLen = 2 + rng.nextInt(3);
for (int j = 0; j < branchLen; j++) {
by += (0.05 + rng.nextDouble() * 0.12);
bx += (rng.nextDouble() - 0.5) * 0.3;
bx = bx.clamp(0.02, 0.98);
by = by.clamp(0.0, 1.0);
branch.add(Offset(bx, by));
}
branches.add(branch);
}
return LightningBolt(mainPath: points, branches: branches);
}
}
class _LightningPainter extends CustomPainter {
final LightningBolt bolt;
final double opacity;
_LightningPainter({required this.bolt, required this.opacity});
@override
void paint(Canvas canvas, Size size) {
Offset toScreen(Offset p) => Offset(p.dx * size.width, p.dy * size.height);
final scaledMain = bolt.mainPath.map(toScreen).toList();
final scaledBranches = bolt.branches
.map((b) => b.map(toScreen).toList())
.toList();
final baseColor = AppColors.accent.withAlpha((opacity * 255).round());
final glowColor = AppColors.accent.withAlpha((opacity * 0.35 * 255).round());
// Glow
final glowPaint = Paint()
..color = glowColor
..strokeWidth = 18
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 8)
..style = PaintingStyle.stroke;
_drawPath(canvas, scaledMain, scaledBranches, glowPaint);
// Core
final corePaint = Paint()
..color = baseColor
..strokeWidth = 5
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..style = PaintingStyle.stroke;
_drawPath(canvas, scaledMain, scaledBranches, corePaint);
// Hot center
if (opacity > 0.6) {
final hotPaint = Paint()
..color = Colors.white.withAlpha((opacity * 180).round())
..strokeWidth = 2
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..style = PaintingStyle.stroke;
_drawPath(canvas, scaledMain, scaledBranches, hotPaint);
}
}
void _drawPath(Canvas canvas, List<Offset> main,
List<List<Offset>> branches, Paint paint) {
final mainPath = Path()..moveTo(main.first.dx, main.first.dy);
for (int i = 1; i < main.length; i++) {
mainPath.lineTo(main[i].dx, main[i].dy);
}
canvas.drawPath(mainPath, paint);
for (final branch in branches) {
final bPath = Path()..moveTo(branch.first.dx, branch.first.dy);
for (int i = 1; i < branch.length; i++) {
bPath.lineTo(branch[i].dx, branch[i].dy);
}
canvas.drawPath(bPath, paint);
}
}
@override
bool shouldRepaint(covariant _LightningPainter old) =>
bolt != old.bolt || opacity != old.opacity;
}
-102
View File
@@ -1,102 +0,0 @@
import 'dart:io';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class VpnNotificationManager {
static final FlutterLocalNotificationsPlugin _plugin =
FlutterLocalNotificationsPlugin();
static bool _initialized = false;
static Future<void> init() async {
if (_initialized) return;
const androidSettings =
AndroidInitializationSettings('@drawable/notification_icon');
const initSettings = InitializationSettings(android: androidSettings);
await _plugin.initialize(initSettings);
// Request POST_NOTIFICATIONS permission on Android 13+
if (Platform.isAndroid) {
final androidPlugin = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
await androidPlugin?.requestNotificationsPermission();
}
_initialized = true;
}
static String? _lastTimeLeft;
static String? _lastSpeedKbps;
static Future<void> showOrUpdateStatus({
required String timeLeft,
required String speedKbps,
}) async {
// Skip update if nothing changed — prevents notification flicker
// on Android skins that animate every notification update.
if (timeLeft == _lastTimeLeft && speedKbps == _lastSpeedKbps) return;
_lastTimeLeft = timeLeft;
_lastSpeedKbps = speedKbps;
if (!_initialized) await init();
// NOTE: The channel ID includes 'v2' to force Android to create a fresh
// notification channel. Android channels are immutable once created — if
// the old channel was created without 'ongoing: true', users would be
// stuck with a swipeable notification forever.
const androidDetails = AndroidNotificationDetails(
'revolt_vpn_status_v2',
'VPN Status',
channelDescription: 'Shown while VPN is active — non-dismissable',
importance: Importance.low,
priority: Priority.low,
// Non-dismissable while VPN is running
ongoing: true,
autoCancel: false,
// Silent updates — no sound or vibration each time stats refresh
playSound: false,
enableVibration: false,
onlyAlertOnce: true,
// Hide the auto-generated timestamp
showWhen: false,
// Show on lock screen
visibility: NotificationVisibility.public,
// Extra insurance against swipe-to-dismiss on aggressive Android skins
usesChronometer: false,
category: AndroidNotificationCategory.service,
);
const notificationDetails = NotificationDetails(android: androidDetails);
try {
await _plugin.show(
888, // Fixed ID — always updates the same notification
'REVOLT VPN Active',
'Time: $timeLeft • $speedKbps',
notificationDetails,
);
} catch (e) {
// If showing fails (e.g. permission revoked), try to recover by
// re-initializing and retrying once.
_initialized = false;
try {
await init();
await _plugin.show(
888,
'REVOLT VPN Active',
'Time: $timeLeft • $speedKbps',
notificationDetails,
);
} catch (_) {
// Give up — the VPN still works, just without the notification.
}
}
}
static Future<void> cancel() async {
if (!_initialized) return;
await _plugin.cancel(888);
}
}
+183
View File
@@ -0,0 +1,183 @@
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:revoltvpn/screens/settings/in_settings/rain.dart';
/// Subtle animated rain effect — sits behind all UI as a full-screen overlay.
///
/// Usage (in a Stack, as the first child so it renders behind everything):
class RainEffect extends StatefulWidget {
final int dropCount;
final Color color;
final double minLength;
final double maxLength;
final double windDrift;
const RainEffect({
super.key,
this.dropCount = 150,
this.color = const Color(0xFFE8EAF6),
this.minLength = 12,
this.maxLength = 44,
this.windDrift = 4.0,
});
@override
State<RainEffect> createState() => _RainEffectState();
}
class _RainEffectState extends State<RainEffect>
with SingleTickerProviderStateMixin {
late final Ticker _ticker;
final _drops = <_Drop>[];
final _random = Random();
final _repaint = ValueNotifier<int>(0);
Duration _last = Duration.zero;
// Lifecycle
@override
void initState() {
super.initState();
for (int i = 0; i < widget.dropCount; i++) {
_drops.add(
_Drop.spawn(_random, widget.minLength, widget.maxLength, widget.color));
}
_ticker = createTicker(_onTick);
rainEnabled.addListener(_onEnabledChanged);
if (rainEnabled.value) _ticker.start();
}
@override
void dispose() {
rainEnabled.removeListener(_onEnabledChanged);
_ticker.dispose();
_repaint.dispose();
super.dispose();
}
void _onEnabledChanged() {
if (rainEnabled.value) {
// Ticker elapsed restarts at zero; a stale _last makes the first dt negative.
_last = Duration.zero;
_ticker.start();
} else {
_ticker.stop();
}
if (mounted) setState(() {});
}
// Tick
void _onTick(Duration now) {
double dt = 0.016; // ~60 fps fallback on first tick
if (_last != Duration.zero) {
dt = (now - _last).inMicroseconds / 1000000.0;
dt = dt.clamp(0.0, 0.1);
}
_last = now;
for (final d in _drops) {
d.y += d.speed * dt;
if (d.y > 1.08) {
d.spawn(_random, widget.minLength, widget.maxLength, widget.color);
d.y = -0.06 - _random.nextDouble() * 0.08;
}
}
_repaint.value++;
}
// Build
@override
Widget build(BuildContext context) {
if (!rainEnabled.value) return const SizedBox.shrink();
return CustomPaint(
painter: _RainPainter(
drops: _drops,
windDrift: widget.windDrift,
repaint: _repaint,
),
size: Size.infinite,
);
}
}
// ═══════════════════════════════════════════════════════════════════════════
// Drop model
// ═══════════════════════════════════════════════════════════════════════════
class _Drop {
double x;
double y;
double speed;
double length;
Color color;
_Drop({
required this.x,
required this.y,
required this.speed,
required this.length,
required this.color,
});
/// Create a drop at a random position anywhere on screen.
factory _Drop.spawn(Random r, double minLen, double maxLen, Color base) {
return _Drop(
x: r.nextDouble(),
y: r.nextDouble(),
speed: 0.30 + r.nextDouble() * 0.55,
length: minLen + r.nextDouble() * (maxLen - minLen),
color: base.withAlpha(((0.05 + r.nextDouble() * 0.12) * 255).round()),
);
}
/// Re-randomise all properties (call when recycling a drop to the top).
void spawn(Random r, double minLen, double maxLen, Color base) {
x = r.nextDouble();
speed = 0.30 + r.nextDouble() * 0.55;
length = minLen + r.nextDouble() * (maxLen - minLen);
color = base.withAlpha(((0.05 + r.nextDouble() * 0.12) * 255).round());
}
}
// ═══════════════════════════════════════════════════════════════════════════
// Painter
// ═══════════════════════════════════════════════════════════════════════════
class _RainPainter extends CustomPainter {
final List<_Drop> drops;
final double windDrift;
_RainPainter({
required this.drops,
required this.windDrift,
required Listenable repaint,
}) : super(repaint: repaint);
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..strokeCap = StrokeCap.round
..strokeWidth = 1.5;
for (final d in drops) {
final sx = d.x * size.width;
final sy = d.y * size.height;
final ex = sx - windDrift; // slight leftward slant
final ey = sy + d.length;
paint.color = d.color;
canvas.drawLine(Offset(sx, sy), Offset(ex, ey), paint);
}
}
@override
bool shouldRepaint(_RainPainter old) => false; // repaint listenable drives frames
}
@@ -6,7 +6,7 @@ class DiscordLinkButton extends StatelessWidget {
const DiscordLinkButton({super.key}); const DiscordLinkButton({super.key});
static Future<void> launchDiscord() async { static Future<void> launchDiscord() async {
final Uri url = Uri.parse('https://discord.gg/revoltvpn'); final Uri url = Uri.parse('https://discord.gg/y7SXpjr2ff');
if (!await launchUrl(url, mode: LaunchMode.externalApplication)) { if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
debugPrint('Could not launch $url'); debugPrint('Could not launch $url');
} }
@@ -14,8 +14,8 @@ class DiscordLinkButton extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return IconButton( return const IconButton(
icon: const Icon(Icons.discord, color: AppColors.textWhite, size: 28), icon: Icon(Icons.discord, color: AppColors.textWhite, size: 28),
onPressed: launchDiscord, onPressed: launchDiscord,
tooltip: 'Join Discord', tooltip: 'Join Discord',
splashRadius: 24, splashRadius: 24,
@@ -76,8 +76,8 @@ class GdprButton extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return IconButton( return const IconButton(
icon: const Icon(Icons.admin_panel_settings_outlined, icon: Icon(Icons.admin_panel_settings_outlined,
color: AppColors.textWhite, size: 28), color: AppColors.textWhite, size: 28),
onPressed: showConsentForm, onPressed: showConsentForm,
tooltip: 'Ad consent & privacy choices', tooltip: 'Ad consent & privacy choices',
@@ -14,8 +14,8 @@ class InfoButton extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return IconButton( return const IconButton(
icon: const Icon(Icons.help_outline, color: AppColors.textWhite, size: 28), icon: Icon(Icons.help_outline, color: AppColors.textWhite, size: 28),
onPressed: launchGitHub, onPressed: launchGitHub,
tooltip: 'About ReVoltVPN', tooltip: 'About ReVoltVPN',
splashRadius: 24, splashRadius: 24,
@@ -14,8 +14,8 @@ class PrivacyPolicyButton extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return IconButton( return const IconButton(
icon: const Icon(Icons.privacy_tip_outlined, color: AppColors.textWhite, size: 28), icon: Icon(Icons.privacy_tip_outlined, color: AppColors.textWhite, size: 28),
onPressed: launchPrivacyPolicy, onPressed: launchPrivacyPolicy,
tooltip: 'Privacy Policy', tooltip: 'Privacy Policy',
splashRadius: 24, splashRadius: 24,
@@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/screens/settings/settings_screen.dart';
// ── lib/components/sidebar_contents/settings.dart ────────────────────────────
// Thin sidebar row — taps navigate to the full SettingsScreen.
// The actual settings UI lives in lib/screens/settings/ (separate folder,
// one file per feature).
class SettingsButton extends StatelessWidget {
const SettingsButton({super.key});
// Opens the settings page sliding in from the right — matches the
// sidebar end-drawer animation so it feels like one continuous motion.
static PageRoute<void> _route() => PageRouteBuilder<void>(
transitionDuration: const Duration(milliseconds: 300),
reverseTransitionDuration: const Duration(milliseconds: 250),
pageBuilder: (_, __, ___) => const SettingsScreen(),
transitionsBuilder: (_, animation, __, child) {
return SlideTransition(
position: Tween<Offset>(
begin: const Offset(1.0, 0.0),
end: Offset.zero,
).animate(
CurvedAnimation(parent: animation, curve: Curves.easeOut),
),
child: child,
);
},
);
static void openWithNavigator(NavigatorState navigator) {
if (!navigator.mounted) return;
navigator.push(_route());
}
static void open(BuildContext context) {
openWithNavigator(Navigator.of(context, rootNavigator: true));
}
@override
Widget build(BuildContext context) {
return IconButton(
icon: const Icon(Icons.settings, color: AppColors.textWhite, size: 28),
onPressed: () => open(context),
tooltip: 'Settings',
splashRadius: 24,
);
}
}
@@ -0,0 +1,24 @@
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:revoltvpn/logic/app_colors.dart';
class WebsiteButton extends StatelessWidget {
const WebsiteButton({super.key});
static Future<void> launchWebsite() async {
final Uri url = Uri.parse('https://userevolt.app');
if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
debugPrint('Could not launch $url');
}
}
@override
Widget build(BuildContext context) {
return const IconButton(
icon: Icon(Icons.language, color: AppColors.textWhite, size: 28),
onPressed: launchWebsite,
tooltip: 'Website',
splashRadius: 24,
);
}
}
+70 -5
View File
@@ -1,13 +1,43 @@
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:revoltvpn/logic/app_colors.dart'; import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/components/sidebar_contents/gdpr_button.dart'; import 'package:revoltvpn/components/sidebar_contents/gdpr_button.dart';
import 'package:revoltvpn/components/sidebar_contents/privacy_policy_button.dart'; import 'package:revoltvpn/components/sidebar_contents/privacy_policy_button.dart';
import 'package:revoltvpn/components/sidebar_contents/info_button.dart'; import 'package:revoltvpn/components/sidebar_contents/info_button.dart';
import 'package:revoltvpn/components/sidebar_contents/discord_link_button.dart'; import 'package:revoltvpn/components/sidebar_contents/discord_link_button.dart';
import 'package:revoltvpn/components/sidebar_contents/website_button.dart';
import 'package:revoltvpn/components/sidebar_contents/settings.dart';
import 'package:revoltvpn/logic/updater.dart';
class SidebarDrawer extends StatelessWidget { class SidebarDrawer extends StatefulWidget {
const SidebarDrawer({super.key}); const SidebarDrawer({super.key});
@override
State<SidebarDrawer> createState() => _SidebarDrawerState();
}
class _SidebarDrawerState extends State<SidebarDrawer> {
String _version = '';
@override
void initState() {
super.initState();
_loadVersion();
}
Future<void> _loadVersion() async {
try {
final info = await PackageInfo.fromPlatform();
debugPrint('[Sidebar] PackageInfo version: ${info.version} '
'(build: ${info.buildNumber})');
if (mounted) setState(() => _version = info.version);
} catch (e) {
debugPrint('[Sidebar] PackageInfo failed: $e');
if (mounted) setState(() => _version = '?.?.?');
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Drawer( return Drawer(
@@ -84,12 +114,47 @@ class SidebarDrawer extends StatelessWidget {
}, },
), ),
_Row(
icon: Icons.language,
label: 'Website',
onTap: () {
Navigator.of(context).pop();
WebsiteButton.launchWebsite();
},
),
_Row(
icon: Icons.settings,
label: 'Settings',
onTap: () {
final navigator = Navigator.of(context, rootNavigator: true);
Navigator.of(context).pop();
SettingsButton.openWithNavigator(navigator);
},
),
_Row(
icon: Icons.system_update_alt,
label: 'Check for updates',
onTap: () {
final navigator = Navigator.of(context, rootNavigator: true);
final messenger = ScaffoldMessenger.of(context);
Navigator.of(context).pop();
unawaited(
Updater.checkWithHandles(
navigator: navigator,
messenger: messenger,
),
);
},
),
const Spacer(), const Spacer(),
const Padding( Padding(
padding: EdgeInsets.all(20), padding: const EdgeInsets.all(20),
child: Text('ReVoltVPN · v1.0.6', textAlign: TextAlign.center, child: Text('ReVoltVPN · v$_version', textAlign: TextAlign.center,
style: TextStyle(color: AppColors.slate, fontSize: 11, letterSpacing: 1), style: const TextStyle(color: AppColors.slate, fontSize: 11, letterSpacing: 1),
), ),
), ),
], ],
+5 -4
View File
@@ -8,10 +8,11 @@ class SpeedBox extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Consumer<SessionTimer>( return Selector<SessionTimer, double>(
builder: (context, timer, _) { selector: (_, timer) => timer.currentSpeedKBps,
final speed = timer.currentSpeedKBps > 0.5 builder: (context, speedKBps, _) {
? '${timer.currentSpeedKBps.toStringAsFixed(1)} KB/s' final speed = speedKBps > 0.5
? '${speedKBps.toStringAsFixed(1)} KB/s'
: 'Idle'; : 'Idle';
return Container( return Container(
+119 -31
View File
@@ -1,9 +1,44 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
import 'package:revoltvpn/logic/session_timer.dart';
import 'package:revoltvpn/components/online_dot.dart'; import 'package:revoltvpn/components/online_dot.dart';
import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/logic/session_timer.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
// The one line worth showing right now, and whether it is a problem.
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);
}
// 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',
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 { class StatusBar extends StatelessWidget {
const StatusBar({super.key}); const StatusBar({super.key});
@@ -14,11 +49,25 @@ class StatusBar extends StatelessWidget {
builder: (context, vpn, timer, _) { builder: (context, vpn, timer, _) {
final isConnected = vpn.status == VpnStatus.connected; final isConnected = vpn.status == VpnStatus.connected;
final isConnecting = vpn.status == VpnStatus.connecting; final isConnecting = vpn.status == VpnStatus.connecting;
final serverHealthy = vpn.serverReachable || (isConnected && timer.hasSyncedOnce); // Rule 60: reachability is known only from a session sync that
// succeeded, never from a probe. While disconnected the app knows
// nothing about the server, so it claims nothing either way.
final serverHealthy = isConnected && timer.hasSyncedOnce;
return Container( final statusLabel = isConnected
margin: const EdgeInsets.symmetric(horizontal: 24), ? (timer.hasSyncedOnce ? 'Online' : 'Syncing…')
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12), : (isConnecting ? 'Connecting…' : 'Ready');
final detail = _detail(vpn, timer);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding:
const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
decoration: BoxDecoration( decoration: BoxDecoration(
color: AppColors.bgCard, color: AppColors.bgCard,
borderRadius: BorderRadius.circular(16), borderRadius: BorderRadius.circular(16),
@@ -26,38 +75,77 @@ class StatusBar extends StatelessWidget {
), ),
child: Row( child: Row(
children: [ children: [
// ── Connection status (left) ───────────────────────────── Image.asset(
if (isConnected) ...[ 'assets/finland_flag_256.png',
Image.asset('assets/finland_flag_256.png', width: 20, height: 20), width: 20,
const SizedBox(width: 8), height: 20,
const Text('Helsinki, Finland', style: TextStyle(
color: AppColors.accent, fontWeight: FontWeight.w600,
fontSize: 13, letterSpacing: 0.5,
)),
] else ...[
Icon(
isConnecting ? Icons.sync : Icons.shield_outlined,
size: 18,
color: isConnecting ? AppColors.accent : AppColors.slate70,
), ),
const SizedBox(width: 8), const SizedBox(width: 8),
Text( const Expanded(
vpn.statusMessage.toUpperCase(), child: Text(
'Helsinki, Finland',
style: TextStyle( style: TextStyle(
color: isConnecting ? AppColors.accent : AppColors.slate70, color: AppColors.accent,
fontWeight: FontWeight.w600, fontSize: 13, letterSpacing: 1, fontWeight: FontWeight.w600,
fontSize: 13,
letterSpacing: 0.5,
),
), ),
), ),
], ],
),
const Spacer(), ),
const SizedBox(height: 8),
// ── Server health dot (right) ──────────────────────────── Container(
padding:
const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(
color: AppColors.bgCard,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: AppColors.slate15),
),
child: Row(
children: [
OnlineDot( OnlineDot(
isOnline: serverHealthy, isOnline: serverHealthy,
label: isConnected label: statusLabel,
? (timer.hasSyncedOnce ? 'Online' : 'Syncing…') ),
: (vpn.serverReachable ? 'Ready' : 'Offline'), const Spacer(),
if (vpn.networkTransport != 'unknown' &&
vpn.networkTransport != 'none')
Padding(
padding: const EdgeInsets.only(right: 8),
child: Text(
vpn.networkTransport,
style: const TextStyle(
color: AppColors.textDim,
fontSize: 11,
),
),
),
if (isConnected)
const Icon(
Icons.lock,
color: AppColors.green50,
size: 14,
),
],
),
),
// Errors and session-end reasons used to render nowhere.
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,
),
),
), ),
], ],
), ),
+32 -8
View File
@@ -20,13 +20,22 @@ class _SupportButtonState extends State<SupportButton> {
final ad = context.read<AdManager>(); final ad = context.read<AdManager>();
final timer = context.read<SessionTimer>(); final timer = context.read<SessionTimer>();
// Only available when there's an active session. // Only available when there's an active session, once the persisted
if (!timer.isRunning && !timer.hasSyncedOnce) return; // support state is known, and only once per client-side VPN session.
if ((!timer.isRunning && !timer.hasSyncedOnce) ||
!timer.supportRewardStateLoaded ||
timer.supportRewardClaimed) {
return;
}
setState(() => _busy = true); setState(() => _busy = true);
try { try {
await ad.showAd('support'); final rewarded = await ad.showAd('support') != null;
if (rewarded) {
await timer.markSupportRewardClaimed();
await timer.syncNow();
}
} finally { } finally {
if (mounted) setState(() => _busy = false); if (mounted) setState(() => _busy = false);
} }
@@ -40,8 +49,14 @@ class _SupportButtonState extends State<SupportButton> {
return const SizedBox.shrink(); return const SizedBox.shrink();
} }
final stateLoaded = timer.supportRewardStateLoaded;
final claimed = timer.supportRewardClaimed;
final disabled = !stateLoaded || claimed;
return GestureDetector( return GestureDetector(
onTap: _handleTap, onTap: disabled ? null : _handleTap,
child: Opacity(
opacity: disabled ? 0.55 : 1.0,
child: Container( child: Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -55,7 +70,11 @@ class _SupportButtonState extends State<SupportButton> {
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
const Icon(Icons.favorite_border, color: AppColors.accent, size: 20), Icon(
claimed ? Icons.check_circle_outline : Icons.favorite_border,
color: AppColors.accent,
size: 20,
),
const SizedBox(width: 8), const SizedBox(width: 8),
_busy _busy
? const SizedBox( ? const SizedBox(
@@ -66,9 +85,13 @@ class _SupportButtonState extends State<SupportButton> {
color: AppColors.accent, color: AppColors.accent,
), ),
) )
: const Text( : Text(
'Support us \u2014 30 min!', !stateLoaded
style: TextStyle( ? 'Checking support bonus…'
: claimed
? 'Support bonus used'
: 'Support us — 30 min!',
style: const TextStyle(
color: AppColors.textWhite, color: AppColors.textWhite,
fontSize: 14, fontSize: 14,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
@@ -77,6 +100,7 @@ class _SupportButtonState extends State<SupportButton> {
], ],
), ),
), ),
),
); );
}, },
); );
+8 -4
View File
@@ -19,17 +19,21 @@ class TimerBox extends StatelessWidget {
), ),
child: Text( child: Text(
timer.hasSyncedOnce ? timer.formatted : '00:00:00', timer.hasSyncedOnce ? timer.formatted : '00:00:00',
style: const TextStyle( style: TextStyle(
fontSize: 32, fontSize: 32,
fontWeight: FontWeight.w700, fontWeight: FontWeight.w700,
color: AppColors.textWhite, color: timer.hasSyncedOnce
? AppColors.textWhite
: AppColors.slate70,
letterSpacing: 2, letterSpacing: 2,
shadows: [ shadows: timer.hasSyncedOnce
? const [
Shadow( Shadow(
color: AppColors.accent50, color: AppColors.accent50,
blurRadius: 16, blurRadius: 16,
), ),
], ]
: [],
), ),
), ),
); );
+56 -33
View File
@@ -1,18 +1,13 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:math';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:revoltvpn/logic/crypto_service.dart'; import 'package:revoltvpn/logic/crypto_service.dart';
import 'package:revoltvpn/logic/hivemind_service.dart'; import 'package:revoltvpn/logic/hivemind_service.dart';
import 'package:revoltvpn/logic/app_config.dart'; import 'package:revoltvpn/logic/app_config.dart';
import 'package:revoltvpn/logic/consent_manager.dart';
/// AdManager manages the lifecycle of rewarded video ads.
///
/// When [adsEnabled] is false (pre-launch mode) all ad operations are
/// silently skipped — the app connects without any ad requirement.
class AdManager extends ChangeNotifier { class AdManager extends ChangeNotifier {
/// Flip to `true` after Google Play launch when real ads are wired up.
static const bool adsEnabled = false; static const bool adsEnabled = false;
RewardedAd? _rewardedAd; RewardedAd? _rewardedAd;
@@ -32,15 +27,30 @@ class AdManager extends ChangeNotifier {
if (adsEnabled) preloadAd(); if (adsEnabled) preloadAd();
} }
/// Loads a rewarded ad in the background and returns a Future when ready. static Future<void>? _sdkInit;
/// Safe to call multiple times — re-entrant calls wait on the same load. static Future<void> ensureSdkInitialized() {
/// No-op when [adsEnabled] is false. if (!adsEnabled) return Future.value();
return _sdkInit ??= _initSdk();
}
static Future<void> _initSdk() async {
try {
await ConsentManager.requestConsentIfNeeded()
.timeout(const Duration(seconds: 5));
} catch (e) {
debugPrint('[AdManager] Consent init skipped: $e');
}
try {
await MobileAds.instance.initialize().timeout(const Duration(seconds: 5));
} catch (e) {
debugPrint('[AdManager] MobileAds init skipped: $e');
}
}
Future<bool> preloadAd() async { Future<bool> preloadAd() async {
if (!adsEnabled) return true; if (!adsEnabled) return true;
// If already loaded, return instantly await ensureSdkInitialized();
if (_isAdLoaded) return true; if (_isAdLoaded) return true;
// If we're already loading one right now, wait for that same request to finish
if (_isAdLoading) return _loadCompleter?.future ?? Future.value(false); if (_isAdLoading) return _loadCompleter?.future ?? Future.value(false);
_isAdLoading = true; _isAdLoading = true;
@@ -84,30 +94,48 @@ class AdManager extends ChangeNotifier {
return _loadCompleter!.future; return _loadCompleter!.future;
} }
/// Displays the rewarded video ad to the user. // ── Show ad (or debug bypass) ─────────────────────────────────────
/// Returns false immediately when [adsEnabled] is false.
Future<bool> showAd(String adType) async { // Returns the nonce put in the SSV custom_data, null if unrewarded. connect()
if (!adsEnabled) return false; // must reuse it: minting a second nonce there rejects the ad's own session.
Future<String?> showAd(String adType) async {
if (!adsEnabled) {
// Main connect fires its own bypass in fetchConfigDirectly (rule 87).
if (adType != 'support' || !kDebugMode) return null;
// Needs ADMOB_BYPASS=True server-side.
final deviceId = await CryptoService.getDeviceId();
final nonce = HivemindService.newNonce();
try {
final customData = jsonEncode({
'device_id': deviceId,
'ad_type': adType,
'nonce': nonce,
});
final fakeUrl = Uri.parse(
'${AppConfig.hivemindApiPublic}/admob/callback'
'?signature=test&key_id=test'
'&custom_data=${Uri.encodeComponent(customData)}');
await HivemindService.directGet(fakeUrl, timeout: const Duration(seconds: 8));
return nonce;
} catch (_) {
return null;
}
}
await ensureSdkInitialized();
// 1. Ensure the ad is fully loaded before trying to show it
if (!_isAdLoaded || _rewardedAd == null) { if (!_isAdLoaded || _rewardedAd == null) {
final loaded = await preloadAd(); final loaded = await preloadAd();
if (!loaded || _rewardedAd == null) { if (!loaded || _rewardedAd == null) {
debugPrint('[AdManager] Cannot show ad, failed to load.'); debugPrint('[AdManager] Cannot show ad, failed to load.');
return false; return null;
} }
} }
// 2. Fetch device ID for Server-Side Verification (SSV)
final deviceId = await CryptoService.getDeviceId(); final deviceId = await CryptoService.getDeviceId();
final nonce = HivemindService.newNonce();
// 3. Generate a connect nonce so the subsequent poll can verify
// it's talking to the session created by *this* ad.
final nonce = '${Random().nextInt(0x7FFFFFFF)}-${DateTime.now().millisecondsSinceEpoch}';
HivemindService.setExpectedNonce(nonce);
debugPrint('[AdManager] Ad nonce: $nonce');
// 4. Build SSV options to send to our Hivemind server via Google's callback
final ssvOptions = ServerSideVerificationOptions( final ssvOptions = ServerSideVerificationOptions(
customData: jsonEncode({ customData: jsonEncode({
'device_id': deviceId, 'device_id': deviceId,
@@ -118,7 +146,6 @@ class AdManager extends ChangeNotifier {
Completer<bool> rewardCompleter = Completer<bool>(); Completer<bool> rewardCompleter = Completer<bool>();
// 4. Setup full screen callbacks to handle dismissal and errors
_rewardedAd!.fullScreenContentCallback = FullScreenContentCallback( _rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
onAdShowedFullScreenContent: (ad) => debugPrint('[AdManager] Ad showing.'), onAdShowedFullScreenContent: (ad) => debugPrint('[AdManager] Ad showing.'),
onAdDismissedFullScreenContent: (ad) { onAdDismissedFullScreenContent: (ad) {
@@ -126,10 +153,9 @@ class AdManager extends ChangeNotifier {
ad.dispose(); ad.dispose();
_isAdLoaded = false; _isAdLoaded = false;
_rewardedAd = null; _rewardedAd = null;
// Start loading the next ad immediately
preloadAd(); preloadAd();
if (!rewardCompleter.isCompleted) { if (!rewardCompleter.isCompleted) {
rewardCompleter.complete(false); // User closed before earning reward rewardCompleter.complete(false);
} }
}, },
onAdFailedToShowFullScreenContent: (ad, error) { onAdFailedToShowFullScreenContent: (ad, error) {
@@ -143,20 +169,17 @@ class AdManager extends ChangeNotifier {
}, },
); );
// 5. Show the ad with SSV options
_rewardedAd!.setServerSideOptions(ssvOptions); _rewardedAd!.setServerSideOptions(ssvOptions);
await _rewardedAd!.show( await _rewardedAd!.show(
onUserEarnedReward: (AdWithoutView ad, RewardItem reward) { onUserEarnedReward: (AdWithoutView ad, RewardItem reward) {
debugPrint('[AdManager] Reward earned: ${reward.amount} ${reward.type}'); debugPrint('[AdManager] Reward earned: ${reward.amount} ${reward.type}');
// The SSV callback will hit our server independently. We just need to signal the UI
// that the ad was successfully completed.
if (!rewardCompleter.isCompleted) { if (!rewardCompleter.isCompleted) {
rewardCompleter.complete(true); rewardCompleter.complete(true);
} }
}, },
); );
return rewardCompleter.future; return await rewardCompleter.future ? nonce : null;
} }
@override @override
+25 -17
View File
@@ -1,31 +1,39 @@
// ============================================================================= // =============================================================================
// app_config.example.dart — TEMPLATE FOR SERVER SETTINGS // app_config.example.dart — TEMPLATE FOR SERVER SETTINGS
// ───────────────────────────────────────────────────────────────────────────── // ─────────────────────────────────────────────────────────────────────────────
// Rename this file to `app_config.dart` and fill in your real values.
// Do not commit your real `app_config.dart` to GitHub!
//
// Most Reality tunnel fields (vless_ip, vless_port, reality_pbk, reality_sid,
// reality_sni, reality_fp) come from the server's /session/status response.
// The constants below are fallbacks — the server is the source of truth.
// =============================================================================
abstract final class AppConfig { abstract final class AppConfig {
AppConfig._(); AppConfig._(); // static members only
// ── Server (API) ────────────────────────────────────────────────────── // ── Server ───────────────────────────────────────────────────────────
static const String serverDomain = 'yourdomain.com'; // ◄── REPLACE /// Your server's public IP. The VPN tunnel is pinned to this.
static const String serverIp = '0.0.0.0'; // ◄── REPLACE
static String get hivemindApiBase => 'https://$serverDomain/api'; static const String hivemindApiPublic = 'https://YOUR_DOMAIN/api'; // ◄── REPLACE
// ── Reality (VPN tunnel) ────────────────────────────────────────────── // ── Reality (VPN tunnel) ──────────────────────────────────────────────
// These are fallbacks — normally overridden by /session/status response. // Credentials (public key, shortId) come from /session/status, not from
static const String realitySni = 'www.microsoft.com'; // here. Only the transport parameters below are compiled in.
/// The server picks a random SNI per session from REALITY_SNI_POOL.
/// The client does NOT hardcode one — server is always the source of truth.
/// TLS fingerprint: chrome | firefox | safari | random
static const String realityFp = 'chrome'; static const String realityFp = 'chrome';
// These are authoritative — never sent by the server. // These are normally overridden by /session/status response fields.
static const String vlessSecurity = 'reality'; static const String vlessSecurity = 'reality';
static const String vlessType = 'tcp'; static const String vlessType = 'xhttp';
static const String vlessFlow = 'xtls-rprx-vision';
/// XHTTP path — must match xray_config_reality.json xhttpSettings.path.
static const String vlessPath = '/revolt';
// ── Updates ────────────────────────────────────────────────────────────
/// Used by the updater.
static const String applicationId = 'com.paladinvpn.app'; // ◄── REPLACE
static const String githubOwner = 'YOUR_GITHUB_USERNAME'; // ◄── REPLACE (current: 'esefxdz')
static const String githubRepo = 'YOUR_REPO_NAME'; // ◄── REPLACE (current: 'ReVoltVPN')
/// Fallback URL if the GitHub API call fails.
static const String githubReleasesUrl = 'https://github.com/$githubOwner/$githubRepo/releases/latest';
// ── AdMob ────────────────────────────────────────────────────────────── // ── AdMob ──────────────────────────────────────────────────────────────
static const String adUnitId = 'ca-app-pub-0000000000000000/0000000000'; // REPLACE static const String adUnitId = 'ca-app-pub-0000000000000000/0000000000'; // REPLACE
+55
View File
@@ -0,0 +1,55 @@
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
enum ConnectionMode { tun, proxy }
abstract final class ConnectionSettings {
ConnectionSettings._();
static const String _modeKey = 'connection_mode';
static ConnectionMode _mode = ConnectionMode.tun;
static bool _initialized = false;
static ConnectionMode get mode => _mode;
static Future<void> initialize() async {
if (_initialized) return;
final prefs = await SharedPreferences.getInstance();
final storedMode = prefs.getString(_modeKey);
// Only the explicit current proxy value restores SOCKS5. Unknown and
// obsolete values, including the pre-V3 'auto' label, fail closed to
// full-tunnel TUN instead of silently selecting a weaker route.
_mode = storedMode == ConnectionMode.proxy.name
? ConnectionMode.proxy
: ConnectionMode.tun;
if (storedMode != _mode.name) {
// Best-effort. _mode is already the safe TUN default in memory, so a
// failed write leaves nothing insecure — it only means the migration
// is retried next launch. initialize() runs from main() before
// runApp(), with no zone guard, so throwing here would black-screen
// the app on the fresh-install path for no security gain.
final migrated = await prefs.setString(_modeKey, _mode.name);
if (!migrated) {
debugPrint('[ConnectionSettings] Could not persist migrated mode.');
}
}
_initialized = true;
}
static Future<bool> setMode(ConnectionMode mode) async {
if (_initialized && _mode == mode) return true;
final prefs = await SharedPreferences.getInstance();
final saved = await prefs.setString(_modeKey, mode.name);
if (!saved) return false;
_mode = mode;
_initialized = true;
return true;
}
}
+7 -1
View File
@@ -4,11 +4,17 @@ import 'package:uuid/uuid.dart';
class CryptoService { class CryptoService {
static const String _deviceIdPref = 'device_uuid'; static const String _deviceIdPref = 'device_uuid';
static const _storage = FlutterSecureStorage(); static const _storage = FlutterSecureStorage();
static final RegExp _uuidV4 = RegExp(
r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$',
caseSensitive: false,
);
/// Get or create a persistent device UUID for server-side session tracking. /// Get or create a persistent device UUID for server-side session tracking.
/// Corrupted or tampered storage values are replaced instead of being sent
/// to the public API as arbitrary query data.
static Future<String> getDeviceId() async { static Future<String> getDeviceId() async {
final existing = await _storage.read(key: _deviceIdPref); final existing = await _storage.read(key: _deviceIdPref);
if (existing != null) return existing; if (existing != null && _uuidV4.hasMatch(existing)) return existing;
final newId = const Uuid().v4(); final newId = const Uuid().v4();
await _storage.write(key: _deviceIdPref, value: newId); await _storage.write(key: _deviceIdPref, value: newId);
+72
View File
@@ -0,0 +1,72 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
abstract final class HapticSettings {
HapticSettings._();
static const String _prefKey = 'haptic_feedback_enabled';
static const MethodChannel _channel =
MethodChannel('com.revoltvpn.app/haptics');
static bool _enabled = false;
static bool _initialized = false;
static bool get enabled => _enabled;
static Future<void> initialize() async {
if (_initialized) return;
try {
final prefs = await SharedPreferences.getInstance();
_enabled = prefs.getBool(_prefKey) ?? false;
} catch (e) {
debugPrint('[Haptics] Failed to load preference: $e');
_enabled = false;
} finally {
_initialized = true;
}
}
static Future<void> setEnabled(bool value) async {
final previous = _enabled;
_enabled = value;
_initialized = true;
try {
final prefs = await SharedPreferences.getInstance();
final saved = await prefs.setBool(_prefKey, value);
if (!saved) throw StateError('Could not save haptic setting');
} catch (e) {
_enabled = previous;
debugPrint('[Haptics] Failed to save preference: $e');
rethrow;
}
}
/// Confirmation haptic for a successful connect/disconnect. Best-effort: a
/// vibration failure must never block or fail the VPN action.
static void success() => unawaited(_impact());
static Future<void> _impact() async {
if (!_initialized) await initialize();
if (!_enabled || kIsWeb) return;
if (defaultTargetPlatform == TargetPlatform.android) {
try {
final handled = await _channel.invokeMethod<bool>(
'impact',
<String, Object>{'kind': 'success'},
) ??
false;
if (handled) return;
} catch (e) {
debugPrint('[Haptics] Native vibration unavailable: $e');
}
}
await HapticFeedback.mediumImpact();
}
}
+414 -92
View File
@@ -1,6 +1,7 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:math'; import 'dart:math';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'package:revoltvpn/logic/app_config.dart'; import 'package:revoltvpn/logic/app_config.dart';
@@ -10,122 +11,443 @@ class HivemindService {
static String? _expectedNonce; static String? _expectedNonce;
static int _currentCallId = 0; static int _currentCallId = 0;
/// Call this from disconnect to abort any in-progress polling. static const _ua = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 '
static void cancel() { '(KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36';
_currentCallId++; // bump — any running loop sees a stale ID and exits static const int _maxControlResponseBytes = 256 * 1024;
static const _pollBackoff = <Duration>[
Duration(seconds: 1),
Duration(seconds: 2),
Duration(seconds: 3),
Duration(seconds: 5),
];
static Future<http.Response> directGet(
Uri uri, {
Duration timeout = const Duration(seconds: 5),
}) {
return controlGet(uri, timeout: timeout);
} }
static void setExpectedNonce(String nonce) { static Future<http.Response> controlGet(
_expectedNonce = nonce; Uri uri, {
} Duration timeout = const Duration(seconds: 5),
/// Tries to fetch the VLESS config from the server.
/// Only polls a few times — by the time the ad finishes, the SSV callback
/// has usually already fired.
static Future<String> fetchConfigWithPolling({
void Function(int attempt, int total)? onAttempt,
bool skipAdBypass = false,
bool quickReconnect = false,
}) async { }) async {
final client = http.Client();
final request = http.Request('GET', uri)
..headers['User-Agent'] = _ua
..followRedirects = false;
Future<http.Response> read() 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 = <int>[];
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,
isRedirect: streamed.isRedirect,
persistentConnection: streamed.persistentConnection,
reasonPhrase: streamed.reasonPhrase,
request: request,
);
}
try {
return await read().timeout(
timeout,
onTimeout: () {
client.close();
throw TimeoutException('Control request timed out.', timeout);
},
);
} finally {
client.close();
}
}
static Future<http.Response> controlPost(
Uri uri,
Map<String, dynamic> 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<http.Response> 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 = <int>[];
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<void> releaseSession() async {
try {
final deviceId = await CryptoService.getDeviceId(); final deviceId = await CryptoService.getDeviceId();
await controlPost(
final callId = ++_currentCallId; _publicUrl('/session/stop'),
final nonce = '${Random().nextInt(0x7FFFFFFF)}-${DateTime.now().millisecondsSinceEpoch}'; {'device_id': deviceId},
_expectedNonce = nonce; timeout: const Duration(seconds: 3),
debugPrint('[HivemindService] Call #$callId — nonce: $nonce'); );
} catch (_) {
final url = Uri.parse('${AppConfig.hivemindApiBase}/session/status?device_id=$deviceId'); // Nothing to recover: the server expires the session anyway.
}
// ── AD BYPASS (debug only) ────────────────────────────────────────
if (kDebugMode && !skipAdBypass) {
try {
final customData = jsonEncode({'device_id': deviceId, 'nonce': nonce});
final fakeUrl = Uri.parse(
'${AppConfig.hivemindApiBase}/admob/callback?signature=test&key_id=test&custom_data=${Uri.encodeComponent(customData)}');
await http.get(fakeUrl).timeout(const Duration(seconds: 8));
} catch (_) {}
} }
final maxAttempts = quickReconnect ? 1 : 5; static void cancel() {
for (int i = 1; i <= maxAttempts; i++) { _currentCallId++;
if (_currentCallId != callId) throw Exception('Cancelled');
onAttempt?.call(i, maxAttempts);
try {
final response = await http.get(url).timeout(const Duration(seconds: 5));
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final serverNonce = data['nonce'] as String?;
if (_expectedNonce != null && serverNonce != null && serverNonce != _expectedNonce) {
debugPrint('[HivemindService] Nonce mismatch — retrying…');
} else if (data['active'] == true && data['vless_uuid'] != null) {
final vlessUuid = data['vless_uuid'];
// Reality tunnel fields — server is source of truth, AppConfig is fallback.
final vlessIp = data['vless_ip'] ?? AppConfig.serverDomain;
final vlessPort = data['vless_port'] ?? 8443;
final pbk = data['reality_pbk'] ?? '';
final sid = data['reality_sid'] ?? '';
final sni = data['reality_sni'] ?? AppConfig.realitySni;
final fp = data['reality_fp'] ?? AppConfig.realityFp;
final vlessUrl = 'vless://$vlessUuid@$vlessIp:$vlessPort'
'?security=${AppConfig.vlessSecurity}'
'&type=${AppConfig.vlessType}'
'&flow=${AppConfig.vlessFlow}'
'&pbk=${Uri.encodeComponent(pbk)}'
'&sni=${Uri.encodeComponent(sni)}'
'&sid=${Uri.encodeComponent(sid)}'
'&fp=${Uri.encodeComponent(fp)}'
'#ReVoltVPN';
_expectedNonce = null; _expectedNonce = null;
return vlessUrl;
} }
// Fetches this device's VLESS URL. Every session starts the same way, so
// there is always a nonce to bind it to: either the one the ad minted, or one
// we mint here before firing the bypass (rule 87). The re-attach path that
// used to accept any nonce is gone - see rule 4.
static Future<String> fetchConfigDirectly({
void Function(int attempt, int total)? onAttempt,
String? adNonce,
}) async {
// Capture the generation before the first await. Otherwise a disconnect
// that lands while secure storage is resolving the device ID can be lost
// and the cancelled call can resume network work with a fresh generation.
final callId = ++_currentCallId;
final deviceId = await CryptoService.getDeviceId();
_throwIfCancelled(callId);
final nonce = adNonce ?? newNonce();
_expectedNonce = nonce;
if (adNonce == null) {
await _runConfiguredBypass(deviceId, nonce);
_throwIfCancelled(callId);
}
final maxAttempts = adNonce != null ? 10 : 5;
for (var attempt = 1; attempt <= maxAttempts; attempt++) {
_throwIfCancelled(callId);
onAttempt?.call(attempt, maxAttempts);
try {
final session = await _fetchActiveSession(deviceId, nonce);
_throwIfCancelled(callId);
if (session != null) {
_expectedNonce = null;
return session.toVlessUrl();
} }
} catch (e) { } catch (e) {
if (e.toString().contains('Cancelled')) rethrow; if (_isCancelledError(e)) rethrow;
debugPrint('[HivemindService] Attempt $i failed: $e'); debugPrint('[Hivemind] session attempt $attempt failed');
} }
if (i < maxAttempts) await Future.delayed(const Duration(seconds: 1)); if (attempt < maxAttempts) {
await Future.delayed(
_pollBackoff[min(attempt - 1, _pollBackoff.length - 1)],
);
_throwIfCancelled(callId);
}
} }
throw Exception('Session not activated. Server callback may have timed out.'); throw Exception('Session not activated. Server callback may have timed out.');
} }
static Future<bool> checkHealth() async { static String newNonce() {
final random = Random.secure();
final high = random.nextInt(0x7FFFFFFF);
final low = random.nextInt(0x7FFFFFFF);
return '$high-$low-${DateTime.now().microsecondsSinceEpoch}';
}
static Future<void> _runConfiguredBypass(String deviceId, String nonce) async {
try { try {
final url = Uri.parse('${AppConfig.hivemindApiBase}/health'); final customData = jsonEncode({'device_id': deviceId, 'nonce': nonce});
final response = await http.get(url).timeout(const Duration(seconds: 3)); final callback = _publicUrl(
return response.statusCode == 200; '/admob/callback?signature=test&key_id=test&custom_data=${Uri.encodeComponent(customData)}',
);
await directGet(callback, timeout: const Duration(seconds: 8));
} catch (_) { } catch (_) {
return false; // Validation bypass behavior is intentionally best-effort in this build.
} }
} }
static Future<bool> verifySession() async { static Future<_HivemindSessionConfig?> _fetchActiveSession(
try { String deviceId,
final deviceId = await CryptoService.getDeviceId(); String nonce,
final url = Uri.parse('${AppConfig.hivemindApiBase}/session/status?device_id=$deviceId'); ) async {
final response = await http.get(url).timeout(const Duration(seconds: 5)); final statusUri = _publicUrl('/session/status').replace(
if (response.statusCode == 200) { queryParameters: {'device_id': deviceId},
final data = jsonDecode(response.body); );
return data['active'] == true; final response = await controlGet(statusUri);
} if (response.statusCode != 200) return null;
} catch (_) {}
return false; final decoded = jsonDecode(response.body);
if (decoded is! Map<String, dynamic>) return null;
final serverNonce = decoded['nonce'];
if (_expectedNonce != nonce) return null;
if (serverNonce is! String || serverNonce != nonce) return null;
if (decoded['active'] != true || decoded['vless_uuid'] == null) {
return null;
} }
static Future<void> disconnectAndCleanup() async { return _HivemindSessionConfig.fromJson(decoded);
final deviceId = await CryptoService.getDeviceId(); }
final url = Uri.parse('${AppConfig.hivemindApiBase}/session/stop');
static void _throwIfCancelled(int callId) {
if (_currentCallId != callId) throw Exception('Cancelled');
}
static bool _isCancelledError(Object error) =>
error.toString().contains('Cancelled');
static Uri _publicUrl(String path) =>
Uri.parse('${AppConfig.hivemindApiPublic}$path');
}
class _HivemindSessionConfig {
static final RegExp _uuidPattern = RegExp(
r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
caseSensitive: false,
);
static final RegExp _shortIdPattern =
RegExp(r'^[0-9a-f]{0,16}$', caseSensitive: false);
final String uuid;
final String host;
final int port;
final String publicKey;
final String shortId;
final String sni;
final String fingerprint;
final String path;
const _HivemindSessionConfig({
required this.uuid,
required this.host,
required this.port,
required this.publicKey,
required this.shortId,
required this.sni,
required this.fingerprint,
required this.path,
});
factory _HivemindSessionConfig.fromJson(Map<String, dynamic> json) {
final uuid = _requiredString(json, 'vless_uuid', maxLength: 64);
if (!_uuidPattern.hasMatch(uuid)) {
throw const FormatException('Invalid VLESS UUID');
}
// The API may rotate credentials and Reality parameters, but it must never
// choose the tunnel destination. Keep that trust anchor compiled into the
// app so an API/domain compromise can cause denial of service, not redirect
// VPN traffic to an attacker-controlled server.
final pinnedHost = _validatedPublicIp(AppConfig.serverIp, 'serverIp');
final advertisedHost = json['vless_ip'];
if (advertisedHost != null) {
if (advertisedHost is! String || advertisedHost.trim() != pinnedHost) {
throw const FormatException(
'Session VLESS host does not match compiled server pin',
);
}
}
final host = pinnedHost;
final advertisedPort = json['vless_port'];
if (advertisedPort != null &&
(advertisedPort is! num || advertisedPort.toInt() != 443)) {
throw const FormatException('Session VLESS port does not match compiled pin');
}
const port = 443;
final sni = _validatedHost(
_requiredString(json, 'reality_sni', maxLength: 253),
'reality_sni',
);
final publicKey = _requiredString(json, 'reality_pbk', maxLength: 128);
final shortId = _stringOr(json['reality_sid'], '').trim();
if (!_shortIdPattern.hasMatch(shortId)) {
throw const FormatException('Invalid Reality short ID');
}
final fingerprint =
_boundedString(json['reality_fp'], AppConfig.realityFp, 32, 'reality_fp');
final path =
_boundedString(json['xhttp_path'], AppConfig.vlessPath, 2048, 'xhttp_path');
if (!path.startsWith('/')) {
throw const FormatException('Invalid XHTTP path');
}
return _HivemindSessionConfig(
uuid: uuid,
host: host,
port: port,
publicKey: publicKey,
shortId: shortId,
sni: sni,
fingerprint: fingerprint,
path: path,
);
}
String toVlessUrl() {
return Uri(
scheme: 'vless',
userInfo: uuid,
host: host,
port: port,
queryParameters: <String, String>{
'security': AppConfig.vlessSecurity,
'type': AppConfig.vlessType,
'path': path,
'pbk': publicKey,
'sni': sni,
'sid': shortId,
'fp': fingerprint,
},
fragment: 'Revolt VPN',
).toString();
}
static String _requiredString(
Map<String, dynamic> json,
String key, {
int maxLength = 4096,
}) {
final value = json[key];
if (value is! String) {
throw FormatException('Missing required session field: $key');
}
final trimmed = value.trim();
if (trimmed.isEmpty || trimmed.length > maxLength) {
throw FormatException('Invalid session field: $key');
}
return trimmed;
}
static String _stringOr(Object? value, String fallback) {
return value is String && value.trim().isNotEmpty ? value.trim() : fallback;
}
static String _boundedString(
Object? value,
String fallback,
int maxLength,
String field,
) {
final result = _stringOr(value, fallback);
if (result.isEmpty || result.length > maxLength) {
throw FormatException('Invalid session field: $field');
}
return result;
}
static String _validatedHost(String input, String field) {
final value = input.trim();
if (value.isEmpty ||
value.length > 253 ||
value.contains(RegExp(r'[\s/@?#]'))) {
throw FormatException('Invalid session host: $field');
}
try { try {
await http.post( final probe = Uri(scheme: 'https', host: value);
url, if (probe.host.isEmpty) {
headers: {'Content-Type': 'application/json'}, throw FormatException('Invalid session host: $field');
body: jsonEncode({'device_id': deviceId}), }
).timeout(const Duration(seconds: 3)); } on FormatException {
} catch (_) {} throw FormatException('Invalid session host: $field');
}
return value;
}
static String _validatedPublicIp(String input, String field) {
final value = input.trim().toLowerCase();
if (_isPublicIpv4(value) || _isPublicIpv6(value)) return value;
throw FormatException('Invalid public IP pin: $field');
}
static bool _isPublicIpv4(String value) {
final parts = value.split('.');
if (parts.length != 4) return false;
final octets = <int>[];
for (final part in parts) {
if (part.isEmpty || (part.length > 1 && part.startsWith('0'))) return false;
final parsed = int.tryParse(part);
if (parsed == null || parsed < 0 || parsed > 255) return false;
octets.add(parsed);
}
final a = octets[0];
final b = octets[1];
if (a == 0 || a == 10 || a == 127 || a >= 224) return false;
if (a == 100 && b >= 64 && b <= 127) return false;
if (a == 169 && b == 254) return false;
if (a == 172 && b >= 16 && b <= 31) return false;
if (a == 192 && b == 168) return false;
if (a == 192 && b == 0 && octets[2] == 2) return false;
if (a == 198 && b == 51 && octets[2] == 100) return false;
if (a == 203 && b == 0 && octets[2] == 113) return false;
return true;
}
static bool _isPublicIpv6(String value) {
if (!value.contains(':') || value.contains('.')) return false;
try {
final parsed = Uri.parse('https://[$value]/');
if (parsed.host.isEmpty || !parsed.host.contains(':')) return false;
} on FormatException {
return false;
}
if (value == '::' || value == '::1') return false;
if (value.startsWith('fc') || value.startsWith('fd')) return false;
if (value.startsWith('fe8') || value.startsWith('fe9') || value.startsWith('fea') || value.startsWith('feb')) return false;
if (value.startsWith('ff')) return false;
if (value.startsWith('2001:db8:') || value == '2001:db8::') return false;
return true;
} }
} }
+342
View File
@@ -0,0 +1,342 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
class LocalSocksTestResult {
final bool ok;
final int? latencyMs;
final String message;
const LocalSocksTestResult({
required this.ok,
required this.latencyMs,
required this.message,
});
}
abstract final class LocalSocksTester {
LocalSocksTester._();
/// Fast local readiness probe used while starting the VPN.
///
/// This stops after authenticated SOCKS5 negotiation. Startup must not depend
/// on an unrelated external host being reachable.
static Future<LocalSocksTestResult> testListener({
String host = '127.0.0.1',
required int port,
required String username,
required String password,
}) async {
final stopwatch = Stopwatch()..start();
Socket? socket;
_SocketReader? reader;
try {
socket = await Socket.connect(
host,
port,
timeout: const Duration(seconds: 1),
);
socket.setOption(SocketOption.tcpNoDelay, true);
reader = _SocketReader(socket);
final authenticated = await _authenticate(
reader,
socket,
username: username,
password: password,
timeout: const Duration(seconds: 1),
);
if (!authenticated) {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'Local SOCKS5 listener rejected authentication.',
);
}
stopwatch.stop();
return LocalSocksTestResult(
ok: true,
latencyMs: stopwatch.elapsedMilliseconds,
message: 'Local SOCKS5 listener is ready.',
);
} on TimeoutException {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'Local SOCKS5 listener timed out.',
);
} on SocketException {
return LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'Local SOCKS5 is not listening on $host:$port.',
);
} catch (_) {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'Local SOCKS5 listener check failed.',
);
} finally {
await reader?.close();
await socket?.close();
}
}
/// Full user-facing test: authenticated local SOCKS handshake, an outbound
/// CONNECT through the active ReVolt route, and — critically — a real
/// request/response exchange over that CONNECT.
///
/// The exchange is not optional politeness. Xray answers a SOCKS CONNECT
/// before it dials upstream, so the reply code alone says nothing about the
/// outbound: it returns success for unroutable addresses and for hostnames
/// that can never resolve. Without a round trip this test reports OK while
/// the server is down, which is precisely when a user runs it.
static Future<LocalSocksTestResult> test({
String host = '127.0.0.1',
required int port,
required String username,
required String password,
String targetHost = 'example.com',
int targetPort = 80,
}) async {
const totalTimeout = Duration(seconds: 8);
final stopwatch = Stopwatch()..start();
Socket? socket;
_SocketReader? reader;
Duration remaining() {
final micros = totalTimeout.inMicroseconds - stopwatch.elapsedMicroseconds;
if (micros <= 0) throw TimeoutException('SOCKS5 test timed out.', totalTimeout);
return Duration(microseconds: micros);
}
try {
if (targetPort <= 0 || targetPort > 65535) {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'SOCKS5 test target is invalid.',
);
}
socket = await Socket.connect(
host,
port,
timeout: remaining(),
);
socket.setOption(SocketOption.tcpNoDelay, true);
reader = _SocketReader(socket);
final authenticated = await _authenticate(
reader,
socket,
username: username,
password: password,
timeout: remaining(),
);
if (!authenticated) {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'Local SOCKS5 listener rejected authentication.',
);
}
final hostBytes = utf8.encode(targetHost);
if (hostBytes.isEmpty || hostBytes.length > 255) {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'SOCKS5 test target is invalid.',
);
}
socket.add(<int>[
0x05,
0x01,
0x00,
0x03,
hostBytes.length,
...hostBytes,
(targetPort >> 8) & 0xff,
targetPort & 0xff,
]);
await socket.flush();
final replyHead = await reader.readExactly(4, timeout: remaining());
if (replyHead[0] != 0x05 || replyHead[1] != 0x00) {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message:
'SOCKS5 is listening, but the ReVolt route could not reach the test target.',
);
}
await _consumeAddress(reader, replyHead[3], timeout: remaining());
// The CONNECT reply above is not evidence of an outbound. Force a round
// trip and require the peer's answer before claiming the route works.
socket.add(
utf8.encode(
'GET / HTTP/1.1\r\nHost: $targetHost\r\nConnection: close\r\n\r\n',
),
);
await socket.flush();
List<int> banner;
try {
banner = await reader.readExactly(5, timeout: remaining());
} on TimeoutException {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'Local SOCKS5 is up, but the ReVolt outbound never replied.',
);
} on SocketException {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message:
'Local SOCKS5 is up, but the ReVolt outbound dropped the connection.',
);
}
if (String.fromCharCodes(banner) != 'HTTP/') {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message:
'Local SOCKS5 is up, but the ReVolt outbound returned unexpected data.',
);
}
stopwatch.stop();
return LocalSocksTestResult(
ok: true,
latencyMs: stopwatch.elapsedMilliseconds,
message: 'Local SOCKS5 and the ReVolt outbound are reachable.',
);
} on TimeoutException {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'Local SOCKS5 test timed out.',
);
} on SocketException {
return LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'Local SOCKS5 is not listening on $host:$port.',
);
} catch (_) {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'Local SOCKS5 test failed.',
);
} finally {
await reader?.close();
await socket?.close();
}
}
static Future<bool> _authenticate(
_SocketReader reader,
Socket socket, {
required String username,
required String password,
Duration timeout = const Duration(seconds: 4),
}) async {
final userBytes = utf8.encode(username);
final passBytes = utf8.encode(password);
if (userBytes.isEmpty ||
passBytes.isEmpty ||
userBytes.length > 255 ||
passBytes.length > 255) {
return false;
}
// ReVolt never accepts unauthenticated local SOCKS. Advertising only RFC
// 1929 username/password auth makes a future credential-plumbing regression
// fail closed instead of silently falling back to method 0x00.
socket.add(const <int>[0x05, 0x01, 0x02]);
await socket.flush();
final greeting = await reader.readExactly(2, timeout: timeout);
if (greeting[0] != 0x05 || greeting[1] != 0x02) return false;
socket.add(<int>[
0x01,
userBytes.length,
...userBytes,
passBytes.length,
...passBytes,
]);
await socket.flush();
final authReply = await reader.readExactly(2, timeout: timeout);
return authReply[0] == 0x01 && authReply[1] == 0x00;
}
static Future<void> _consumeAddress(
_SocketReader reader,
int addressType, {
required Duration timeout,
}) async {
if (addressType == 0x01) {
await reader.readExactly(4 + 2, timeout: timeout);
return;
}
if (addressType == 0x04) {
await reader.readExactly(16 + 2, timeout: timeout);
return;
}
if (addressType == 0x03) {
final length = (await reader.readExactly(1, timeout: timeout)).first;
if (length == 0) {
throw const FormatException('Invalid SOCKS5 domain length');
}
await reader.readExactly(length + 2, timeout: timeout);
return;
}
throw const FormatException('Unsupported SOCKS5 address type');
}
}
class _SocketReader {
final StreamIterator<Uint8List> _iterator;
final List<int> _buffer = <int>[];
_SocketReader(Socket socket) : _iterator = StreamIterator<Uint8List>(socket);
Future<List<int>> readExactly(
int count, {
Duration timeout = const Duration(seconds: 4),
}) async {
final elapsed = Stopwatch()..start();
while (_buffer.length < count) {
final remainingMicros = timeout.inMicroseconds - elapsed.elapsedMicroseconds;
if (remainingMicros <= 0) {
throw TimeoutException('Socket read timed out', timeout);
}
final hasNext = await _iterator.moveNext().timeout(
Duration(microseconds: remainingMicros),
);
if (!hasNext) {
throw const SocketException('Socket closed early');
}
_buffer.addAll(_iterator.current);
}
final result = _buffer.sublist(0, count);
_buffer.removeRange(0, count);
return result;
}
Future<void> close() => _iterator.cancel();
}
+42
View File
@@ -0,0 +1,42 @@
import 'package:flutter/services.dart';
class NetworkSnapshot {
final String reason;
final String transport;
final bool connected;
final bool validated;
final bool metered;
final int timestamp;
const NetworkSnapshot({
required this.reason,
required this.transport,
required this.connected,
required this.validated,
required this.metered,
required this.timestamp,
});
factory NetworkSnapshot.fromMap(Map<dynamic, dynamic> map) {
return NetworkSnapshot(
reason: map['reason'] as String? ?? 'changed',
transport: map['transport'] as String? ?? 'unknown',
connected: map['connected'] == true,
validated: map['validated'] == true,
metered: map['metered'] == true,
timestamp: (map['timestamp'] as num?)?.toInt() ?? 0,
);
}
}
abstract final class NetworkMonitor {
NetworkMonitor._();
static const EventChannel _channel = EventChannel('com.revoltvpn.app/network');
static Stream<NetworkSnapshot> get changes {
return _channel.receiveBroadcastStream().where((event) => event is Map).map(
(event) => NetworkSnapshot.fromMap(event as Map<dynamic, dynamic>),
);
}
}
+62
View File
@@ -0,0 +1,62 @@
import 'package:flutter/services.dart';
// ── lib/logic/notification_service.dart ─────────────────────────────────────
// Bridge to the native VPN notification, which flutter_vless owns. This only
// refreshes its content text with the session countdown, so a failure here is
// never worth propagating to the session timer.
class NotificationService {
NotificationService._();
static const MethodChannel _channel =
MethodChannel('com.revoltvpn.app/notification');
static String? _lastText;
/// Sets the notification's content text to [text].
///
/// The native side rebuilds the whole notification, so skip the round-trip
/// when the text has not changed. A failed native update is intentionally
/// not cached so the next tick can retry it.
static Future<void> updateTimer(String text) async {
if (text == _lastText) return;
try {
await _channel.invokeMethod<void>('updateNotificationText', {
'title': 'Revolt VPN',
'text': text,
'disconnectLabel': 'Disconnect',
});
_lastText = text;
} catch (_) {
// Cosmetic.
}
}
// Same id as the service's own alert, so a double post replaces.
static Future<void> showDisconnectedAlert() async {
try {
await _channel.invokeMethod<void>('showDisconnectedAlert');
} catch (_) {
// Informational only.
}
}
/// 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<void> cancelTimer() async {
_lastText = null;
try {
await _channel.invokeMethod<void>('cancelNotification');
} catch (_) {
// Cosmetic.
}
}
/// Forces the next connect to re-post even if the countdown resumes on the
/// same value.
static void reset() => _lastText = null;
}
+44
View File
@@ -0,0 +1,44 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// Background-survival controls.
///
/// Android stops background services of apps that are not exempt from Doze and
/// App Standby, and it tears down the whole process group when a task is swiped
/// away. Those are OS behaviours, not app bugs; the battery-optimisation
/// exemption is the one sanctioned way an app can ask for around them, and it
/// still needs one user tap.
abstract final class PowerSettings {
PowerSettings._();
static const MethodChannel _channel = MethodChannel(
'com.revoltvpn.app/power',
);
/// Whether the OS has exempted this app from Doze / App Standby.
static Future<bool> isBatteryOptimisationDisabled() async {
if (kIsWeb) return true;
try {
return await _channel.invokeMethod<bool>(
'isIgnoringBatteryOptimizations',
) ??
false;
} catch (_) {
return false;
}
}
/// Shows the system exemption dialog. Returns false only when no system UI
/// could be opened at all — a user declining still returns true.
static Future<bool> requestDisableBatteryOptimisation() async {
if (kIsWeb) return true;
try {
return await _channel.invokeMethod<bool>(
'requestIgnoreBatteryOptimizations',
) ??
false;
} catch (_) {
return false;
}
}
}
+78
View File
@@ -0,0 +1,78 @@
import 'dart:convert';
import 'dart:io';
import 'dart:math';
class SecureSocksSession {
static const String inboundTag = 'revolt-secure-socks';
static final Random _random = Random.secure();
final int port;
final String username;
final String password;
final String configJson;
const SecureSocksSession._({
required this.port,
required this.username,
required this.password,
required this.configJson,
});
static Future<SecureSocksSession> create(String baseConfig) async {
final decoded = jsonDecode(baseConfig);
if (decoded is! Map<String, dynamic>) {
throw const FormatException('VLESS configuration must be a JSON object.');
}
final reservation = await ServerSocket.bind(
InternetAddress.loopbackIPv4,
0,
shared: false,
);
final port = reservation.port;
await reservation.close();
if (port <= 1024 || port > 65535) {
throw StateError('Could not allocate a safe local SOCKS5 port.');
}
final username = _token(16);
final password = _token(32);
// ReVolt owns local ingress. Never accept listeners supplied by a remote
// or imported Xray config; the client exposes exactly one authenticated
// loopback SOCKS5 listener for the current ephemeral session.
decoded['inbounds'] = <Map<String, dynamic>>[
<String, dynamic>{
'tag': inboundTag,
'port': port,
'listen': '127.0.0.1',
'protocol': 'socks',
'settings': <String, dynamic>{
'auth': 'password',
'udp': true,
'ip': '127.0.0.1',
'users': <Map<String, String>>[
<String, String>{'user': username, 'pass': password},
],
},
'sniffing': <String, dynamic>{
'enabled': true,
'destOverride': <String>['http', 'tls'],
},
},
];
return SecureSocksSession._(
port: port,
username: username,
password: password,
configJson: jsonEncode(decoded),
);
}
static String _token(int byteCount) {
final bytes = List<int>.generate(byteCount, (_) => _random.nextInt(256));
return bytes.map((value) => value.toRadixString(16).padLeft(2, '0')).join();
}
}
+330 -150
View File
@@ -1,55 +1,80 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:revoltvpn/logic/app_config.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
import 'package:revoltvpn/logic/crypto_service.dart';
import 'package:revoltvpn/components/notification.dart';
class SessionTimer extends ChangeNotifier { import 'package:flutter/widgets.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:revoltvpn/logic/app_config.dart';
import 'package:revoltvpn/logic/crypto_service.dart';
import 'package:revoltvpn/logic/hivemind_service.dart';
import 'package:revoltvpn/logic/notification_service.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
class SessionTimer extends ChangeNotifier with WidgetsBindingObserver {
Timer? _timer; Timer? _timer;
int _tickCount = 0; int _tickCount = 0;
bool _appBackgrounded = false;
final VpnConnection vpnConnection; final VpnConnection vpnConnection;
int _remainingSeconds = 0; int _remainingSeconds = 0;
int _remainingAtLastSync = 0;
int _usedBytes = 0; int _usedBytes = 0;
bool _hasSyncedOnce = false; bool _hasSyncedOnce = false;
int _consecutiveFailures = 0; int _consecutiveFailures = 0;
bool _isDisconnecting = false; bool _isDisconnecting = false;
bool _userInitiatedStop = false; int? _syncEpochInProgress;
Completer<void>? _syncCompletion;
int _sessionEpoch = 0;
bool _supportRewardClaimed = false;
bool _supportRewardStateLoaded = false;
int _supportStateEpoch = 0;
int? _currentPort; static const String _supportRewardClaimKey =
bool _portSwitchInProgress = false; 'support_reward_claimed_active_session';
static const FlutterSecureStorage _supportStorage = FlutterSecureStorage();
static const int _maxConsecutiveFailures = 3; static const int _maxConsecutiveFailures = 3;
static const int _maxOfflineSeconds = 120; static const int _pollIntervalSeconds = 60;
int _offlineSeconds = 0; static const int _backgroundPollIntervalSeconds = 60;
static const int _pollIntervalSeconds = 5;
int _lastUsedBytes = 0; int _lastUsedBytes = 0;
Stopwatch? _sinceLastSuccessfulSync;
// 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; double _currentSpeedKBps = 0.0;
String _lastNotifTime = '';
String _lastNotifSpeed = '';
SessionTimer({required this.vpnConnection}) { SessionTimer({required this.vpnConnection}) {
WidgetsBinding.instance.addObserver(this);
vpnConnection.addListener(_onVpnConnectionChanged); vpnConnection.addListener(_onVpnConnectionChanged);
unawaited(_loadSupportRewardState());
// VpnConnection is eager and can report an already-running native tunnel
// before this provider is created. ChangeNotifier listeners do not replay
// old events, so always evaluate the current state once after construction.
unawaited(Future.microtask(_onVpnConnectionChanged));
} }
int get remaining => _remainingSeconds; int get remaining => _remainingSeconds;
bool get isRunning => _timer != null && _timer!.isActive; bool get isRunning => _timer != null && _timer!.isActive;
bool get isExpired => _remainingSeconds <= 0 && !isRunning; bool get isExpired => _remainingSeconds <= 0 && !isRunning;
bool get hasSyncedOnce => _hasSyncedOnce; bool get hasSyncedOnce => _hasSyncedOnce;
bool get supportRewardClaimed => _supportRewardClaimed;
bool get supportRewardStateLoaded => _supportRewardStateLoaded;
int get usedBytes => _usedBytes; int get usedBytes => _usedBytes;
double get currentSpeedKBps => _currentSpeedKBps; double get currentSpeedKBps => _currentSpeedKBps;
// Display state only - an unreachable API never tears down a live tunnel.
bool get serverUnreachable => _consecutiveFailures >= _maxConsecutiveFailures;
// Why the last session ended, if the user did not end it. Cleared on connect.
String? _lastEndMessage;
String? get lastEndMessage => _lastEndMessage;
String get formatted { String get formatted {
final h = (_remainingSeconds ~/ 3600).toString().padLeft(2, '0'); final h = (_remainingSeconds ~/ 3600).toString().padLeft(2, '0');
final m = ((_remainingSeconds % 3600) ~/ 60).toString().padLeft(2, '0'); final m = ((_remainingSeconds % 3600) ~/ 60).toString().padLeft(2, '0');
@@ -57,243 +82,398 @@ class SessionTimer extends ChangeNotifier {
return '$h:$m:$s'; return '$h:$m:$s';
} }
// Lifecycle Future<void> _loadSupportRewardState() async {
final epoch = _supportStateEpoch;
var claimed = false;
try {
claimed =
(await _supportStorage.read(key: _supportRewardClaimKey)) == '1';
} catch (e) {
debugPrint('[Timer] Failed to load support reward state: $e');
}
if (epoch != _supportStateEpoch) return;
_supportRewardClaimed = claimed;
_supportRewardStateLoaded = true;
notifyListeners();
}
Future<void> _persistSupportRewardState(bool value) async {
try {
await _supportStorage.write(
key: _supportRewardClaimKey,
value: value ? '1' : '0',
);
} catch (e) {
debugPrint('[Timer] Failed to persist support reward state: $e');
}
}
Future<void> markSupportRewardClaimed() async {
if (_supportRewardClaimed) return;
_supportRewardClaimed = true;
_supportRewardStateLoaded = true;
notifyListeners();
await _persistSupportRewardState(true);
}
/// Fires whenever VpnConnection state changes.
void _onVpnConnectionChanged() { void _onVpnConnectionChanged() {
// A live tunnel with a stopped clock is always wrong, whether this process
// adopted an existing runtime, attached late, or recovered from a blip.
if (vpnConnection.status == VpnStatus.connected && if (vpnConnection.status == VpnStatus.connected &&
!isRunning && !isRunning &&
vpnConnection.isStartupRestoration) { !_isDisconnecting) {
debugPrint('[Timer] Connected with a stopped clock - resuming.');
_resumeTicking(); _resumeTicking();
return; return;
} }
final hadActiveSession = isRunning || _hasSyncedOnce;
if (!hadActiveSession || _isDisconnecting) return;
// The underlying VLESS tunnel may briefly flap. If we weren't if (vpnConnection.status == VpnStatus.error) {
// explicitly stopped by the user, resume where we left off. unawaited(_doDisconnect(
if (vpnConnection.status == VpnStatus.connected && 'VPN entered error state',
!isRunning && endedMessage: 'The tunnel stopped. You are not protected.',
!_userInitiatedStop && ));
_hasSyncedOnce) {
debugPrint('[Timer] VPN reconnected after blip — resuming.');
_resumeTicking();
return; return;
} }
if (vpnConnection.status == VpnStatus.disconnected) {
if (vpnConnection.status == VpnStatus.disconnected && isRunning) { // The native deadline beats the 1 s tick, so expiry lands here, not in
_stopInternal(); // _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)),
);
unawaited(_doDisconnect(
'VPN tunnel dropped',
endedMessage:
expired ? 'Your session ended. You are not protected.' : null,
postAlert: false,
));
} }
} }
Future<void> start() async { Future<void> start() async {
_sessionEpoch++;
_remainingSeconds = 0; _remainingSeconds = 0;
_remainingAtLastSync = 0;
_usedBytes = 0; _usedBytes = 0;
_lastUsedBytes = 0; _lastUsedBytes = 0;
_sinceLastSuccessfulSync?.stop();
_sinceLastSuccessfulSync = null;
_deadlineAt = null;
_currentSpeedKBps = 0.0; _currentSpeedKBps = 0.0;
_tickCount = 0; _tickCount = 0;
_hasSyncedOnce = false; _hasSyncedOnce = false;
_consecutiveFailures = 0; _consecutiveFailures = 0;
_offlineSeconds = 0;
_isDisconnecting = false; _isDisconnecting = false;
_userInitiatedStop = false; _appBackgrounded = false;
_currentPort = null; _lastEndMessage = null;
_portSwitchInProgress = false; NotificationService.reset();
// Every session is new, so the once-per-session top-up resets with it.
_supportStateEpoch++;
_supportRewardClaimed = false;
_supportRewardStateLoaded = true;
unawaited(_persistSupportRewardState(false));
_timer?.cancel(); _timer?.cancel();
_timer = Timer.periodic(const Duration(seconds: 1), _tick); _timer = Timer.periodic(const Duration(seconds: 1), _tick);
notifyListeners(); notifyListeners();
unawaited(_syncWithHivemind());
// Kick off the first sync — the UI will show real data as soon as it lands.
_syncWithHivemind();
} }
void _tick(Timer t) { void _tick(Timer t) {
if (_isDisconnecting) return;
// Decrement the local clock as long as we're not in a network blackout. if (_hasSyncedOnce) {
if (_hasSyncedOnce && _consecutiveFailures < _maxConsecutiveFailures) { _reconcileElapsedTime();
if (_remainingSeconds > 0) {
_remainingSeconds--;
}
} }
// If the server has been unreachable for too long, kill the VPN.
// Don't let an orphaned tunnel keep running forever.
if (_consecutiveFailures >= _maxConsecutiveFailures) {
_offlineSeconds++;
if (_offlineSeconds >= _maxOfflineSeconds) {
debugPrint('[Timer] Offline for $_maxOfflineSeconds s — forcing disconnect.');
_forceDisconnect('Session lost — server unreachable');
return;
}
}
// When our clock hits zero, disconnect immediately. Don't wait for the
// next server poll — the session is over and the user expects the VPN
// to drop right now.
if (_hasSyncedOnce && _remainingSeconds <= 0) { if (_hasSyncedOnce && _remainingSeconds <= 0) {
debugPrint('[Timer] Local countdown expired — disconnecting.'); unawaited(_doDisconnect(
_forceDisconnect('Session expired'); 'Session expired',
endedMessage: 'Your session ended. You are not protected.',
));
return; return;
} }
_tickCount++; _tickCount++;
if (_tickCount % _pollIntervalSeconds == 0) { final pollInterval = _appBackgrounded
_syncWithHivemind(); ? _backgroundPollIntervalSeconds
} : _pollIntervalSeconds;
if (_tickCount % pollInterval == 0) {
unawaited(_syncWithHivemind());
// Uses the locally-decremented time so the notification stays in sync
// with the in-app display, not gated behind the 5 s server poll.
if (_hasSyncedOnce) {
final speedText = _currentSpeedKBps > 0.5
? '${_currentSpeedKBps.toStringAsFixed(1)} KB/s'
: 'Idle';
if (formatted != _lastNotifTime || speedText != _lastNotifSpeed) {
_lastNotifTime = formatted;
_lastNotifSpeed = speedText;
VpnNotificationManager.showOrUpdateStatus(
timeLeft: formatted,
speedKbps: speedText,
);
}
} }
notifyListeners(); notifyListeners();
if (_hasSyncedOnce && vpnConnection.status == VpnStatus.connected) {
NotificationService.updateTimer(formatted);
}
} }
void _forceDisconnect(String reason) { /// Force a control-plane refresh after an event that changes the session
if (_isDisconnecting) return; // Already tearing down /// server-side. If a periodic sync is already in flight, wait for it and
debugPrint('[Timer] $reason — forcing disconnect.'); /// issue a fresh request so the event cannot be hidden behind the busy guard.
Future<void> syncNow() async {
final requestedEpoch = _sessionEpoch;
while (requestedEpoch == _sessionEpoch && !_isDisconnecting) {
final active = _syncEpochInProgress == requestedEpoch
? _syncCompletion
: null;
if (active != null) {
await active.future;
continue;
}
await _syncWithHivemind();
return;
}
}
Future<void> 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);
}
// endedMessage is what the UI shows; postAlert raises the notification.
// A user-requested disconnect passes neither.
Future<void> _doDisconnect(
String reason, {
String? endedMessage,
bool postAlert = true,
}) async {
if (_isDisconnecting) return;
_isDisconnecting = true;
_sessionEpoch++;
debugPrint('[Timer] Disconnecting: $reason');
_lastEndMessage = endedMessage;
_deadlineAt = null;
_timer?.cancel(); _timer?.cancel();
_timer = null; _timer = null;
_currentSpeedKBps = 0.0; _currentSpeedKBps = 0.0;
_isDisconnecting = true; _remainingSeconds = 0;
VpnNotificationManager.cancel(); _remainingAtLastSync = 0;
_hasSyncedOnce = false;
_sinceLastSuccessfulSync?.stop();
_sinceLastSuccessfulSync = null;
NotificationService.reset();
notifyListeners(); notifyListeners();
// Await the disconnect so the tunnel is confirmed down before we
// consider the session fully cleaned up. await vpnConnection.disconnect();
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());
} }
_isDisconnecting = false;
notifyListeners();
}
int _readNonNegativeInt(dynamic value, int fallback) {
if (value is int) return value >= 0 ? value : fallback;
if (value is num && value >= 0) return value.toInt();
return fallback;
}
Future<void> _syncWithHivemind() async { Future<void> _syncWithHivemind() async {
// Never sync while the user is explicitly disconnecting.
if (_isDisconnecting) return; if (_isDisconnecting) return;
final epoch = _sessionEpoch;
if (_syncEpochInProgress == epoch) return;
final completion = Completer<void>();
_syncCompletion = completion;
_syncEpochInProgress = epoch;
try { try {
final deviceId = await CryptoService.getDeviceId(); final deviceId = await CryptoService.getDeviceId();
final url = Uri.parse( if (epoch != _sessionEpoch || _isDisconnecting) return;
'${AppConfig.hivemindApiBase}/session/status?device_id=$deviceId');
final response = await http.get(url).timeout(const Duration(seconds: 5)); final base = Uri.parse('${AppConfig.hivemindApiPublic}/session/status');
final url = base.replace(queryParameters: {'device_id': deviceId});
final response = await HivemindService.directGet(url);
if (epoch != _sessionEpoch || _isDisconnecting) return;
if (response.statusCode == 200) { if (response.statusCode == 200) {
final data = jsonDecode(response.body); final decoded = jsonDecode(response.body);
if (decoded is! Map<String, dynamic>) {
debugPrint('[Timer] Invalid session payload type.');
_markSyncFailure(epoch);
return;
}
final data = decoded;
final bool active = data['active'] ?? false; final activeValue = data['active'];
if (!active) { if (activeValue is! bool) {
// Server killed the session — tear down and wait for it. debugPrint('[Timer] Session payload missing boolean active state.');
stop(); _markSyncFailure(epoch);
await vpnConnection.disconnect(); return;
}
if (!activeValue) {
await _doDisconnect(
'Server ended session',
endedMessage:
'The server ended your session. You are not protected.',
);
return; return;
} }
_remainingSeconds = data['expires_in_seconds'] ?? _remainingSeconds; final expiresValue = data['expires_in_seconds'];
_usedBytes = data['used_bytes'] ?? _usedBytes; if (expiresValue is! num ||
!expiresValue.isFinite ||
expiresValue < 0) {
debugPrint('[Timer] Session payload has invalid expiry.');
_markSyncFailure(epoch);
return;
}
final elapsedMs = _sinceLastSuccessfulSync?.elapsedMilliseconds;
_remainingAtLastSync = expiresValue.toInt();
_remainingSeconds = _remainingAtLastSync;
_deadlineAt = DateTime.now().add(
Duration(seconds: _remainingAtLastSync),
);
_usedBytes = _readNonNegativeInt(data['used_bytes'], _usedBytes);
final int deltaBytes = _usedBytes - _lastUsedBytes; final deltaBytes = _usedBytes - _lastUsedBytes;
if (_hasSyncedOnce && deltaBytes > 0) { if (_hasSyncedOnce && elapsedMs != null && elapsedMs > 0) {
_currentSpeedKBps = (deltaBytes / _pollIntervalSeconds) / 1000; _currentSpeedKBps = deltaBytes > 0
} else if (!_hasSyncedOnce) { ? (deltaBytes / (elapsedMs / 1000.0)) / 1000.0
: 0.0;
} else {
_currentSpeedKBps = 0.0; _currentSpeedKBps = 0.0;
} }
_lastUsedBytes = _usedBytes; _lastUsedBytes = _usedBytes;
_sinceLastSuccessfulSync?.stop();
_sinceLastSuccessfulSync = Stopwatch()..start();
if (data['cap_exhausted'] == true) {
// ── Detect port change (throttle engage / disengage) ────── await _doDisconnect(
final serverPort = data['vless_port']; 'Data cap reached',
if (serverPort != null && endedMessage: 'Data limit reached. You are not protected.',
_currentPort != null && );
serverPort != _currentPort &&
!_portSwitchInProgress) {
debugPrint('[Timer] Port changed $_currentPort → $serverPort — reconnecting…');
_currentPort = serverPort;
_portSwitchInProgress = true;
_timer?.cancel();
_isDisconnecting = true;
await vpnConnection.disconnect(skipCleanup: true);
await vpnConnection.connect(skipAdBypass: true, quickReconnect: true);
_resumeTicking();
_portSwitchInProgress = false;
return; return;
} }
_currentPort = serverPort;
if (epoch != _sessionEpoch || _isDisconnecting) return;
try {
await vpnConnection.setNativeSessionDeadline(_remainingAtLastSync);
} catch (e) {
debugPrint('[Timer] Failed to arm native session deadline: $e');
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; _consecutiveFailures = 0;
_offlineSeconds = 0;
_hasSyncedOnce = true; _hasSyncedOnce = true;
notifyListeners(); notifyListeners();
} else { } else {
_markSyncFailure(); _markSyncFailure(epoch);
} }
} catch (e) { } catch (e) {
if (epoch == _sessionEpoch && !_isDisconnecting) {
debugPrint('Hivemind sync error: $e'); debugPrint('Hivemind sync error: $e');
_markSyncFailure(); _markSyncFailure(epoch);
}
} finally {
if (_syncEpochInProgress == epoch) {
_syncEpochInProgress = null;
}
if (identical(_syncCompletion, completion)) {
_syncCompletion = null;
}
if (!completion.isCompleted) completion.complete();
} }
} }
void _markSyncFailure() { void _markSyncFailure(int epoch) {
if (epoch != _sessionEpoch || _isDisconnecting) return;
_consecutiveFailures++; _consecutiveFailures++;
if (_consecutiveFailures >= _maxConsecutiveFailures) { if (_consecutiveFailures >= _maxConsecutiveFailures) {
notifyListeners(); // let the UI show "Reconnecting…" notifyListeners();
} }
} }
void _reconcileElapsedTime() {
final clock = _sinceLastSuccessfulSync;
if (!_hasSyncedOnce || clock == null) return;
final elapsed = clock.elapsed.inSeconds;
_remainingSeconds =
(_remainingAtLastSync - elapsed).clamp(0, 1 << 31).toInt();
void stop() { // The Stopwatch over-reports after device suspend. Take the smaller of
_userInitiatedStop = true; // the two, never the wall clock alone - a backward clock must not extend.
_isDisconnecting = true; final deadline = _deadlineAt;
_timer?.cancel(); if (deadline != null) {
_timer = null; final byWallClock = deadline.difference(DateTime.now()).inSeconds;
_currentSpeedKBps = 0.0; if (byWallClock < _remainingSeconds) {
_hasSyncedOnce = false; _remainingSeconds = byWallClock.clamp(0, 1 << 31).toInt();
_remainingSeconds = 0; }
}
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.paused ||
state == AppLifecycleState.detached ||
state == AppLifecycleState.inactive ||
state == AppLifecycleState.hidden) {
_appBackgrounded = true;
return;
}
if (state != AppLifecycleState.resumed || _isDisconnecting) return;
_appBackgrounded = false;
if (vpnConnection.status != VpnStatus.connected) return;
_reconcileElapsedTime();
if (!isRunning) {
_resumeTicking();
return;
}
unawaited(_syncWithHivemind());
notifyListeners(); notifyListeners();
} }
void _resumeTicking() { void _resumeTicking() {
_reconcileElapsedTime();
_timer?.cancel(); _timer?.cancel();
_timer = Timer.periodic(const Duration(seconds: 1), _tick); _timer = Timer.periodic(const Duration(seconds: 1), _tick);
_isDisconnecting = false; _isDisconnecting = false;
_syncWithHivemind(); unawaited(_syncWithHivemind());
notifyListeners();
}
void _stopInternal() {
_isDisconnecting = true;
_timer?.cancel();
_timer = null;
_currentSpeedKBps = 0.0;
_hasSyncedOnce = false;
VpnNotificationManager.cancel();
notifyListeners(); notifyListeners();
} }
@override @override
void dispose() { void dispose() {
// Invalidate every asynchronous generation before removing listeners so
// late storage/network completions cannot notify a disposed notifier.
_sessionEpoch++;
_supportStateEpoch++;
_isDisconnecting = true;
WidgetsBinding.instance.removeObserver(this);
vpnConnection.removeListener(_onVpnConnectionChanged); vpnConnection.removeListener(_onVpnConnectionChanged);
_timer?.cancel(); _timer?.cancel();
VpnNotificationManager.cancel(); _sinceLastSuccessfulSync?.stop();
super.dispose(); super.dispose();
} }
} }
+322
View File
@@ -0,0 +1,322 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:revoltvpn/logic/app_config.dart';
import 'package:revoltvpn/logic/app_colors.dart';
enum UpdateStatus { upToDate, updateAvailable, checkFailed }
enum InstallSource { playStore, sideload }
Uri? _trustedHttpsUri(String raw, Set<String> allowedHosts) {
final uri = Uri.tryParse(raw);
if (uri == null || uri.scheme != 'https' || !allowedHosts.contains(uri.host)) {
return null;
}
return uri;
}
class _ParsedVersion {
final List<int> core;
final List<String> preRelease;
const _ParsedVersion(this.core, this.preRelease);
static _ParsedVersion? tryParse(String input) {
var value = input.trim();
if (value.startsWith('v') || value.startsWith('V')) {
value = value.substring(1);
}
value = value.split('+').first;
final dash = value.indexOf('-');
final corePart = dash < 0 ? value : value.substring(0, dash);
final prePart = dash < 0 ? '' : value.substring(dash + 1);
final rawCore = corePart.split('.');
if (rawCore.isEmpty || rawCore.any((p) => int.tryParse(p) == null)) {
return null;
}
final core = rawCore.map(int.parse).toList(growable: false);
while (core.length < 3) {
core.add(0);
}
final pre = prePart.isEmpty
? const <String>[]
: prePart.split('.').where((e) => e.isNotEmpty).toList(growable: false);
return _ParsedVersion(core, pre);
}
int compareTo(_ParsedVersion other) {
final length = core.length > other.core.length ? core.length : other.core.length;
for (var i = 0; i < length; i++) {
final left = i < core.length ? core[i] : 0;
final right = i < other.core.length ? other.core[i] : 0;
if (left != right) return left.compareTo(right);
}
if (preRelease.isEmpty && other.preRelease.isEmpty) return 0;
if (preRelease.isEmpty) return 1;
if (other.preRelease.isEmpty) return -1;
final preLength = preRelease.length > other.preRelease.length
? preRelease.length
: other.preRelease.length;
for (var i = 0; i < preLength; i++) {
if (i >= preRelease.length) return -1;
if (i >= other.preRelease.length) return 1;
final left = preRelease[i];
final right = other.preRelease[i];
final leftNum = int.tryParse(left);
final rightNum = int.tryParse(right);
if (leftNum != null && rightNum != null) {
if (leftNum != rightNum) return leftNum.compareTo(rightNum);
continue;
}
if (leftNum != null) return -1;
if (rightNum != null) return 1;
final lexical = left.compareTo(right);
if (lexical != 0) return lexical;
}
return 0;
}
}
class PlayStoreUpdater {
PlayStoreUpdater._();
static String get _url =>
'https://play.google.com/store/apps/details?id=${AppConfig.applicationId}';
static Future<bool> open() async {
final uri = _trustedHttpsUri(_url, const {'play.google.com'});
if (uri == null) {
debugPrint('[Updater] Refusing invalid Play Store URL.');
return false;
}
try {
return await launchUrl(uri, mode: LaunchMode.externalApplication);
} catch (e) {
debugPrint('[Updater] Failed to open Play Store: $e');
return false;
}
}
}
class GitHubUpdater {
GitHubUpdater._();
static String? _cachedDownloadUrl;
static Future<String?> fetchLatestVersion() async {
final apiUri = Uri.https(
'api.github.com',
'/repos/${AppConfig.githubOwner}/${AppConfig.githubRepo}/releases/latest',
);
try {
final response = await http
.get(apiUri, headers: {'Accept': 'application/vnd.github+json'})
.timeout(const Duration(seconds: 8));
if (response.statusCode != 200) {
debugPrint('[Updater] GitHub API returned ${response.statusCode}');
return null;
}
final decoded = jsonDecode(response.body);
if (decoded is! Map<String, dynamic>) {
debugPrint('[Updater] Invalid GitHub release payload.');
return null;
}
final htmlUrl = decoded['html_url'];
if (htmlUrl is String &&
_trustedHttpsUri(htmlUrl, const {'github.com'}) != null) {
_cachedDownloadUrl = htmlUrl;
} else {
_cachedDownloadUrl = null;
}
final rawTag = decoded['tag_name'];
if (rawTag is! String || rawTag.isEmpty || rawTag.length > 64) {
debugPrint('[Updater] Invalid release tag.');
return null;
}
final normalized = rawTag.startsWith('v') ? rawTag.substring(1) : rawTag;
if (_ParsedVersion.tryParse(normalized) == null) {
debugPrint('[Updater] Release tag is not a supported version: $rawTag');
return null;
}
return normalized;
} catch (e) {
debugPrint('[Updater] GitHub API error: $e');
return null;
}
}
static Future<bool> open() async {
final raw = _cachedDownloadUrl ?? AppConfig.githubReleasesUrl;
final uri = _trustedHttpsUri(raw, const {'github.com'});
if (uri == null) {
debugPrint('[Updater] Refusing untrusted GitHub update URL.');
return false;
}
try {
return await launchUrl(uri, mode: LaunchMode.externalApplication);
} catch (e) {
debugPrint('[Updater] Failed to open GitHub: $e');
return false;
}
}
}
class Updater {
Updater._();
static InstallSource? _cachedSource;
static Future<InstallSource> get installSource async {
if (_cachedSource != null) return _cachedSource!;
if (kIsWeb || !Platform.isAndroid) {
_cachedSource = InstallSource.sideload;
return _cachedSource!;
}
try {
final result = await const MethodChannel('com.revoltvpn.app/installer')
.invokeMethod<String>('getInstallerPackage');
_cachedSource = (result == 'com.android.vending')
? InstallSource.playStore
: InstallSource.sideload;
} catch (e) {
debugPrint('[Updater] Installer check failed: $e');
_cachedSource = InstallSource.sideload;
}
return _cachedSource!;
}
static int _compareVersions(String a, String b) {
final left = _ParsedVersion.tryParse(a);
final right = _ParsedVersion.tryParse(b);
if (left == null || right == null) {
// Invalid local metadata should not invent an ordering.
return 0;
}
return left.compareTo(right);
}
static String _versionLabel(String v, bool isLocal) {
final prefix = v.startsWith('v') ? '' : 'v';
return '$prefix$v${isLocal ? ' (installed)' : ''}';
}
static Future<void> check(BuildContext context) {
final navigator = Navigator.of(context, rootNavigator: true);
final messenger = ScaffoldMessenger.of(context);
return checkWithHandles(
navigator: navigator,
messenger: messenger,
);
}
static Future<void> checkWithHandles({
required NavigatorState navigator,
required ScaffoldMessengerState messenger,
}) async {
final info = await PackageInfo.fromPlatform();
final localVersion = info.version;
if (localVersion.isEmpty || _ParsedVersion.tryParse(localVersion) == null) {
_showSnackBar(
messenger,
'Could not determine app version',
isError: true,
);
return;
}
final latestVersion = await GitHubUpdater.fetchLatestVersion();
if (latestVersion == null) {
_showSnackBar(messenger, 'Could not reach GitHub', isError: true);
return;
}
if (_compareVersions(localVersion, latestVersion) >= 0) {
_showSnackBar(messenger, 'Up to date');
return;
}
final source = await installSource;
final storeName =
source == InstallSource.playStore ? 'Play Store' : 'GitHub';
if (!navigator.mounted) return;
showDialog(
context: navigator.context,
builder: (ctx) => AlertDialog(
backgroundColor: AppColors.bgCard,
title: const Text(
'Update available',
style: TextStyle(color: AppColors.textWhite),
),
content: Text(
'${_versionLabel(latestVersion, false)} is available on $storeName.\n'
'You have ${_versionLabel(localVersion, true)}.',
style: const TextStyle(color: AppColors.slate70),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text(
'Later',
style: TextStyle(color: AppColors.slate70),
),
),
TextButton(
onPressed: () {
Navigator.pop(ctx);
source == InstallSource.playStore
? PlayStoreUpdater.open()
: GitHubUpdater.open();
},
child: Text(
'Open $storeName',
style: const TextStyle(color: AppColors.accent),
),
),
],
),
);
}
static void _showSnackBar(
ScaffoldMessengerState messenger,
String message, {
bool isError = false,
}) {
if (!messenger.mounted) return;
messenger.showSnackBar(
SnackBar(
content: Row(
children: [
Icon(
isError ? Icons.error_outline : Icons.check_circle,
color: isError ? AppColors.red : AppColors.green,
size: 18,
),
const SizedBox(width: 8),
Text(message),
],
),
backgroundColor: AppColors.bgCard,
duration: const Duration(seconds: 2),
),
);
}
}
+324 -108
View File
@@ -1,7 +1,13 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_vless/flutter_vless.dart'; import 'package:flutter_vless/flutter_vless.dart';
import 'package:revoltvpn/logic/connection_settings.dart';
import 'package:revoltvpn/logic/hivemind_service.dart'; import 'package:revoltvpn/logic/hivemind_service.dart';
import 'package:revoltvpn/logic/local_socks_tester.dart';
import 'package:revoltvpn/logic/network_monitor.dart';
import 'package:revoltvpn/logic/secure_socks_session.dart';
enum VpnStatus { enum VpnStatus {
disconnected, disconnected,
@@ -12,7 +18,12 @@ enum VpnStatus {
} }
class VpnConnection extends ChangeNotifier { class VpnConnection extends ChangeNotifier {
bool _cancelled = false; static const MethodChannel _nativeControl = MethodChannel('flutter_vless');
int _connectEpoch = 0;
bool _suppressNativeConnect = false;
bool _disposed = false;
VpnStatus _status = VpnStatus.disconnected; VpnStatus _status = VpnStatus.disconnected;
VpnStatus get status => _status; VpnStatus get status => _status;
@@ -22,78 +33,156 @@ class VpnConnection extends ChangeNotifier {
String? _errorMessage; String? _errorMessage;
String? get errorMessage => _errorMessage; String? get errorMessage => _errorMessage;
// True when the app was killed and reopened while the VPN was running. /// True when the UI attached to a tunnel that was already running, rather
bool _isStartupRestoration = false; /// than starting one itself. The session timer uses this to resume ticking.
bool get isStartupRestoration => _isStartupRestoration; bool _adoptedRunningRuntime = false;
bool get adoptedRunningRuntime => _adoptedRunningRuntime;
bool _serverReachable = false; ConnectionMode _activeMode = ConnectionMode.tun;
bool get serverReachable => _serverReachable; ConnectionMode get activeMode => _activeMode;
Timer? _healthTimer; String _networkTransport = 'unknown';
String get networkTransport => _networkTransport;
SecureSocksSession? get activeSocksSession => _lastSecureSocks;
bool get canTestActiveLocalSocks =>
!_disposed &&
_status == VpnStatus.connected &&
_activeMode == ConnectionMode.proxy &&
_lastSecureSocks != null;
Future<LocalSocksTestResult> testActiveLocalSocks() async {
final active = _lastSecureSocks;
if (!canTestActiveLocalSocks || active == null) {
return const LocalSocksTestResult(
ok: false,
latencyMs: null,
message: 'No active authenticated SOCKS5 session.',
);
}
return LocalSocksTester.test(
host: '127.0.0.1',
port: active.port,
username: active.username,
password: active.password,
);
}
StreamSubscription<NetworkSnapshot>? _networkSubscription;
SecureSocksSession? _lastSecureSocks;
bool _userDisconnecting = false;
late final FlutterVless _vless; late final FlutterVless _vless;
bool _initialized = false; bool _initialized = false;
final Completer<void> _readyCompleter = Completer<void>();
Future<void> get ready => _readyCompleter.future;
VpnConnection() { VpnConnection() {
_activeMode = ConnectionSettings.mode;
_init(); _init();
} }
Future<void> _init() async { Future<void> _init() async {
if (kIsWeb) return; try {
await _startEngine();
} catch (e) {
debugPrint('[VPN] Engine init failed: $e');
} finally {
if (!_readyCompleter.isCompleted) _readyCompleter.complete();
}
}
Future<void> _startEngine() async {
if (kIsWeb || _disposed) return;
await ConnectionSettings.initialize();
if (_disposed) return;
_activeMode = ConnectionSettings.mode;
_vless = FlutterVless( _vless = FlutterVless(
onStatusChanged: (status) { onStatusChanged: (status) {
debugPrint('[VPN] Status: state=${status.state} ' debugPrint(
'connection=${status.connectionState.name}'); '[VPN] Status: state=${status.state} '
'connection=${status.connectionState.name}',
);
_mapStatus(status); _mapStatus(status);
}, },
); );
try { try {
await _vless.initializeVless( await _vless.initializeVless(
providerBundleIdentifier: 'com.revoltvpn.app', providerBundleIdentifier: 'com.paladinvpn.app',
notificationIconResourceType: 'drawable',
notificationIconResourceName: 'notification_icon',
); );
if (_disposed) return;
_initialized = true; _initialized = true;
} catch (e) { } catch (e) {
debugPrint('[VPN] VLESS init error (expected on emulator): $e'); debugPrint('[VPN] VLESS init error (expected on emulator): $e');
} }
if (_disposed) return;
// Periodic server health check _networkSubscription = NetworkMonitor.changes.listen(
_checkHealth(); (snapshot) {
_healthTimer = Timer.periodic(const Duration(seconds: 30), (_) => _checkHealth()); if (_disposed) return;
// ConnectivityManager is informational only. Restarting from every
// callback caused the old VPN-created-network reconnect loop.
_networkTransport = snapshot.transport;
notifyListeners();
},
onError: (Object error) {
debugPrint('[VPN] Network monitor error: $error');
},
);
// Check if VPN was already running (app killed and reopened)
try { try {
final coreVersion = await _vless.getCoreVersion(); final coreVersion = await _vless.getCoreVersion();
if (!_disposed) {
debugPrint('[VPN] Xray core version: $coreVersion'); debugPrint('[VPN] Xray core version: $coreVersion');
final delay = await _vless.getConnectedServerDelay();
if (delay > 0) {
_isStartupRestoration = true;
_setStatus(VpnStatus.connected, 'Secured');
} }
} catch (_) {} } catch (_) {}
} }
String get _connectedLabel {
switch (_activeMode) {
case ConnectionMode.proxy:
return 'SOCKS5 gateway active';
case ConnectionMode.tun:
return 'Secured';
}
}
bool _isCurrentConnect(int epoch) =>
!_disposed && epoch == _connectEpoch && !_userDisconnecting;
void _mapStatus(VlessStatus status) { void _mapStatus(VlessStatus status) {
if (_disposed) return;
switch (status.connectionState) { switch (status.connectionState) {
case VlessConnectionState.connected: case VlessConnectionState.connected:
_setStatus(VpnStatus.connected, 'Secured'); if (_suppressNativeConnect || _userDisconnecting) return;
if (_connectEpoch == 0) _adoptedRunningRuntime = true;
_setStatus(VpnStatus.connected, _connectedLabel);
break; break;
case VlessConnectionState.disconnected: case VlessConnectionState.disconnected:
_isStartupRestoration = false; _clearRuntimeSnapshot();
_setStatus(VpnStatus.disconnected, 'Tap to connect'); _setStatus(VpnStatus.disconnected, 'Tap to connect');
break; break;
case VlessConnectionState.connecting: case VlessConnectionState.connecting:
if (_suppressNativeConnect || _userDisconnecting) return;
_setStatus(VpnStatus.connecting, 'Establishing tunnel…'); _setStatus(VpnStatus.connecting, 'Establishing tunnel…');
break; break;
case VlessConnectionState.disconnecting: case VlessConnectionState.disconnecting:
_isStartupRestoration = false;
_setStatus(VpnStatus.disconnecting, 'Tearing down…'); _setStatus(VpnStatus.disconnecting, 'Tearing down…');
break; break;
case VlessConnectionState.unknown: case VlessConnectionState.unknown:
// Native backend emitted an unrecognized state — treat as error if (_suppressNativeConnect || _userDisconnecting) return;
// only if we aren't already in a terminal state.
if (_status != VpnStatus.connected && if (_status != VpnStatus.connected &&
_status != VpnStatus.disconnected) { _status != VpnStatus.disconnected) {
_setStatus(VpnStatus.error, 'Connection failed'); _setStatus(VpnStatus.error, 'Connection failed');
@@ -102,161 +191,288 @@ class VpnConnection extends ChangeNotifier {
} }
} }
Future<bool> connect({bool skipAdBypass = false, bool quickReconnect = false}) async { Future<bool> connect({String? adNonce}) async {
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) { if (_disposed ||
_userDisconnecting ||
_status == VpnStatus.connected ||
_status == VpnStatus.connecting ||
_status == VpnStatus.disconnecting) {
return false; return false;
} }
_cancelled = false;
final connectEpoch = ++_connectEpoch;
_suppressNativeConnect = false;
_userDisconnecting = false;
await ConnectionSettings.initialize();
if (!_isCurrentConnect(connectEpoch)) return false;
_activeMode = ConnectionSettings.mode;
if (!kIsWeb && !_initialized) { if (!kIsWeb && !_initialized) {
_suppressNativeConnect = true;
_errorMessage = 'VPN service unavailable.'; _errorMessage = 'VPN service unavailable.';
_setStatus(VpnStatus.error, 'Service unavailable'); _setStatus(VpnStatus.error, 'Service unavailable');
return false; return false;
} }
_setStatus(VpnStatus.connecting, 'Fetching config…'); // 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<void>('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;
if (!ok) {
_suppressNativeConnect = true;
_errorMessage = 'VPN permission denied.';
_setStatus(VpnStatus.error, 'Permission required');
return false;
}
}
final startingMessage = switch (_activeMode) {
ConnectionMode.tun => 'Establishing secure channel…',
ConnectionMode.proxy => 'Starting local SOCKS5 proxy…',
};
_setStatus(VpnStatus.connecting, startingMessage);
_errorMessage = null; _errorMessage = null;
if (kIsWeb) { if (kIsWeb) {
await Future.delayed(const Duration(seconds: 1)); await Future.delayed(const Duration(seconds: 1));
if (!_isCurrentConnect(connectEpoch)) return false;
_setStatus(VpnStatus.connected, 'Secured (dev mode)'); _setStatus(VpnStatus.connected, 'Secured (dev mode)');
return true; return true;
} }
String vlessUrl; _setStatus(VpnStatus.connecting, 'Fetching config…');
String realUrl;
try { try {
vlessUrl = await HivemindService.fetchConfigWithPolling( realUrl = await HivemindService.fetchConfigDirectly(
skipAdBypass: skipAdBypass, adNonce: adNonce,
quickReconnect: quickReconnect,
onAttempt: (attempt, total) { onAttempt: (attempt, total) {
if (!quickReconnect) { if (!_isCurrentConnect(connectEpoch)) return;
_setStatus(VpnStatus.connecting, 'Contacting server ($attempt/$total)…'); _setStatus(
} VpnStatus.connecting,
'Contacting server ($attempt/$total)…',
);
}, },
); );
} catch (e) { } catch (e) {
debugPrint('[VPN] Hivemind config error: $e'); if (!_isCurrentConnect(connectEpoch)) return false;
debugPrint('[VPN] Config fetch error: $e');
final raw = e.toString().replaceAll('Exception: ', ''); final raw = e.toString().replaceAll('Exception: ', '');
if (raw.contains('Cancelled')) { if (raw.contains('Cancelled')) return false;
// User tapped disconnect — silently abort _suppressNativeConnect = true;
return false; if (raw.contains('timed out') || raw.contains('Session not activated')) {
} else if (raw.contains('timed out') || raw.contains('Session not activated')) { _errorMessage =
_errorMessage = 'The server did not respond in time.\nCheck your connection and try again.'; 'The server did not respond in time.\nCheck your connection and try again.';
_setStatus(VpnStatus.error, 'Server unreachable'); _setStatus(VpnStatus.error, 'Server unreachable');
} else if (raw.contains('SocketException') || raw.contains('Failed host lookup')) {
_errorMessage = 'Cannot reach the server.\nMake sure you have internet access.';
_setStatus(VpnStatus.error, 'No internet');
} else { } else {
_errorMessage = raw; _errorMessage = raw;
final short = raw.length > 35 ? '${raw.substring(0, 35)}…' : raw; _setStatus(VpnStatus.error, 'Config fetch error');
_setStatus(VpnStatus.error, short);
} }
return false; return false;
} }
if (_cancelled) { if (!_isCurrentConnect(connectEpoch)) return false;
_setStatus(VpnStatus.disconnected, 'Tap to connect'); _setStatus(VpnStatus.connecting, 'Starting secure route…');
return false;
}
try { try {
final parsed = FlutterVless.parse(vlessUrl); final parsed = FlutterVless.parse(realUrl);
final config = parsed.getFullConfiguration(); final baseConfig = parsed.getFullConfiguration();
final remark = parsed.remark.isNotEmpty ? parsed.remark : 'Revolt VPN';
final secureSocks = await SecureSocksSession.create(baseConfig);
if (!_isCurrentConnect(connectEpoch)) return false;
final verifyLocalSocks = _activeMode == ConnectionMode.proxy;
await _vless.startVless( await _startRuntime(
remark: parsed.remark.isNotEmpty ? parsed.remark : 'ReVoltVPN', config: secureSocks.configJson,
config: config, remark: remark,
proxyOnly: verifyLocalSocks,
); );
if (!_isCurrentConnect(connectEpoch)) return false;
if (quickReconnect) { _setStatus(
_setStatus(VpnStatus.connected, 'Secured'); VpnStatus.connecting,
} else { verifyLocalSocks
// Give the tunnel a moment to stabilise ? 'Waiting for local SOCKS5…'
_setStatus(VpnStatus.connecting, 'Verifying session…'); : 'Waiting for VPN interface…',
await Future.delayed(const Duration(seconds: 1)); );
if (!await _waitForNativeConnected(connectEpoch)) {
throw StateError('VPN runtime did not report CONNECTED');
}
bool sessionOk = false; if (verifyLocalSocks) {
for (int attempt = 0; attempt < 2; attempt++) { if (!_isCurrentConnect(connectEpoch)) return false;
sessionOk = await HivemindService.verifySession(); _setStatus(VpnStatus.connecting, 'Checking Local SOCKS5…');
if (sessionOk) break; if (!await _waitForLocalSocksListener(
if (attempt == 0) { secureSocks,
debugPrint('[VPN] verifySession attempt 1 failed, retrying…'); connectEpoch,
await Future.delayed(const Duration(seconds: 2)); )) {
throw StateError('Local SOCKS5 listener did not become ready');
} }
} }
if (!sessionOk) { if (!_isCurrentConnect(connectEpoch)) return false;
debugPrint('[VPN] Tunnel started but no server session — tearing down.'); _lastSecureSocks = secureSocks;
} catch (e) {
if (!_isCurrentConnect(connectEpoch)) return false;
debugPrint('[VPN] Tunnel start error: $e');
_suppressNativeConnect = true;
try { try {
await _vless.stopVless(); await _stopRuntime();
} catch (_) {} } catch (stopError) {
_errorMessage = 'Session not confirmed by server.\nPlease try again.'; debugPrint('[VPN] Runtime cleanup failed after start error: $stopError');
_setStatus(VpnStatus.error, 'Session rejected'); if (!_isCurrentConnect(connectEpoch)) return false;
_errorMessage = 'VPN failed to shut down cleanly.\nPlease restart the app.';
_setStatus(VpnStatus.error, 'Shutdown failed');
return false; return false;
} }
if (!_isCurrentConnect(connectEpoch)) return false;
_setStatus(VpnStatus.connected, 'Secured'); _clearRuntimeSnapshot();
} _errorMessage = _activeMode == ConnectionMode.proxy
return true; ? 'SOCKS5 gateway failed to start.\nTry reconnecting.'
} catch (e) { : 'Connection failed to start.\nTry reconnecting.';
debugPrint('[VPN] VLESS tunnel error: $e');
_errorMessage = 'Tunnel failed to start.\nTry reconnecting.';
_setStatus(VpnStatus.error, 'Connection failed'); _setStatus(VpnStatus.error, 'Connection failed');
return false; return false;
} }
if (!_isCurrentConnect(connectEpoch)) return false;
_setStatus(VpnStatus.connected, _connectedLabel);
return true;
} }
Future<void> disconnect({bool skipCleanup = false}) async { Future<void> _startRuntime({
_cancelled = true; required String config,
HivemindService.cancel(); // abort any in-progress polling required String remark,
if (_status == VpnStatus.disconnected || _status == VpnStatus.disconnecting) { required bool proxyOnly,
return; }) async {
await _vless.startVless(
remark: remark,
config: config,
proxyOnly: proxyOnly,
);
} }
Future<bool> _waitForLocalSocksListener(
SecureSocksSession session,
int connectEpoch,
) async {
for (var attempt = 0; attempt < 4; attempt++) {
if (!_isCurrentConnect(connectEpoch)) return false;
final result = await LocalSocksTester.testListener(
host: '127.0.0.1',
port: session.port,
username: session.username,
password: session.password,
);
if (!_isCurrentConnect(connectEpoch)) return false;
if (result.ok) return true;
if (attempt < 3) {
await Future.delayed(const Duration(milliseconds: 250));
}
}
return false;
}
Future<bool> _waitForNativeConnected(int connectEpoch) async {
for (var attempt = 0; attempt < 24; attempt++) {
if (!_isCurrentConnect(connectEpoch)) return false;
if (_status == VpnStatus.connected) return true;
if (_status == VpnStatus.error || _status == VpnStatus.disconnected) {
return false;
}
await Future.delayed(const Duration(milliseconds: 250));
}
return _isCurrentConnect(connectEpoch) &&
_status == VpnStatus.connected;
}
Future<void> _stopRuntime() async {
await _vless.stopVless().timeout(const Duration(seconds: 8));
}
Future<void> setNativeSessionDeadline(int remainingSeconds) async {
if (kIsWeb) return;
if (_disposed) throw StateError('VPN connection has been disposed');
if (!_initialized) throw StateError('VPN native service is not initialized');
if (remainingSeconds < 0) {
throw ArgumentError.value(remainingSeconds, 'remainingSeconds');
}
await _nativeControl.invokeMethod<void>(
'setSessionDeadline',
<String, Object>{'remainingSeconds': remainingSeconds},
);
}
Future<void> disconnect() async {
if (_disposed || _status == VpnStatus.disconnecting) return;
_connectEpoch++;
_suppressNativeConnect = true;
_userDisconnecting = true;
HivemindService.cancel();
_setStatus(VpnStatus.disconnecting, 'Tearing down…'); _setStatus(VpnStatus.disconnecting, 'Tearing down…');
if (kIsWeb) { if (kIsWeb) {
await Future.delayed(const Duration(milliseconds: 500)); await Future.delayed(const Duration(milliseconds: 500));
if (_disposed) return;
_clearRuntimeSnapshot();
_setStatus(VpnStatus.disconnected, 'Tap to connect'); _setStatus(VpnStatus.disconnected, 'Tap to connect');
_userDisconnecting = false;
return; return;
} }
try { try {
await _vless.stopVless().timeout( await _vless.stopVless().timeout(const Duration(seconds: 8));
const Duration(seconds: 5),
onTimeout: () => debugPrint('[VPN] stopVless() timed out.'),
);
} catch (e) { } catch (e) {
if (_disposed) return;
debugPrint('[VPN] VLESS stop error: $e'); debugPrint('[VPN] VLESS stop error: $e');
_errorMessage = 'VPN shutdown error.\nPlease restart the app.';
_clearRuntimeSnapshot();
_setStatus(VpnStatus.error, 'Shutdown failed');
_userDisconnecting = false;
return;
} }
if (!skipCleanup) { if (_disposed) return;
HivemindService.disconnectAndCleanup(); _errorMessage = null;
} _clearRuntimeSnapshot();
_setStatus(VpnStatus.disconnected, 'Tap to connect'); _setStatus(VpnStatus.disconnected, 'Tap to connect');
_userDisconnecting = false;
} }
void _setStatus(VpnStatus s, String msg) { void _clearRuntimeSnapshot() {
_status = s; _lastSecureSocks = null;
_statusMessage = msg; _adoptedRunningRuntime = false;
notifyListeners();
} }
Future<void> _checkHealth() async { void _setStatus(VpnStatus status, String message) {
_serverReachable = await HivemindService.checkHealth(); if (_disposed) return;
_status = status;
_statusMessage = message;
notifyListeners(); notifyListeners();
} }
@override @override
void dispose() { void dispose() {
_healthTimer?.cancel(); _disposed = true;
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) { _connectEpoch++;
try { _suppressNativeConnect = true;
_vless.stopVless(); _userDisconnecting = true;
} catch (_) { HivemindService.cancel();
// Best-effort — widget is being destroyed anyway _networkSubscription?.cancel();
} // Provider/UI disposal is not a user disconnect command. Keeping teardown
} // in disconnect() prevents lifecycle churn from silently dropping the VPN.
super.dispose(); super.dispose();
} }
} }
+18 -14
View File
@@ -1,20 +1,22 @@
import 'package:flutter/material.dart';
import 'dart:ui'; import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
import 'package:revoltvpn/logic/session_timer.dart';
import 'package:revoltvpn/logic/ad_manager.dart'; import 'package:revoltvpn/logic/ad_manager.dart';
import 'package:revoltvpn/logic/consent_manager.dart';
import 'package:revoltvpn/logic/app_colors.dart'; import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/logic/connection_settings.dart';
import 'package:revoltvpn/logic/haptic_settings.dart';
import 'package:revoltvpn/logic/session_timer.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
import 'package:revoltvpn/screens/intro.dart'; import 'package:revoltvpn/screens/intro.dart';
void main() async { Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); await HapticSettings.initialize();
await ConnectionSettings.initialize();
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle( SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
statusBarColor: Colors.transparent, statusBarColor: Colors.transparent,
@@ -32,9 +34,6 @@ void main() async {
return true; return true;
}; };
await ConsentManager.requestConsentIfNeeded();
await MobileAds.instance.initialize();
runApp(const ReVoltApp()); runApp(const ReVoltApp());
} }
@@ -45,10 +44,15 @@ class ReVoltApp extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MultiProvider( return MultiProvider(
providers: [ providers: [
ChangeNotifierProvider(create: (_) => VpnConnection()), ChangeNotifierProvider(create: (_) => VpnConnection(), lazy: false),
ChangeNotifierProxyProvider<VpnConnection, SessionTimer>( ChangeNotifierProxyProvider<VpnConnection, SessionTimer>(
create: (ctx) => SessionTimer(vpnConnection: ctx.read<VpnConnection>()), // Eager, like VpnConnection: the timer has to be listening before the
update: (_, vpn, prev) => prev ?? SessionTimer(vpnConnection: vpn), // engine reports an already-running tunnel, not after the intro.
lazy: false,
create: (ctx) =>
SessionTimer(vpnConnection: ctx.read<VpnConnection>()),
update: (_, vpn, prev) =>
prev ?? SessionTimer(vpnConnection: vpn),
), ),
ChangeNotifierProvider(create: (_) => AdManager()), ChangeNotifierProvider(create: (_) => AdManager()),
], ],
+67 -16
View File
@@ -1,7 +1,12 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:revoltvpn/logic/app_colors.dart'; import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/logic/haptic_settings.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
import 'package:revoltvpn/screens/main_screen.dart'; import 'package:revoltvpn/screens/main_screen.dart';
import 'package:revoltvpn/screens/settings/in_settings/rain.dart';
import 'package:revoltvpn/screens/settings/in_settings/lightning.dart';
class IntroScreen extends StatefulWidget { class IntroScreen extends StatefulWidget {
const IntroScreen({super.key}); const IntroScreen({super.key});
@@ -11,11 +16,18 @@ class IntroScreen extends StatefulWidget {
} }
class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver { class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
static const _minDisplay = Duration(milliseconds: 500);
static const _bootTimeout = Duration(seconds: 8);
String _status = 'Starting secure engine…';
bool _bootComplete = false;
bool _navigated = false;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
WidgetsBinding.instance.addObserver(this); WidgetsBinding.instance.addObserver(this);
_scheduleNavigation(); _boot();
} }
@override @override
@@ -26,28 +38,56 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
@override @override
void didChangeAppLifecycleState(AppLifecycleState state) { void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) { if (state == AppLifecycleState.resumed) _navigateIfReady();
_navigateToMain();
} }
Future<void> _boot() async {
final elapsed = Stopwatch()..start();
final vpn = context.read<VpnConnection>();
// The overlays and haptic layer read these before MainScreen mounts.
final settingsPrefs = Future.wait([
loadRainPref(),
loadLightningPref(),
HapticSettings.initialize(),
]);
try {
await vpn.ready.timeout(_bootTimeout);
} on TimeoutException {
debugPrint('[Boot] Engine init exceeded ${_bootTimeout.inSeconds}s '
'— continuing to the main screen anyway.');
} catch (e) {
debugPrint('[Boot] Engine init error: $e');
}
try {
await settingsPrefs;
} catch (e) {
debugPrint('[Boot] Settings prefs load failed, using defaults: $e');
} }
void _scheduleNavigation() {
// Brief natural pause — just long enough to perceive the logo.
Timer(const Duration(milliseconds: 1200), () {
if (!mounted) return; if (!mounted) return;
setState(() => _status = 'Ready');
final remaining = _minDisplay - elapsed.elapsed;
if (remaining > Duration.zero) await Future.delayed(remaining);
if (!mounted) return;
_bootComplete = true;
_navigateIfReady();
}
void _navigateIfReady() {
if (!mounted || _navigated || !_bootComplete) return;
if (WidgetsBinding.instance.lifecycleState == AppLifecycleState.paused) { if (WidgetsBinding.instance.lifecycleState == AppLifecycleState.paused) {
// App is backgrounded — defer navigation until resumed.
return; return;
} }
_navigateToMain(); _navigated = true;
});
}
void _navigateToMain() {
if (!mounted) return;
Navigator.of(context).pushReplacement( Navigator.of(context).pushReplacement(
PageRouteBuilder( PageRouteBuilder(
transitionDuration: const Duration(milliseconds: 600), transitionDuration: const Duration(milliseconds: 400),
pageBuilder: (_, __, ___) => const MainScreen(), pageBuilder: (_, __, ___) => const MainScreen(),
transitionsBuilder: (_, animation, __, child) { transitionsBuilder: (_, animation, __, child) {
return FadeTransition(opacity: animation, child: child); return FadeTransition(opacity: animation, child: child);
@@ -63,7 +103,6 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
body: Column( body: Column(
children: [ children: [
const Spacer(flex: 7), const Spacer(flex: 7),
// Image slightly below center
Center( Center(
child: Image.asset( child: Image.asset(
'assets/brand.png', 'assets/brand.png',
@@ -78,7 +117,6 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
}, },
), ),
), ),
// Spinner + text paired together below the image
const SizedBox(height: 8), const SizedBox(height: 8),
const SizedBox( const SizedBox(
width: 40, width: 40,
@@ -90,7 +128,7 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
), ),
const SizedBox(height: 4), const SizedBox(height: 4),
const Text( const Text(
'REVOLT VPN', 'Revolt VPN',
style: TextStyle( style: TextStyle(
color: AppColors.textWhite, color: AppColors.textWhite,
fontSize: 28, fontSize: 28,
@@ -98,6 +136,19 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
letterSpacing: 2.0, letterSpacing: 2.0,
), ),
), ),
const SizedBox(height: 10),
AnimatedSwitcher(
duration: const Duration(milliseconds: 250),
child: Text(
_status,
key: ValueKey(_status),
style: const TextStyle(
color: AppColors.textDim,
fontSize: 13,
letterSpacing: 0.5,
),
),
),
const Spacer(flex: 5), const Spacer(flex: 5),
const SizedBox(height: 12), const SizedBox(height: 12),
], ],
+41 -9
View File
@@ -1,15 +1,32 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:revoltvpn/logic/app_colors.dart'; import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/components/connect_button.dart'; import 'package:revoltvpn/components/connect_button.dart';
import 'package:revoltvpn/components/data_disclosure_dialog.dart';
import 'package:revoltvpn/components/sidebar_drawer.dart'; import 'package:revoltvpn/components/sidebar_drawer.dart';
import 'package:revoltvpn/components/timer_box.dart'; import 'package:revoltvpn/components/timer_box.dart';
import 'package:revoltvpn/components/speed_box.dart'; import 'package:revoltvpn/components/speed_box.dart';
import 'package:revoltvpn/components/status_bar.dart'; import 'package:revoltvpn/components/status_bar.dart';
import 'package:revoltvpn/components/support_button.dart'; import 'package:revoltvpn/components/support_button.dart';
import 'package:revoltvpn/components/rain.dart';
import 'package:revoltvpn/components/lightning.dart';
class MainScreen extends StatelessWidget { class MainScreen extends StatefulWidget {
const MainScreen({super.key}); const MainScreen({super.key});
@override
State<MainScreen> createState() => _MainScreenState();
}
class _MainScreenState extends State<MainScreen> {
@override
void initState() {
super.initState();
// Show data disclosure on first launch — Google Play Data safety requirement.
WidgetsBinding.instance.addPostFrameCallback((_) {
DataDisclosureDialog.showIfFirstLaunch(context);
});
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
@@ -27,8 +44,21 @@ class MainScreen extends StatelessWidget {
), ),
), ),
child: SafeArea( child: SafeArea(
child: Stack( child: LayoutBuilder(
builder: (context, constraints) {
// Proportional positioning — fractions of available height.
// On the reference device (~700 dp) this produces the exact
// original pixel positions (100, 175, 250, 520) and scales
// proportionally on taller/shorter screens.
final h = constraints.maxHeight;
return Stack(
children: [ children: [
// Lightning — behind rain
const Positioned.fill(child: LightningEffect()),
// Rain — behind all UI
const Positioned.fill(child: RainEffect()),
Positioned( Positioned(
top: 0, top: 0,
right: 4, right: 4,
@@ -42,40 +72,42 @@ class MainScreen extends StatelessWidget {
), ),
Positioned( Positioned(
top: 100, // <-- CHANGE ME: timer distance from top top: h * 0.143,
left: 0, left: 0,
right: 0, right: 0,
child: const Center(child: TimerBox()), child: const Center(child: TimerBox()),
), ),
Positioned( Positioned(
top: 175, // <-- CHANGE ME: support button from top top: h * 0.250,
left: 0, left: 0,
right: 0, right: 0,
child: const Center(child: SupportButton()), child: const Center(child: SupportButton()),
), ),
Positioned( Positioned(
top: 250, // <-- CHANGE ME: connect button from top top: h * 0.357,
left: 0, left: 0,
right: 0, right: 0,
child: const Center(child: ConnectButton()), child: const Center(child: ConnectButton()),
), ),
Positioned( Positioned(
top: 520, // <-- CHANGE ME: speed box from top top: h * 0.743,
left: 0, left: 0,
right: 0, right: 0,
child: const Center(child: SpeedBox()), child: const Center(child: SpeedBox()),
), ),
Positioned( const Positioned(
bottom: 16, // <-- CHANGE ME: status bar from bottom bottom: 16,
left: 0, left: 0,
right: 0, right: 0,
child: const StatusBar(), child: StatusBar(),
), ),
], ],
);
},
), ),
), ),
), ),
@@ -0,0 +1,107 @@
import 'package:flutter/material.dart';
import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/logic/power_settings.dart';
/// Keeping the tunnel alive is an OS concern, not an app one.
///
/// Android stops background services of apps that are not exempt from Doze, and
/// removes the whole process group when its task is swiped away. There are
/// exactly two sanctioned ways around that, both requiring one user tap, and
/// neither can be enabled programmatically. This tile surfaces both.
class BackgroundReliabilityTile extends StatefulWidget {
const BackgroundReliabilityTile({super.key});
@override
State<BackgroundReliabilityTile> createState() =>
_BackgroundReliabilityTileState();
}
class _BackgroundReliabilityTileState extends State<BackgroundReliabilityTile>
with WidgetsBindingObserver {
bool? _batteryExempt;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_refresh();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// The exemption is granted in a system dialog, so the only reliable moment
// to re-read it is when we come back to the foreground.
if (state == AppLifecycleState.resumed) _refresh();
}
Future<void> _refresh() async {
final exempt = await PowerSettings.isBatteryOptimisationDisabled();
if (mounted) setState(() => _batteryExempt = exempt);
}
Future<void> _requestExemption() async {
final opened = await PowerSettings.requestDisableBatteryOptimisation();
if (!mounted || opened) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Could not open battery settings on this device.'),
),
);
}
@override
Widget build(BuildContext context) {
final exempt = _batteryExempt;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const ListTile(
title: Text(
'Background reliability',
style: TextStyle(color: AppColors.textWhite, fontSize: 15),
),
subtitle: Text(
'Android stops background apps to save power. Disabling battery '
'optimisation is what keeps the VPN running when the app is closed.',
style: TextStyle(color: AppColors.textDim, fontSize: 12),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
exempt == null
? 'Battery optimisation: checking…'
: exempt
? 'Battery optimisation: disabled for Revolt VPN ✓'
: 'Battery optimisation: still active — the system may '
'stop the VPN in the background.',
style: TextStyle(
color: exempt == true ? AppColors.accent : AppColors.textMuted,
fontSize: 12,
),
),
if (exempt == false) ...[
const SizedBox(height: 8),
OutlinedButton.icon(
onPressed: _requestExemption,
icon: const Icon(Icons.battery_saver),
label: const Text('Allow background activity'),
),
],
],
),
),
],
);
}
}
@@ -0,0 +1,300 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:revoltvpn/logic/ad_manager.dart';
import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/logic/connection_settings.dart';
import 'package:revoltvpn/logic/local_socks_tester.dart';
import 'package:revoltvpn/logic/session_timer.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
class ConnectionModeTile extends StatefulWidget {
final ValueChanged<ConnectionMode>? onChanged;
const ConnectionModeTile({super.key, this.onChanged});
@override
State<ConnectionModeTile> createState() => _ConnectionModeTileState();
}
class _ConnectionModeTileState extends State<ConnectionModeTile> {
ConnectionMode _mode = ConnectionSettings.mode;
bool _testingLocalSocks = false;
bool _reconnecting = false;
LocalSocksTestResult? _lastSocksTest;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
await ConnectionSettings.initialize();
if (mounted) setState(() => _mode = ConnectionSettings.mode);
}
bool _isTunnelBusy(VpnStatus status) {
return status == VpnStatus.connected ||
status == VpnStatus.connecting ||
status == VpnStatus.disconnecting;
}
Future<void> _changeMode(ConnectionMode? next) async {
if (next == null || next == _mode) return;
final vpn = context.read<VpnConnection>();
if (_isTunnelBusy(vpn.status)) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Disconnect before changing connection mode.'),
),
);
return;
}
final saved = await ConnectionSettings.setMode(next);
if (!mounted) return;
if (!saved) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Could not save connection mode.')),
);
return;
}
setState(() {
_mode = next;
_lastSocksTest = null;
});
widget.onChanged?.call(next);
}
// Recovers an orphaned proxy by ending the session and starting a new one,
// exactly as the connect button does. Re-attaching to the session already
// held was the one place a session began without an ad and without a nonce
// to bind it to; a fresh one is the same path everywhere and hands back a
// full window rather than the remainder of a broken one.
Future<void> _reconnect() async {
if (_reconnecting) return;
final vpn = context.read<VpnConnection>();
final timer = context.read<SessionTimer>();
final ad = context.read<AdManager>();
setState(() => _reconnecting = true);
try {
await timer.disconnect();
if (!mounted) return;
final adNonce = await ad.showAd('main');
if (adNonce == null && AdManager.adsEnabled) return;
if (!mounted) return;
if (await vpn.connect(adNonce: adNonce)) {
if (!mounted) return;
await timer.start();
}
} finally {
if (mounted) {
setState(() {
_reconnecting = false;
_lastSocksTest = null;
});
}
}
}
Future<void> _testLocalSocks() async {
if (_testingLocalSocks) return;
final vpn = context.read<VpnConnection>();
if (vpn.status != VpnStatus.connected || !vpn.canTestActiveLocalSocks) {
final orphaned =
vpn.status == VpnStatus.connected && vpn.adoptedRunningRuntime;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
orphaned
? 'Credentials were lost when the app restarted. Reconnect first.'
: 'Connect with SOCKS5 first, then run the local test.',
),
),
);
return;
}
setState(() => _testingLocalSocks = true);
final result = await vpn.testActiveLocalSocks();
if (!mounted) return;
setState(() {
_testingLocalSocks = false;
_lastSocksTest = result;
});
final latency = result.latencyMs == null ? '' : ' (${result.latencyMs} ms)';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('${result.message}$latency')),
);
}
String get _subtitle {
switch (_mode) {
case ConnectionMode.tun:
return 'TUN: Android VPN routing for normal device traffic.';
case ConnectionMode.proxy:
return 'SOCKS5: local authenticated proxy — point apps at 127.0.0.1:<port> with the credentials shown below.';
}
}
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ListTile(
title: const Text(
'Connection mode',
style: TextStyle(color: AppColors.textWhite, fontSize: 15),
),
subtitle: Text(
_subtitle,
style: const TextStyle(color: AppColors.textDim, fontSize: 12),
),
trailing: DropdownButtonHideUnderline(
child: DropdownButton<ConnectionMode>(
value: _mode,
dropdownColor: AppColors.bgCard,
onChanged: _changeMode,
items: const [
DropdownMenuItem(
value: ConnectionMode.tun,
child: Text('TUN'),
),
DropdownMenuItem(
value: ConnectionMode.proxy,
child: Text('SOCKS5'),
),
],
),
),
),
if (_mode == ConnectionMode.proxy) ...[
Consumer<VpnConnection>(
builder: (context, vpn, _) {
final session = vpn.activeSocksSession;
if (session == null) {
// The proxy can be running while this session is unknown:
// Android killed the app process, the foreground service kept
// the listener alive, and its credentials existed only in the
// memory that died with it. Saying "Connect" there would be a
// lie — the user is already connected.
final orphaned = vpn.status == VpnStatus.connected &&
vpn.adoptedRunningRuntime;
if (orphaned) {
return Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'The proxy is still running, but its credentials were '
'lost when the app restarted. Reconnect to get a new '
'endpoint.',
style: TextStyle(
color: AppColors.textMuted,
fontSize: 12,
),
),
const SizedBox(height: 8),
OutlinedButton.icon(
onPressed: _reconnecting ? null : _reconnect,
icon: _reconnecting
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(Icons.refresh),
label: Text(
_reconnecting ? 'Reconnecting…' : 'Reconnect',
),
),
],
),
);
}
return const Padding(
padding: EdgeInsets.fromLTRB(20, 0, 20, 8),
child: Text(
'Connect to start a local SOCKS5 proxy. Credentials change every session.',
style: TextStyle(color: AppColors.textMuted, fontSize: 12),
),
);
}
return Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Proxy: 127.0.0.1:${session.port}',
style: const TextStyle(
color: AppColors.textMuted,
fontSize: 12,
fontFamily: 'monospace',
),
),
Text(
'Username: ${session.username}',
style: const TextStyle(
color: AppColors.textMuted,
fontSize: 12,
fontFamily: 'monospace',
),
),
Text(
'Password: ${session.password}',
style: const TextStyle(
color: AppColors.textMuted,
fontSize: 12,
fontFamily: 'monospace',
),
),
],
),
);
},
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 8),
child: OutlinedButton.icon(
onPressed: _testingLocalSocks ? null : _testLocalSocks,
icon: _testingLocalSocks
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.network_check),
label: Text(
_testingLocalSocks ? 'Testing…' : 'Test Local SOCKS',
),
),
),
if (_lastSocksTest != null)
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 12),
child: Text(
_lastSocksTest!.ok
? 'Last test: OK${_lastSocksTest!.latencyMs == null ? '' : ' · ${_lastSocksTest!.latencyMs} ms'}'
: 'Last test: Failed · ${_lastSocksTest!.message}',
style: const TextStyle(
color: AppColors.textMuted,
fontSize: 12,
),
),
),
],
],
);
}
}
@@ -0,0 +1,57 @@
import 'package:flutter/material.dart';
import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/logic/haptic_settings.dart';
class HapticFeedbackTile extends StatefulWidget {
const HapticFeedbackTile({super.key});
@override
State<HapticFeedbackTile> createState() => _HapticFeedbackTileState();
}
class _HapticFeedbackTileState extends State<HapticFeedbackTile> {
bool _on = HapticSettings.enabled;
bool _saving = false;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
await HapticSettings.initialize();
if (mounted) setState(() => _on = HapticSettings.enabled);
}
Future<void> _toggle(bool value) async {
if (_saving) return;
setState(() {
_saving = true;
_on = value;
});
try {
await HapticSettings.setEnabled(value);
} catch (_) {
if (mounted) setState(() => _on = HapticSettings.enabled);
} finally {
if (mounted) setState(() => _saving = false);
}
}
@override
Widget build(BuildContext context) {
return SwitchListTile(
title: const Text(
'Haptic feedback',
style: TextStyle(color: AppColors.textWhite, fontSize: 15),
),
value: _on,
onChanged: _saving ? null : _toggle,
activeTrackColor: AppColors.accent.withAlpha(80),
activeThumbColor: AppColors.accent,
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
);
}
}
@@ -0,0 +1,57 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:revoltvpn/logic/app_colors.dart';
// ── lib/screens/settings/in_settings/lightning.dart ─────────────────────────
// Toggle for the lightning strike overlay on the main screen.
final ValueNotifier<bool> lightningEnabled = ValueNotifier(true);
Future<void> loadLightningPref() async {
final prefs = await SharedPreferences.getInstance();
lightningEnabled.value = prefs.getBool('lightning_effect_enabled') ?? true;
}
class LightningToggleTile extends StatefulWidget {
const LightningToggleTile({super.key});
@override
State<LightningToggleTile> createState() => _LightningToggleTileState();
}
class _LightningToggleTileState extends State<LightningToggleTile> {
bool _on = true;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
await loadLightningPref();
if (mounted) setState(() => _on = lightningEnabled.value);
}
Future<void> _toggle(bool value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('lightning_effect_enabled', value);
lightningEnabled.value = value;
setState(() => _on = value);
}
@override
Widget build(BuildContext context) {
return SwitchListTile(
title: const Text(
'Lightning effect',
style: TextStyle(color: AppColors.textWhite, fontSize: 15),
),
value: _on,
onChanged: _toggle,
activeTrackColor: AppColors.accent.withAlpha(80),
activeThumbColor: AppColors.accent,
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
);
}
}
@@ -0,0 +1,57 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:revoltvpn/logic/app_colors.dart';
// ── lib/screens/settings/in_settings/rain.dart ──────────────────────────────
// Toggle for the animated rain overlay on the main screen.
final ValueNotifier<bool> rainEnabled = ValueNotifier(true);
Future<void> loadRainPref() async {
final prefs = await SharedPreferences.getInstance();
rainEnabled.value = prefs.getBool('rain_effect_enabled') ?? true;
}
class RainToggleTile extends StatefulWidget {
const RainToggleTile({super.key});
@override
State<RainToggleTile> createState() => _RainToggleTileState();
}
class _RainToggleTileState extends State<RainToggleTile> {
bool _on = true;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
await loadRainPref();
if (mounted) setState(() => _on = rainEnabled.value);
}
Future<void> _toggle(bool value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('rain_effect_enabled', value);
rainEnabled.value = value;
setState(() => _on = value);
}
@override
Widget build(BuildContext context) {
return SwitchListTile(
title: const Text(
'Rain effect',
style: TextStyle(color: AppColors.textWhite, fontSize: 15),
),
value: _on,
onChanged: _toggle,
activeTrackColor: AppColors.accent.withAlpha(80),
activeThumbColor: AppColors.accent,
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
);
}
}
+43
View File
@@ -0,0 +1,43 @@
import 'package:flutter/material.dart';
import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/screens/settings/in_settings/background_reliability.dart';
import 'package:revoltvpn/screens/settings/in_settings/connection_mode.dart';
import 'package:revoltvpn/screens/settings/in_settings/haptic.dart';
import 'package:revoltvpn/screens/settings/in_settings/lightning.dart';
import 'package:revoltvpn/screens/settings/in_settings/rain.dart';
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.bgDeep,
appBar: AppBar(
backgroundColor: AppColors.bgSurface,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back, color: AppColors.textWhite),
onPressed: () => Navigator.of(context).pop(),
),
title: const Text(
'Settings',
style: TextStyle(
color: AppColors.textWhite,
fontWeight: FontWeight.w600,
),
),
),
body: ListView(
padding: const EdgeInsets.symmetric(vertical: 8),
children: const [
ConnectionModeTile(),
BackgroundReliabilityTile(),
HapticFeedbackTile(),
RainToggleTile(),
LightningToggleTile(),
],
),
);
}
}
@@ -0,0 +1,30 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "adc901062556672b4138e18a4dc62a4be8f4b3c2"
channel: "stable"
project_type: plugin
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2
base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2
- platform: android
create_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2
base_revision: adc901062556672b4138e18a4dc62a4be8f4b3c2
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
@@ -0,0 +1,49 @@
## 1.1.5
* Updated the Android runtime dependency to `dev.tfox.fluttervless:xray-android:26.7.11`.
* Rebuilt Android `libxray.so` binaries for `armeabi-v7a`, `arm64-v8a`, `x86`, and `x86_64` against Xray-core `v26.7.11`.
* Fixed Android VPN app routing: all configured blocked apps are now applied to `VpnService.Builder` as disallowed applications and bypass the Xray VPN tunnel.
## 1.1.4
* Updated the Android runtime dependency to `dev.tfox.fluttervless:xray-android:26.6.27.1`.
* Rebuilt Android `libxray.so` binaries for `armeabi-v7a`, `arm64-v8a`, `x86`, and `x86_64` against Xray-core `v26.6.27`.
## 1.1.3
* Updated the Android runtime dependency to `dev.tfox.fluttervless:xray-android:26.6.22`.
* Rebuilt Android `libxray.so` binaries for `armeabi-v7a`, `arm64-v8a`, `x86`, and `x86_64` against Xray-core `v26.6.22`.
## 1.1.2
* Clarified that Android device and emulator runtime binaries are delivered through the main Maven `xray-android` AAR.
* Kept the Android runtime dependency on `dev.tfox.fluttervless:xray-android:26.6.1.1`.
## 1.1.1
* Updated the Android device runtime `libxray.so` binaries to Xray-core `v26.6.1`.
* Kept Android 15+ 16KB page-size linker alignment for the rebuilt ARM binaries.
* Moved Android runtime binaries and geodata into the Maven `dev.tfox.fluttervless:xray-android:26.6.1.1` AAR dependency.
* Included device and emulator ABIs (`armeabi-v7a`, `arm64-v8a`, `x86`, `x86_64`) in the main Maven runtime AAR.
* Removed raw device `jniLibs` and geodata files from the Pub.dev wrapper package; the wrapper now resolves the runtime from Maven Central.
## 1.1.0
* Replaced Android Dart boilerplate with the shared `VlessMethodChannelAdapter`.
* Removed template `getPlatformVersion` scaffold files.
* Moved `flutter_lints` to `dev_dependencies`.
* Removed publish-time dependency overrides from `pubspec.yaml`.
## 1.0.2
* XRay version up
## 1.0.1
* XRay version up
## 1.0.0
* Initial release of the Android implementation for `flutter_vless`.
* Supports VLESS/VMESS protocols using Xray core.
* Implements `VlessPlatform` interface.
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024-2026 13FOX Studio / tfox.dev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,13 @@
flutter_vless_android
Copyright (c) 2024-2026 13FOX Studio / tfox.dev.
This package is the Android implementation of the official flutter_vless
project maintained by 13FOX Studio.
Official project: https://github.com/XIIIFOX/flutter_vless
Official publisher: https://pub.dev/publishers/tfox.dev
Website: https://tfox.dev
Redistributions, forks, and derived packages must preserve the copyright notice
and MIT license notice where required by the license.
@@ -0,0 +1,14 @@
# flutter_vless_android
The Android implementation of the `flutter_vless` plugin.
## Runtime
Android runtime binaries and geodata are delivered through the Maven Central AAR dependency `dev.tfox.fluttervless:xray-android:26.7.11`. This keeps the Pub.dev package lightweight while preserving the same packaged Xray files in the final Android app.
Do not add raw `android/src/main/jniLibs` or geodata files back to this package. Rebuild runtime files in `android_runtime/xray_android/src/main`, publish the Maven AAR, then publish this wrapper package.
## Emulator Support
The current Maven runtime AAR includes `armeabi-v7a`, `arm64-v8a`, `x86`, and `x86_64`.
This covers both physical Android devices and Android emulators.
@@ -0,0 +1,4 @@
Upstream: https://github.com/XIIIFOX/flutter_vless
Tag: v1.1.5
Android package: flutter_vless_android 1.1.5
ReVolt hardening is pre-applied to this vendored package.
@@ -0,0 +1,4 @@
include: package:flutter_lints/flutter.yaml
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
@@ -0,0 +1,9 @@
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
.cxx
@@ -0,0 +1,92 @@
# Xray & Tun2socks Android Build Guide
This guide explains how to build the native libraries (`libxray.so` and `libtun2socks.so`) for the Flutter Vless plugin.
Android runtime files are stored in `android_runtime/xray_android/src/main` and published as the Maven Central AAR `dev.tfox.fluttervless:xray-android`. They are not stored in the `flutter_vless_android` Pub.dev package.
**Key Features:**
- ✅ **Android 15+ Support**: Builds with 16KB page size alignment.
- ✅ **Socket FD Passing**: `tun2socks` is patched to receive the TUN file descriptor via a Unix socket (bypassing Android process restrictions).
## Prerequisites
1. **Go (Golang)**: Version 1.21+ installed.
2. **Android NDK**: Version r27+ (recommended).
3. **macOS/Linux**: Build scripts are designed for Unix-like environments.
## 1. Environment Setup
Export the path to your Android NDK.
```bash
# Example (Adjust path to your NDK installation)
export ANDROID_NDK_HOME="$HOME/Library/Android/sdk/ndk/27.0.12077973"
```
## 2. Build Xray (`libxray.so`)
This script builds the Xray core for Android device and emulator architectures (`arm64-v8a`, `armeabi-v7a`, `x86`, `x86_64`) by default and writes them to the Maven runtime module.
```bash
cd android
chmod +x build_xray.sh
./build_xray.sh
```
## 3. Build Tun2socks (`libtun2socks.so`)
We use a custom Go-based build script (`build_tun2socks.sh`) instead of the old C-based one. This ensures 16KB page alignment and includes the socket-based FD passing logic.
```bash
cd android
chmod +x build_tun2socks.sh
./build_tun2socks.sh
```
## 4. Verification (16KB Page Size)
To confirm that the libraries are compatible with Android 15+ (16KB page size), check the `LOAD` segment alignment using `llvm-readelf`.
```bash
# Check alignment (should be 0x4000)
$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/darwin-x86_64/bin/llvm-readelf -l ../../../android_runtime/xray_android/src/main/jniLibs/arm64-v8a/libtun2socks.so | grep LOAD | head -1
```
**Expected Output:**
```
LOAD ... 0x4000
```
If you see `0x1000`, it is **NOT** compatible with 16KB devices.
## 5. Package The Maven Runtime AAR
The `flutter_vless_android` Pub.dev package consumes the Android device runtime through the Maven artifact:
```text
dev.tfox.fluttervless:xray-android:26.7.11
```
After rebuilding `libxray.so`, `libtun2socks.so`, or the geodata files in `android_runtime/xray_android/src/main`, build the local Maven repository from the repository root:
```bash
tool/build_android_runtime_maven.sh
```
For local Android wrapper or example builds before Maven Central publication, pass the local repository path:
```bash
cd example/android
./gradlew :app:assembleDebug \
-PflutterVlessAndroidRuntimeRepo="$PWD/../../android_runtime/xray_android/build/repo"
```
To upload the signed bundle to Maven Central, configure the Central Portal and signing environment variables documented in `android_runtime/xray_android/README.md`, then run:
```bash
tool/publish_android_runtime_maven.sh
```
## 6. Troubleshooting
- **"bad file descriptor"**: This means the socket FD passing failed. Ensure `XrayVPNService.kt` is correctly sending the FD to the socket path specified in `-sock-path`.
- **"permission denied"**: Ensure the app has permissions to write to the socket file in its private directory.
@@ -0,0 +1,95 @@
group 'com.github.tfox.flutter_vless'
version '1.0'
buildscript {
ext.kotlin_version = '2.2.20'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
rootProject.allprojects {
repositories {
def localRuntimeRepo = findProperty('flutterVlessAndroidRuntimeRepo') ?: System.getenv('FLUTTER_VLESS_ANDROID_RUNTIME_REPO')
if (localRuntimeRepo) {
maven { url uri(localRuntimeRepo) }
}
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
android {
if (project.android.hasProperty("namespace")) {
namespace 'com.github.tfox.flutter_vless'
}
compileSdkVersion 34
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
defaultConfig {
minSdkVersion 23
targetSdkVersion 35
// 16KB page size support for Android 15+
ndk {
abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
}
}
// Configure 16KB page alignment
buildFeatures {
prefab true
}
dependencies {
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-core:5.0.0'
testImplementation 'org.json:json:20240303'
}
testOptions {
unitTests.returnDefaultValues = true
unitTests.all {
testLogging {
events "passed", "skipped", "failed", "standardOut", "standardError"
outputs.upToDateWhen {false}
showStandardStreams = true
}
}
}
sourceSets {
main {
java.srcDirs += 'src/main/kotlin'
}
}
packaging {
jniLibs {
pickFirsts += ['lib/**/libc++_shared.so']
}
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.code.gson:gson:2.10.1'
implementation "dev.tfox.fluttervless:xray-android:${findProperty('flutterVlessXrayRuntimeVersion') ?: '26.7.11'}"
}
@@ -0,0 +1,122 @@
#!/bin/bash
set -euo pipefail
# Build script for tun2socks (Go version) with 16KB page size support
# This is required for Android 15+ compatibility
# Configuration
TUN2SOCKS_REPO="https://github.com/xjasonlyu/tun2socks"
TARGET_DIR="${TARGET_DIR:-../../../android_runtime/xray_android/src/main/jniLibs}"
NDK_PATH="${ANDROID_NDK_HOME:-$HOME/Library/Android/sdk/ndk/28.2.13676358}"
# Check NDK
if [ ! -d "$NDK_PATH" ]; then
echo "Error: NDK not found at $NDK_PATH"
echo "Please export ANDROID_NDK_HOME pointing to your NDK installation."
exit 1
fi
echo "Using NDK at: $NDK_PATH"
case "$(uname -s)" in
Darwin) TOOLCHAIN="${NDK_PATH}/toolchains/llvm/prebuilt/darwin-x86_64" ;;
Linux) TOOLCHAIN="${NDK_PATH}/toolchains/llvm/prebuilt/linux-x86_64" ;;
*) echo "Error: unsupported host OS $(uname -s)"; exit 1 ;;
esac
if [ ! -d "$TOOLCHAIN" ]; then
echo "Error: NDK toolchain not found at $TOOLCHAIN"
echo "Please check ANDROID_NDK_HOME and host OS."
exit 1
fi
# Clone tun2socks if not exists
if [ ! -d "tun2socks-go" ]; then
echo "Cloning tun2socks (Go version)..."
git clone "$TUN2SOCKS_REPO" tun2socks-go
else
echo "tun2socks-go directory exists, pulling latest..."
cd tun2socks-go && git pull && cd ..
fi
# Build Function
build_tun2socks() {
local ARCH_NAME=$1
local GO_ARCH=$2
local GO_ARM=$3
local ANDROID_TARGET=$4
local OUTPUT_DIR="${TARGET_DIR}/${ARCH_NAME}"
echo "Building tun2socks for ${ARCH_NAME}..."
mkdir -p "$OUTPUT_DIR"
export CGO_ENABLED=1
export GOOS=android
export GOARCH=$GO_ARCH
export GOARM=$GO_ARM
export CC="${TOOLCHAIN}/bin/${ANDROID_TARGET}-clang"
export CXX="${TOOLCHAIN}/bin/${ANDROID_TARGET}-clang++"
# Verify compiler exists
if [ ! -f "$CC" ]; then
echo "Error: Compiler not found at $CC"
return 1
fi
cd tun2socks-go
# Build with 16KB page alignment - same flags as xray
go build -v -trimpath -ldflags "-s -w -buildid= -linkmode=external -extldflags '-Wl,-z,max-page-size=16384'" -buildmode=pie -o "../${OUTPUT_DIR}/libtun2socks.so" .
echo "Success: ${OUTPUT_DIR}/libtun2socks.so created."
# Verify 16KB alignment
if [ -x "${TOOLCHAIN}/bin/llvm-readelf" ]; then
echo "Verifying 16KB alignment:"
ALIGN=$("${TOOLCHAIN}/bin/llvm-readelf" -l "../${OUTPUT_DIR}/libtun2socks.so" | grep "LOAD" | head -1 | awk '{print $NF}')
if [ "$ALIGN" = "0x4000" ]; then
echo "Alignment: $ALIGN (16KB) - correct"
else
echo "Warning: alignment is $ALIGN; expected 0x4000"
fi
fi
cd ..
}
# Build for Architectures
echo "Building tun2socks (Go version) with 16KB page size support..."
# ARM64
if [ "${TUN2SOCKS_BUILD_ARM64:-1}" = "1" ]; then
build_tun2socks "arm64-v8a" "arm64" "" "aarch64-linux-android21"
fi
# ARMv7
if [ "${TUN2SOCKS_BUILD_ARMV7:-1}" = "1" ]; then
build_tun2socks "armeabi-v7a" "arm" "7" "armv7a-linux-androideabi21"
fi
# x86 is included in the main runtime AAR.
if [ "${TUN2SOCKS_BUILD_X86:-1}" = "1" ]; then
build_tun2socks "x86" "386" "" "i686-linux-android21"
fi
# x86_64 is included in the main runtime AAR.
if [ "${TUN2SOCKS_BUILD_X86_64:-1}" = "1" ]; then
build_tun2socks "x86_64" "amd64" "" "x86_64-linux-android21"
fi
echo ""
echo "========================================="
echo "Build process finished!"
echo "========================================="
echo ""
echo "Verification:"
echo "Run this command to check all libraries:"
echo ""
echo "for arch in armeabi-v7a arm64-v8a x86 x86_64; do"
echo " echo \"=== \$arch ===\";"
echo " ${TOOLCHAIN}/bin/llvm-readelf -l ${TARGET_DIR}/\$arch/libtun2socks.so | grep LOAD | head -1;"
echo "done"
@@ -0,0 +1,116 @@
#!/bin/bash
set -euo pipefail
# Configuration
XRAY_REPO="https://github.com/XTLS/Xray-core"
XRAY_VERSION="${XRAY_VERSION:-v26.7.11}"
TARGET_DIR="${TARGET_DIR:-../../../android_runtime/xray_android/src/main/jniLibs}"
NDK_PATH="${ANDROID_NDK_HOME:-$HOME/Library/Android/sdk/ndk/28.2.13676358}"
# Check NDK
if [ ! -d "$NDK_PATH" ]; then
echo "Error: NDK not found at $NDK_PATH"
echo "Please export ANDROID_NDK_HOME pointing to your NDK installation."
exit 1
fi
echo "Using NDK at: $NDK_PATH"
# MacOS NDK Toolchain path
case "$(uname -s)" in
Darwin) TOOLCHAIN="${NDK_PATH}/toolchains/llvm/prebuilt/darwin-x86_64" ;;
Linux) TOOLCHAIN="${NDK_PATH}/toolchains/llvm/prebuilt/linux-x86_64" ;;
*) echo "Error: unsupported host OS $(uname -s)"; exit 1 ;;
esac
if [ ! -d "$TOOLCHAIN" ]; then
echo "Error: NDK toolchain not found at $TOOLCHAIN"
echo "Are you on macOS? If not, please edit the script to match your OS."
exit 1
fi
# Clone Xray if not exists
if [ ! -d "Xray-core" ]; then
echo "Cloning Xray-core..."
git clone "$XRAY_REPO"
else
echo "Xray-core directory exists, pulling latest..."
cd Xray-core && git fetch --tags && cd ..
fi
cd Xray-core
git fetch --tags
git checkout "$XRAY_VERSION"
cd ..
# Build Function
build_xray() {
local ARCH_NAME=$1
local GO_ARCH=$2
local GO_ARM=$3
local ANDROID_TARGET=$4
local OUTPUT_DIR="${TARGET_DIR}/${ARCH_NAME}"
echo "Building for ${ARCH_NAME}..."
mkdir -p "$OUTPUT_DIR"
export CGO_ENABLED=1
export GOOS=android
export GOARCH=$GO_ARCH
export GOARM=$GO_ARM
export CC="${TOOLCHAIN}/bin/${ANDROID_TARGET}-clang"
export CXX="${TOOLCHAIN}/bin/${ANDROID_TARGET}-clang++"
# 16KB page size support for Android 15+
export LDFLAGS="-Wl,-z,max-page-size=16384"
# Verify compiler exists
if [ ! -f "$CC" ]; then
echo "Error: Compiler not found at $CC"
# Try older NDK naming convention if new one fails (API 21 is standard)
# Some NDKs use specific API levels in clang name
return 1
fi
cd Xray-core
# Build with 16KB page alignment
if go build -v -trimpath -buildvcs=false \
-gcflags "all=-l=4" \
-ldflags "-X github.com/xtls/xray-core/core.build=${XRAY_VERSION} -s -w -buildid= -checklinkname=0 -linkmode=external -extldflags=${LDFLAGS}" \
-buildmode=pie \
-o "../${OUTPUT_DIR}/libxray.so" ./main; then
echo "Success: ${OUTPUT_DIR}/libxray.so created."
else
echo "Failed to build for ${ARCH_NAME}"
return 1
fi
cd ..
}
# Build for Architectures
# API Level 21 is generally safe for modern Flutter apps (Android 5.0+)
# ARM64
if [ "${XRAY_BUILD_ARM64:-1}" = "1" ]; then
build_xray "arm64-v8a" "arm64" "" "aarch64-linux-android21"
fi
# ARMv7
if [ "${XRAY_BUILD_ARMV7:-1}" = "1" ]; then
build_xray "armeabi-v7a" "arm" "7" "armv7a-linux-androideabi21"
fi
# x86 is included in the main runtime AAR.
if [ "${XRAY_BUILD_X86:-1}" = "1" ]; then
build_xray "x86" "386" "" "i686-linux-android21"
fi
# x86_64 is included in the main runtime AAR.
if [ "${XRAY_BUILD_X86_64:-1}" = "1" ]; then
build_xray "x86_64" "amd64" "" "x86_64-linux-android21"
fi
echo "Build process finished."
@@ -0,0 +1 @@
rootProject.name = 'flutter_vless_android'
@@ -0,0 +1,31 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.github.tfox.flutter_vless">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission
android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"
android:minSdkVersion="34" />
<application>
<service
android:name="com.github.tfox.flutter_vless.xray.service.XrayVPNService"
android:enabled="true"
android:exported="false"
android:foregroundServiceType="specialUse"
android:permission="android.permission.BIND_VPN_SERVICE"
android:process=":RunSoLibXrayDaemon">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="vpn" />
<intent-filter>
<action android:name="android.net.VpnService" />
</intent-filter>
<meta-data
android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
android:value="false" />
</service>
</application>
</manifest>
@@ -0,0 +1,424 @@
// Copyright (c) 2024-2026 13FOX Studio / tfox.dev.
// SPDX-License-Identifier: MIT
package com.github.tfox.flutter_vless
import android.Manifest
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.VpnService
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.github.tfox.flutter_vless.xray.dto.XrayConfig
import com.github.tfox.flutter_vless.xray.service.XrayVPNService
import com.github.tfox.flutter_vless.xray.utils.AppConfigs
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.PluginRegistry
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.util.ArrayList
import java.util.UUID
import java.util.concurrent.Executors
/**
* Main entry point for the Flutter Vless plugin on Android.
*
* ReVolt keeps this bridge deliberately narrow: start/stop, session deadline,
* permission handling, core version and private runtime status only.
*/
class FlutterVlessPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityResultListener, MethodChannel.MethodCallHandler {
private val executor = Executors.newSingleThreadExecutor()
private lateinit var vpnControlMethod: MethodChannel
private lateinit var vpnStatusEvent: EventChannel
private var vpnStatusSink: EventChannel.EventSink? = null
private var activity: Activity? = null
private var xrayReceiver: BroadcastReceiver? = null
private var pendingResult: MethodChannel.Result? = null
private lateinit var context: Context
private var expectedRuntimeToken: String? = null
private var pendingStopResult: MethodChannel.Result? = null
private val mainHandler = Handler(Looper.getMainLooper())
private val stopTimeoutRunnable = Runnable {
val pending = pendingStopResult ?: return@Runnable
pendingStopResult = null
pending.error("STOP_TIMEOUT", "VPN service did not confirm shutdown", null)
}
companion object {
private const val TAG = "FlutterVlessPlugin"
private const val REQUEST_CODE_VPN_PERMISSION = 24
private const val REQUEST_CODE_POST_NOTIFICATIONS = 1
}
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
context = binding.applicationContext
vpnControlMethod = MethodChannel(binding.binaryMessenger, "flutter_vless")
vpnStatusEvent = EventChannel(binding.binaryMessenger, "flutter_vless/status")
vpnControlMethod.setMethodCallHandler(this)
vpnStatusEvent.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
vpnStatusSink = events
registerReceiver()
}
override fun onCancel(arguments: Any?) {
vpnStatusSink = null
unregisterReceiver()
}
})
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"startVless" -> {
if (pendingStopResult != null) {
result.error("STOP_IN_PROGRESS", "VPN shutdown is still in progress", null)
return
}
val config = XrayConfig()
val runtimeToken = UUID.randomUUID().toString()
expectedRuntimeToken = runtimeToken
config.RUNTIME_TOKEN = runtimeToken
config.REMARK = call.argument("remark") ?: ""
config.V2RAY_FULL_JSON_CONFIG = call.argument("config") ?: ""
config.BLOCKED_APPS = call.argument<ArrayList<String>>("blocked_apps") ?: ArrayList()
config.BYPASS_SUBNETS = call.argument<ArrayList<String>>("bypass_subnets") ?: ArrayList()
config.NOTIFICATION_DISCONNECT_BUTTON_NAME = call.argument("notificationDisconnectButtonName") ?: "Disconnect"
if (AppConfigs.NOTIFICATION_ICON_RESOURCE_NAME.isNotEmpty() && AppConfigs.NOTIFICATION_ICON_RESOURCE_TYPE.isNotEmpty()) {
config.NOTIFICATION_ICON_RESOURCE_NAME = AppConfigs.NOTIFICATION_ICON_RESOURCE_NAME
config.NOTIFICATION_ICON_RESOURCE_TYPE = AppConfigs.NOTIFICATION_ICON_RESOURCE_TYPE
val resId = context.resources.getIdentifier(
AppConfigs.NOTIFICATION_ICON_RESOURCE_NAME,
AppConfigs.NOTIFICATION_ICON_RESOURCE_TYPE,
context.packageName
)
config.APPLICATION_ICON = resId
}
if (call.argument<Boolean>("proxy_only") == true) {
AppConfigs.V2RAY_CONNECTION_MODE = AppConfigs.V2RAY_CONNECTION_MODES.PROXY_ONLY
} else {
AppConfigs.V2RAY_CONNECTION_MODE = AppConfigs.V2RAY_CONNECTION_MODES.VPN_TUN
}
try {
val jsonConfig = org.json.JSONObject(config.V2RAY_FULL_JSON_CONFIG)
val outbounds = jsonConfig.optJSONArray("outbounds")
if (outbounds != null && outbounds.length() > 0) {
val firstOutbound = outbounds.getJSONObject(0)
val settings = firstOutbound.optJSONObject("settings")
val vnext = settings?.optJSONArray("vnext")
if (vnext != null && vnext.length() > 0) {
val server = vnext.getJSONObject(0)
config.CONNECTED_V2RAY_SERVER_ADDRESS = server.optString("address", "")
config.CONNECTED_V2RAY_SERVER_PORT = server.optInt("port", 0).toString()
} else if (settings != null) {
config.CONNECTED_V2RAY_SERVER_ADDRESS = settings.optString("address", "")
config.CONNECTED_V2RAY_SERVER_PORT = settings.optInt("port", 0).toString()
}
}
} catch (_: Exception) {
// Optional metadata only; runtime config validation happens downstream.
}
val intent = Intent(context, XrayVPNService::class.java)
intent.putExtra("COMMAND", AppConfigs.V2RAY_SERVICE_COMMANDS.START_SERVICE)
intent.putExtra("V2RAY_CONFIG", config)
intent.putExtra("PROXY_ONLY", call.argument<Boolean>("proxy_only") ?: false)
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
result.success(null)
} catch (e: Exception) {
if (expectedRuntimeToken == runtimeToken) expectedRuntimeToken = null
result.error("START_FAILED", e.message ?: "Could not start VPN service", null)
}
}
"stopVless" -> {
if (pendingStopResult != null) {
result.error("STOP_IN_PROGRESS", "VPN shutdown is already in progress", null)
return
}
// A STOP without a generation token can kill a newer runtime after
// UI/process churn. No token means this bridge owns nothing to stop.
val token = expectedRuntimeToken
if (token == null) {
result.success(null)
return
}
val intent = Intent(context, XrayVPNService::class.java)
intent.putExtra("COMMAND", AppConfigs.V2RAY_SERVICE_COMMANDS.STOP_SERVICE)
intent.putExtra("RUNTIME_TOKEN", token)
try {
context.startService(intent)
pendingStopResult = result
mainHandler.removeCallbacks(stopTimeoutRunnable)
mainHandler.postDelayed(stopTimeoutRunnable, 6_000L)
} catch (e: Exception) {
pendingStopResult = null
mainHandler.removeCallbacks(stopTimeoutRunnable)
result.error("STOP_FAILED", e.message ?: "Could not stop VPN service", null)
}
}
"setSessionDeadline" -> {
val token = expectedRuntimeToken
val remainingSeconds = call.argument<Number>("remainingSeconds")?.toLong()
if (token == null) {
result.error("NO_RUNTIME", "No active runtime token", null)
return
}
if (remainingSeconds == null || remainingSeconds < 0) {
result.error("INVALID_DEADLINE", "remainingSeconds must be non-negative", null)
return
}
val intent = Intent(context, XrayVPNService::class.java)
intent.putExtra("COMMAND", AppConfigs.V2RAY_SERVICE_COMMANDS.UPDATE_SESSION_DEADLINE)
intent.putExtra("RUNTIME_TOKEN", token)
intent.putExtra("REMAINING_SECONDS", remainingSeconds)
try {
context.startService(intent)
result.success(null)
} catch (e: Exception) {
result.error("DEADLINE_FAILED", e.message ?: "Could not update session deadline", null)
}
}
"initializeVless" -> {
val iconResourceName = call.argument<String>("notificationIconResourceName")
val iconResourceType = call.argument<String>("notificationIconResourceType")
if (iconResourceName != null && iconResourceType != null) {
AppConfigs.NOTIFICATION_ICON_RESOURCE_NAME = iconResourceName
AppConfigs.NOTIFICATION_ICON_RESOURCE_TYPE = iconResourceType
}
result.success(null)
}
"getCoreVersion" -> {
executor.submit {
try {
val nativeLibraryDir = context.applicationInfo.nativeLibraryDir
val xrayExecutable = File(nativeLibraryDir, "libxray.so")
if (xrayExecutable.exists()) {
val p = Runtime.getRuntime().exec(arrayOf(xrayExecutable.absolutePath, "-version"))
val reader = BufferedReader(InputStreamReader(p.inputStream))
val version = reader.readLine()
result.success(version)
} else {
result.success("Xray not found")
}
} catch (e: Exception) {
result.success("Error: ${e.message}")
}
}
}
// POST_NOTIFICATIONS without VpnService.prepare, for proxy mode.
"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) {
result.error("NO_ACTIVITY", "Activity is not attached", null)
return
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ActivityCompat.checkSelfPermission(currentActivity, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(currentActivity, arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_CODE_POST_NOTIFICATIONS)
}
}
val request = VpnService.prepare(currentActivity)
if (request != null) {
pendingResult = result
currentActivity.startActivityForResult(request, REQUEST_CODE_VPN_PERMISSION)
} else {
result.success(true)
}
}
else -> result.notImplemented()
}
}
private fun registerReceiver() {
if (activity == null) return
if (xrayReceiver == null) {
xrayReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent == null || vpnStatusSink == null) return
val state = intent.getSerializableExtra("STATE") as? AppConfigs.V2RAY_STATES
val runtimeToken = intent.getStringExtra("RUNTIME_TOKEN").orEmpty()
val runtimeReady = intent.getBooleanExtra("RUNTIME_READY", false)
val duration = intent.getStringExtra("DURATION")
val uploadSpeed = intent.getLongExtra("UPLOAD_SPEED", 0)
val downloadSpeed = intent.getLongExtra("DOWNLOAD_SPEED", 0)
val uploadTraffic = intent.getLongExtra("UPLOAD_TRAFFIC", 0)
val downloadTraffic = intent.getLongExtra("DOWNLOAD_TRAFFIC", 0)
val currentToken = expectedRuntimeToken
if (currentToken == null) {
if (runtimeToken.isNotEmpty() &&
(state == AppConfigs.V2RAY_STATES.V2RAY_CONNECTED ||
state == AppConfigs.V2RAY_STATES.V2RAY_CONNECTING)
) {
expectedRuntimeToken = runtimeToken
} else {
return
}
} else if (runtimeToken != currentToken) {
return
}
val stateName = when (state) {
AppConfigs.V2RAY_STATES.V2RAY_CONNECTED -> if (runtimeReady) "CONNECTED" else "CONNECTING"
AppConfigs.V2RAY_STATES.V2RAY_CONNECTING -> "CONNECTING"
else -> "DISCONNECTED"
}
val data = ArrayList<String>()
data.add(duration ?: "0")
data.add(uploadSpeed.toString())
data.add(downloadSpeed.toString())
data.add(uploadTraffic.toString())
data.add(downloadTraffic.toString())
data.add(stateName)
if (state == AppConfigs.V2RAY_STATES.V2RAY_DISCONNECTED &&
runtimeToken.isNotEmpty() && runtimeToken == expectedRuntimeToken
) {
expectedRuntimeToken = null
mainHandler.removeCallbacks(stopTimeoutRunnable)
pendingStopResult?.success(null)
pendingStopResult = null
}
vpnStatusSink?.success(data)
}
}
}
val filter = IntentFilter(AppConfigs.V2RAY_CONNECTION_INFO)
val currentActivity = activity ?: return
ContextCompat.registerReceiver(
currentActivity,
xrayReceiver,
filter,
ContextCompat.RECEIVER_NOT_EXPORTED,
)
}
private fun unregisterReceiver() {
val currentActivity = activity
val receiver = xrayReceiver
if (currentActivity != null && receiver != null) {
try {
currentActivity.unregisterReceiver(receiver)
} catch (e: Exception) {
Log.w(TAG, "Receiver was already detached during lifecycle cleanup", e)
}
}
xrayReceiver = null
}
private fun failPendingPermission(code: String, message: String) {
pendingResult?.error(code, message, null)
pendingResult = null
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
mainHandler.removeCallbacks(stopTimeoutRunnable)
pendingStopResult?.error("ENGINE_DETACHED", "Flutter engine detached during VPN shutdown", null)
pendingStopResult = null
failPendingPermission("ENGINE_DETACHED", "Flutter engine detached during VPN permission request")
unregisterReceiver()
vpnControlMethod.setMethodCallHandler(null)
vpnStatusEvent.setStreamHandler(null)
executor.shutdown()
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
binding.addActivityResultListener(this)
if (vpnStatusSink != null) {
registerReceiver()
}
}
override fun onDetachedFromActivityForConfigChanges() {
unregisterReceiver()
activity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
activity = binding.activity
binding.addActivityResultListener(this)
if (vpnStatusSink != null) {
registerReceiver()
}
}
override fun onDetachedFromActivity() {
failPendingPermission("NO_ACTIVITY", "Activity detached during VPN permission request")
unregisterReceiver()
activity = null
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
if (requestCode == REQUEST_CODE_VPN_PERMISSION) {
if (resultCode == Activity.RESULT_OK) {
pendingResult?.success(true)
} else {
pendingResult?.success(false)
}
pendingResult = null
return true
}
return false
}
}
@@ -0,0 +1,700 @@
package com.github.tfox.flutter_vless.xray.core
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
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
import com.github.tfox.flutter_vless.xray.dto.XrayConfig
import com.github.tfox.flutter_vless.xray.service.XrayVPNService
import com.github.tfox.flutter_vless.xray.utils.AppConfigs
import com.github.tfox.flutter_vless.xray.utils.Utilities
import org.json.JSONObject
import org.json.JSONArray
import java.io.File
import java.io.FileOutputStream
/**
* Manages the Xray Core process (libxray.so).
*
* This singleton object is responsible for:
* 1. Generating the final Xray configuration file (config.json).
* 2. Injecting necessary inbounds (SOCKS, HTTP, API) into the user-provided config.
* 3. Starting and monitoring the Xray process.
* 4. Collecting traffic statistics via the Xray API.
* 5. Showing the persistent foreground notification.
*/
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
private fun deleteEphemeralConfigOnFailure(filesDir: File) {
try {
val config = File(filesDir, "config.json")
if (config.exists() && !config.delete()) {
Log.w(TAG, "Could not delete failed ephemeral Xray config")
}
} catch (e: Exception) {
Log.w(TAG, "Could not delete failed ephemeral Xray config", e)
}
}
private fun nextFreePort(preferredPort: Int, usedPorts: Set<Int>): Int {
var port = preferredPort
while (usedPorts.contains(port)) {
port++
}
return port
}
private fun uniqueInboundTag(inbounds: JSONArray, preferredTag: String): String {
val tags = mutableSetOf<String>()
for (i in 0 until inbounds.length()) {
val tag = inbounds.optJSONObject(i)?.optString("tag").orEmpty()
if (tag.isNotEmpty()) tags.add(tag)
}
if (!tags.contains(preferredTag)) return preferredTag
var index = 1
var candidate = "${preferredTag}_$index"
while (tags.contains(candidate)) {
index++
candidate = "${preferredTag}_$index"
}
return candidate
}
private fun normalizeRuntimeConfig(value: Any?): Any? {
return when (value) {
is JSONObject -> {
val normalized = JSONObject()
val aliases = mapOf(
"xHTTPSettings" to "xhttpSettings",
"httpUpgradeSettings" to "httpupgradeSettings",
"splitHTTPSettings" to "splithttpSettings"
)
val keys = value.keys()
while (keys.hasNext()) {
val key = keys.next()
if (key == "allowInsecure") continue
val targetKey = aliases[key] ?: key
if (aliases.containsKey(key) && value.has(targetKey)) continue
val normalizedValue = normalizeRuntimeConfig(value.opt(key))
if (targetKey == "network" && normalizedValue is String) {
normalized.put(targetKey, normalizedValue.lowercase())
} else {
normalized.put(targetKey, normalizedValue)
}
}
normalized
}
is JSONArray -> {
val normalized = JSONArray()
for (i in 0 until value.length()) {
normalized.put(normalizeRuntimeConfig(value.opt(i)))
}
normalized
}
else -> value
}
}
private fun normalizeVlessOutbounds(configJson: JSONObject) {
val outbounds = configJson.optJSONArray("outbounds") ?: return
for (i in 0 until outbounds.length()) {
val outbound = outbounds.optJSONObject(i) ?: continue
if (outbound.optString("protocol") != "vless") continue
val settings = outbound.optJSONObject("settings") ?: continue
if (settings.has("vnext")) continue
val address = settings.optString("address")
val id = settings.optString("id")
val port = settings.optInt("port", 0)
if (address.isEmpty() || id.isEmpty() || port <= 0) continue
val user = JSONObject()
user.put("id", id)
user.put("encryption", settings.optString("encryption", "none"))
user.put("flow", settings.optString("flow", ""))
user.put("level", settings.optInt("level", 8))
val server = JSONObject()
server.put("address", address)
server.put("port", port)
server.put("users", JSONArray().put(user))
val normalizedSettings = JSONObject()
normalizedSettings.put("vnext", JSONArray().put(server))
outbound.put("settings", normalizedSettings)
Log.d(TAG, "Normalized flat VLESS outbound settings for $address:$port")
}
}
private fun sanitizeLogPaths(configJson: JSONObject, filesDir: File) {
val log = configJson.optJSONObject("log") ?: return
// The VPN client never needs destination/access logs. A server-provided
// config must not silently enable browsing metadata collection locally.
log.remove("access")
try { File(filesDir, "access.log").delete() } catch (_: Exception) {}
val errorPath = log.optString("error")
if (errorPath.isNotEmpty()) {
log.put("error", File(filesDir, "error.log").absolutePath)
}
}
internal fun buildRuntimeConfigJson(config: XrayConfig, filesDir: File): JSONObject {
val configJson = normalizeRuntimeConfig(
JSONObject(config.V2RAY_FULL_JSON_CONFIG)
) as JSONObject
normalizeVlessOutbounds(configJson)
sanitizeLogPaths(configJson, filesDir)
// ReVolt needs only its authenticated local SOCKS ingress.
val inbounds = configJson.optJSONArray("inbounds") ?: JSONArray()
var secureSocksEnabled = false
for (i in 0 until inbounds.length()) {
val inbound = inbounds.optJSONObject(i) ?: continue
if (inbound.optString("tag") != "revolt-secure-socks") continue
val settings = inbound.optJSONObject("settings")
?: throw IllegalStateException("Secure SOCKS5 settings are missing")
val users = settings.optJSONArray("users")
?: throw IllegalStateException("Secure SOCKS5 users are missing")
val account = users.optJSONObject(0)
?: throw IllegalStateException("Secure SOCKS5 account is missing")
val port = inbound.optInt("port", -1)
if (inbound.optString("protocol") != "socks" ||
inbound.optString("listen") != "127.0.0.1" ||
port <= 1024 || port > 65535 ||
settings.optString("auth") != "password" ||
account.optString("user").isEmpty() ||
account.optString("pass").isEmpty()
) {
throw IllegalStateException("Secure SOCKS5 session is invalid")
}
config.LOCAL_SOCKS5_PORT = port
config.LOCAL_HTTP_PORT = 0
secureSocksEnabled = true
break
}
val usedPorts = mutableSetOf<Int>()
var hasSocksOnLocalPort = false
var hasHttpOnLocalPort = false
for (i in 0 until inbounds.length()) {
val inbound = inbounds.getJSONObject(i)
val protocol = inbound.optString("protocol")
val port = inbound.optInt("port", -1)
if (port > 0) usedPorts.add(port)
if (protocol == "socks" && port == config.LOCAL_SOCKS5_PORT) hasSocksOnLocalPort = true
if (protocol == "http" && port == config.LOCAL_HTTP_PORT) hasHttpOnLocalPort = true
}
if (!hasSocksOnLocalPort) {
if (usedPorts.contains(config.LOCAL_SOCKS5_PORT)) {
config.LOCAL_SOCKS5_PORT = nextFreePort(config.LOCAL_SOCKS5_PORT, usedPorts)
}
val socksInbound = JSONObject()
socksInbound.put("tag", uniqueInboundTag(inbounds, "socks"))
socksInbound.put("port", config.LOCAL_SOCKS5_PORT)
socksInbound.put("listen", "127.0.0.1")
socksInbound.put("protocol", "socks")
socksInbound.put("settings", JSONObject().put("auth", "noauth").put("udp", true))
socksInbound.put(
"sniffing",
JSONObject().put("enabled", true).put("destOverride", JSONArray().put("http").put("tls"))
)
inbounds.put(socksInbound)
usedPorts.add(config.LOCAL_SOCKS5_PORT)
Log.d(TAG, "Injected SOCKS inbound on port ${config.LOCAL_SOCKS5_PORT}")
}
if (!secureSocksEnabled && !hasHttpOnLocalPort) {
if (usedPorts.contains(config.LOCAL_HTTP_PORT)) {
config.LOCAL_HTTP_PORT = nextFreePort(config.LOCAL_HTTP_PORT, usedPorts)
}
val httpInbound = JSONObject()
httpInbound.put("tag", uniqueInboundTag(inbounds, "http"))
httpInbound.put("port", config.LOCAL_HTTP_PORT)
httpInbound.put("listen", "127.0.0.1")
httpInbound.put("protocol", "http")
inbounds.put(httpInbound)
usedPorts.add(config.LOCAL_HTTP_PORT)
Log.d(TAG, "Injected HTTP inbound on port ${config.LOCAL_HTTP_PORT}")
}
return configJson
}
internal fun buildDelayConfigJson(configJson: String, proxyPort: Int, filesDir: File): Pair<JSONObject, Int> {
val delayConfig = XrayConfig(
V2RAY_FULL_JSON_CONFIG = configJson,
LOCAL_SOCKS5_PORT = proxyPort,
LOCAL_HTTP_PORT = proxyPort + 1,
LOCAL_API_PORT = proxyPort + 2
)
val runtimeJson = buildRuntimeConfigJson(delayConfig, filesDir)
return Pair(runtimeJson, delayConfig.LOCAL_SOCKS5_PORT)
}
/**
* Starts the Xray Core process.
*
* @param context The service context (needed for file access and notifications).
* @param config The configuration object containing the user's settings.
* @return true if started successfully, false otherwise.
*/
fun startCore(context: Service, config: XrayConfig): Boolean {
AppConfigs.RUNTIME_READY = false
AppConfigs.V2RAY_STATE = AppConfigs.V2RAY_STATES.V2RAY_CONNECTING
AppConfigs.V2RAY_CONFIG = config
// 1. Prepare the configuration file
val configFilesDir = context.filesDir
try {
val configJson = buildRuntimeConfigJson(config, configFilesDir)
val configFile = File(context.filesDir, "config.json")
configFile.writeText(configJson.toString())
} catch (e: Exception) {
Log.e(TAG, "Failed to write config file", e)
deleteEphemeralConfigOnFailure(configFilesDir)
return false
}
// 2. Find Xray executable (libxray.so)
val nativeLibraryDir = context.applicationInfo.nativeLibraryDir
val xrayExecutable = File(nativeLibraryDir, "libxray.so")
if (!xrayExecutable.exists()) {
Log.e(TAG, "Xray executable not found at ${xrayExecutable.absolutePath}")
deleteEphemeralConfigOnFailure(configFilesDir)
return false
}
// 3. Prepare assets (geoip, geosite)
try {
Utilities.copyAssets(context)
} catch (e: Exception) {
Log.e(TAG, "Failed to prepare Xray assets", e)
deleteEphemeralConfigOnFailure(configFilesDir)
return false
}
// 4. Run Xray
try {
val cmd = listOf(
xrayExecutable.absolutePath,
"-config", File(configFilesDir, "config.json").absolutePath
)
val pb = ProcessBuilder(cmd)
pb.directory(configFilesDir)
pb.redirectErrorStream(true)
// Set environment variables (XRAY_LOCATION_ASSET is crucial for finding geoip/geosite)
val env = pb.environment()
env["XRAY_LOCATION_ASSET"] = Utilities.getUserAssetsPath(context)
xrayProcess = pb.start()
Thread.sleep(300)
if (xrayProcess?.isAlive != true) {
val output = xrayProcess?.inputStream?.bufferedReader()?.readText().orEmpty()
Log.e(TAG, "Xray process exited during startup. Output: $output")
xrayProcess = null
AppConfigs.V2RAY_STATE = AppConfigs.V2RAY_STATES.V2RAY_DISCONNECTED
deleteEphemeralConfigOnFailure(configFilesDir)
return false
}
// config.json contains per-session SOCKS credentials. Xray has
// consumed it after the startup liveness check, so remove it now.
try {
val ephemeralConfig = File(configFilesDir, "config.json")
if (ephemeralConfig.exists() && !ephemeralConfig.delete()) {
Log.w(TAG, "Could not delete ephemeral Xray config")
}
} catch (e: Exception) {
Log.w(TAG, "Could not delete ephemeral Xray config", e)
}
AppConfigs.RUNTIME_READY = false
AppConfigs.V2RAY_STATE = AppConfigs.V2RAY_STATES.V2RAY_CONNECTING
startTimer(context)
showNotification(context, config)
sendStatusBroadcast(context, config)
val process = xrayProcess ?: return false
// Monitor process in a separate thread to detect crash
Thread {
try {
val startedAt = System.currentTimeMillis()
val startupLog = ArrayDeque<String>()
process.inputStream.bufferedReader().use { reader ->
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()
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 ||
AppConfigs.V2RAY_STATE == AppConfigs.V2RAY_STATES.V2RAY_CONNECTING)
) {
// Hold the Android TUN while the core is recovered. Killing
// the VPN service here would allow direct-network fallback.
xrayProcess = null
AppConfigs.RUNTIME_READY = false
AppConfigs.V2RAY_STATE = AppConfigs.V2RAY_STATES.V2RAY_CONNECTING
sendStatusBroadcast(context, config)
if (context is XrayVPNService) {
context.handleXrayCoreExit(config)
} else {
stopCore(context)
}
}
} catch (e: java.io.InterruptedIOException) {
// Expected when stopping
} catch (e: InterruptedException) {
// Expected when stopping
} catch (e: Exception) {
Log.e(TAG, "Error reading xray output", e)
}
}.start()
return true
} 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
}
}
/**
* Stops the Xray Core process and cleans up notifications.
*/
fun stopCore(context: Service, confirmationToken: String? = AppConfigs.V2RAY_CONFIG?.RUNTIME_TOKEN) {
try {
xrayProcess?.destroy()
xrayProcess = null
} catch (e: Exception) {
Log.e(TAG, "Failed to destroy Xray process", e)
}
AppConfigs.RUNTIME_READY = false
AppConfigs.V2RAY_STATE = AppConfigs.V2RAY_STATES.V2RAY_DISCONNECTED
stopTimer()
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(NOTIFICATION_ID)
sendDisconnectedBroadcast(context, confirmationToken.orEmpty())
AppConfigs.V2RAY_CONFIG = null
}
fun markRuntimeConnecting(context: Context, config: XrayConfig) {
if (AppConfigs.V2RAY_CONFIG?.RUNTIME_TOKEN != config.RUNTIME_TOKEN) return
AppConfigs.RUNTIME_READY = false
AppConfigs.V2RAY_STATE = AppConfigs.V2RAY_STATES.V2RAY_CONNECTING
sendStatusBroadcast(context, config)
}
fun markRuntimeReady(context: Service, config: XrayConfig) {
if (AppConfigs.V2RAY_CONFIG?.RUNTIME_TOKEN != config.RUNTIME_TOKEN) return
AppConfigs.RUNTIME_READY = true
AppConfigs.V2RAY_STATE = AppConfigs.V2RAY_STATES.V2RAY_CONNECTED
showNotification(context, config)
sendStatusBroadcast(context, config)
}
fun isXrayRunning(): Boolean {
// Check state instead of process because VPN runs in separate service process
return AppConfigs.V2RAY_STATE == AppConfigs.V2RAY_STATES.V2RAY_CONNECTED ||
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) {
override fun onTick(millisUntilFinished: Long) {
seconds++
val intent = Intent(AppConfigs.V2RAY_CONNECTION_INFO).setPackage(context.packageName)
intent.putExtra("STATE", AppConfigs.V2RAY_STATE)
intent.putExtra("RUNTIME_TOKEN", AppConfigs.V2RAY_CONFIG?.RUNTIME_TOKEN.orEmpty())
intent.putExtra("RUNTIME_READY", AppConfigs.RUNTIME_READY)
intent.putExtra("DURATION", seconds.toString())
intent.putExtra("UPLOAD_SPEED", 0L)
intent.putExtra("DOWNLOAD_SPEED", 0L)
intent.putExtra("UPLOAD_TRAFFIC", 0L)
intent.putExtra("DOWNLOAD_TRAFFIC", 0L)
context.sendBroadcast(intent)
}
override fun onFinish() {}
}.start()
}
private fun stopTimer() {
runOnMain {
countDownTimer?.cancel()
countDownTimer = null
seconds = 0
}
}
fun sendStatusBroadcast(context: Context, config: XrayConfig) {
val intent = Intent(AppConfigs.V2RAY_CONNECTION_INFO).setPackage(context.packageName)
intent.putExtra("STATE", AppConfigs.V2RAY_STATE)
intent.putExtra("RUNTIME_TOKEN", config.RUNTIME_TOKEN)
intent.putExtra("RUNTIME_READY", AppConfigs.RUNTIME_READY)
intent.putExtra("DURATION", seconds.toString())
intent.putExtra("UPLOAD_SPEED", 0L)
intent.putExtra("DOWNLOAD_SPEED", 0L)
intent.putExtra("UPLOAD_TRAFFIC", 0L)
intent.putExtra("DOWNLOAD_TRAFFIC", 0L)
context.sendBroadcast(intent)
}
private fun sendDisconnectedBroadcast(context: Context, runtimeToken: String) {
val intent = Intent(AppConfigs.V2RAY_CONNECTION_INFO).setPackage(context.packageName)
intent.putExtra("STATE", AppConfigs.V2RAY_STATES.V2RAY_DISCONNECTED)
intent.putExtra("RUNTIME_TOKEN", runtimeToken)
intent.putExtra("RUNTIME_READY", false)
intent.putExtra("DURATION", "0")
intent.putExtra("UPLOAD_SPEED", 0L)
intent.putExtra("DOWNLOAD_SPEED", 0L)
intent.putExtra("UPLOAD_TRAFFIC", 0L)
intent.putExtra("DOWNLOAD_TRAFFIC", 0L)
context.sendBroadcast(intent)
}
private fun showNotification(context: Service, config: XrayConfig) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
return
}
}
val channelId = createNotificationChannel(context, config.APPLICATION_NAME)
val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)
launchIntent?.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT else PendingIntent.FLAG_UPDATE_CURRENT
val contentPendingIntent = PendingIntent.getActivity(context, 0, launchIntent, flags)
val stopIntent = Intent(context, XrayVPNService::class.java)
stopIntent.putExtra("COMMAND", AppConfigs.V2RAY_SERVICE_COMMANDS.STOP_SERVICE)
stopIntent.putExtra("RUNTIME_TOKEN", config.RUNTIME_TOKEN)
val stopPendingIntent = PendingIntent.getService(context, 0, stopIntent, flags)
val smallIcon = if (config.APPLICATION_ICON != 0) config.APPLICATION_ICON else android.R.drawable.ic_dialog_info
val builder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(smallIcon)
.setContentTitle(config.REMARK)
.setContentText(if (AppConfigs.RUNTIME_READY) "Connected" else "Connecting")
.addAction(0, config.NOTIFICATION_DISCONNECT_BUTTON_NAME, stopPendingIntent)
.setContentIntent(contentPendingIntent)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setOngoing(true)
.setShowWhen(true)
context.startForeground(NOTIFICATION_ID, builder.build())
}
fun getConnectedV2rayServerDelay(context: Context, url: String): Long {
// Use the configured SOCKS port (default 10807)
val port = AppConfigs.V2RAY_CONFIG?.LOCAL_SOCKS5_PORT ?: 10807
Log.d(TAG, "getConnectedV2rayServerDelay: Testing delay to $url via SOCKS port $port")
return try {
val start = System.currentTimeMillis()
val proxy = java.net.Proxy(java.net.Proxy.Type.SOCKS, java.net.InetSocketAddress("127.0.0.1", port))
val connection = java.net.URL(url).openConnection(proxy) as java.net.HttpURLConnection
connection.connectTimeout = 5000
connection.readTimeout = 5000
connection.requestMethod = "HEAD"
val responseCode = connection.responseCode
val end = System.currentTimeMillis()
val delay = end - start
connection.disconnect()
Log.d(TAG, "getConnectedV2rayServerDelay: Success! Response code: $responseCode, Delay: ${delay}ms")
delay
} catch (e: Exception) {
Log.e(TAG, "getConnectedV2rayServerDelay: Failed to measure delay (VPN may not be running)", e)
-1L
}
}
/**
* Measure delay for a server configuration (when not connected).
* Temporarily starts Xray with the provided config, measures delay, then stops it.
*/
fun getServerDelay(context: Context, configJson: String, url: String): Long {
Log.d(TAG, "getServerDelay: Starting temporary Xray instance")
var tempProcess: Process? = null
try {
// Find a random free port to avoid conflict with running VPN
val freePort = try {
val socket = java.net.ServerSocket(0)
val port = socket.localPort
socket.close()
port
} catch (e: Exception) {
10806 // Fallback
}
val (json, socksPort) = buildDelayConfigJson(configJson, freePort, context.filesDir)
Log.d(TAG, "getServerDelay: Using SOCKS port $socksPort")
// Write temp config file
val tempConfigFile = File(context.filesDir, "temp_delay_config.json")
tempConfigFile.writeText(json.toString())
// Copy assets
Utilities.copyAssets(context)
// Start Xray process
val xrayExecutable = File(context.applicationInfo.nativeLibraryDir, "libxray.so")
if (!xrayExecutable.exists()) {
Log.e(TAG, "getServerDelay: Xray executable not found")
return -1L
}
val cmd = listOf(
xrayExecutable.absolutePath,
"-config", tempConfigFile.absolutePath
)
val pb = ProcessBuilder(cmd)
pb.directory(context.filesDir)
val env = pb.environment()
env["XRAY_LOCATION_ASSET"] = Utilities.getUserAssetsPath(context)
tempProcess = pb.start()
// Wait a bit for Xray to start
Thread.sleep(1000)
// Measure delay
val delay = try {
val start = System.currentTimeMillis()
val proxy = java.net.Proxy(java.net.Proxy.Type.SOCKS, java.net.InetSocketAddress("127.0.0.1", socksPort))
val connection = java.net.URL(url).openConnection(proxy) as java.net.HttpURLConnection
connection.connectTimeout = 5000
connection.readTimeout = 5000
connection.requestMethod = "HEAD"
val responseCode = connection.responseCode
val end = System.currentTimeMillis()
connection.disconnect()
val result = end - start
Log.d(TAG, "getServerDelay: Success! Response code: $responseCode, Delay: ${result}ms")
result
} catch (e: Exception) {
Log.e(TAG, "getServerDelay: Failed to measure delay", e)
-1L
}
// Stop temp process
tempProcess?.destroy()
tempConfigFile.delete()
return delay
} catch (e: Exception) {
Log.e(TAG, "getServerDelay: Error starting temp Xray", e)
tempProcess?.destroy()
return -1L
}
}
private fun createNotificationChannel(context: Context, appName: String): String {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "REVOLT_VPN_SERVICE"
val channelName = "$appName Background Service"
val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW)
channel.lightColor = Color.BLUE
channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(channel)
return channelId
}
return ""
}
}
@@ -0,0 +1,71 @@
package com.github.tfox.flutter_vless.xray.dto
import java.io.Serializable
import java.util.ArrayList
/**
* Data class representing the Xray configuration and app settings.
*
* This class is passed from Flutter to Android and contains:
* 1. The full Xray JSON configuration (V2RAY_FULL_JSON_CONFIG).
* 2. App-specific settings like blocked apps, notification text, etc.
* 3. Connection parameters (server address, ports).
*/
data class XrayConfig(
/** The IP address of the connected server (used to exclude it from VPN routing). */
var CONNECTED_V2RAY_SERVER_ADDRESS: String = "",
/** The port of the connected server. */
var CONNECTED_V2RAY_SERVER_PORT: String = "",
/** Local port for SOCKS5 proxy (default: 10807). used by tun2socks. */
var LOCAL_SOCKS5_PORT: Int = 10807,
/** Local port for HTTP proxy (default: 10808). */
var LOCAL_HTTP_PORT: Int = 10808,
/** Local port for Xray API (stats, etc.) (default: 10809). */
var LOCAL_API_PORT: Int = 10809,
/** Timeout for connections in milliseconds. */
var ALLOWED_TIMEOUT_MS: Int = 0,
/** List of subnets to bypass (not routed through VPN). */
var BYPASS_SUBNETS: ArrayList<String> = ArrayList(),
/** List of app package names to exclude from VPN. */
var BLOCKED_APPS: ArrayList<String> = ArrayList(),
/** The raw Xray configuration JSON string. */
var V2RAY_FULL_JSON_CONFIG: String = "",
/** Whether to enable traffic statistics collection. */
var ENABLE_TRAFFIC_STATICS: Boolean = false,
/** Remark/Name of the server configuration. */
var REMARK: String = "",
/** Name of the application (displayed in notification). */
var APPLICATION_NAME: String = "Flutter Vless",
/** Resource ID of the notification icon. */
var APPLICATION_ICON: Int = 0,
/** Resource name of the notification icon (e.g. "ic_notification"). */
var NOTIFICATION_ICON_RESOURCE_NAME: String = "",
/** Resource type of the notification icon (e.g. "drawable"). */
var NOTIFICATION_ICON_RESOURCE_TYPE: String = "",
/** Text for the disconnect button in the notification. */
var NOTIFICATION_DISCONNECT_BUTTON_NAME: String = "Disconnect",
/** Domain resolution strategy (e.g. "IPIfNonMatch"). */
var DOMAIN_STRATEGY: String = "",
/** Routing domain strategy. */
var ROUTING_DOMAIN_STRATEGY: String = "",
/** Unique generation token used to reject stale native runtime events. */
var RUNTIME_TOKEN: String = ""
) : Serializable
@@ -0,0 +1,827 @@
package com.github.tfox.flutter_vless.xray.service
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.net.VpnService
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.ParcelFileDescriptor
import android.os.SystemClock
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
/**
* Android VPN Service implementation.
*
* This service owns the TUN interface and keeps runtime state generation-scoped.
* Session deadlines are enforced both by an in-process monotonic timer and by
* AlarmManager, while only the non-secret token/deadline pair is persisted.
* Per-session VLESS/SOCKS credentials remain memory-only.
*/
class XrayVPNService : VpnService() {
private var mInterface: ParcelFileDescriptor? = null
private var tun2socksProcess: Process? = null
@Volatile private var isRunning = false
@Volatile private var recoveringXray = false
@Volatile private var recoveringTun2socks = false
private var tun2socksRecoveryAttempt = 0
private var currentConfig: XrayConfig? = null
private var currentProxyOnly = false
private var shuttingDownIntentionally = false
private val deadlineHandler = Handler(Looper.getMainLooper())
private var sessionDeadlineElapsed: Long? = null
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()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) {
if (isRunning && currentConfig != null) return START_REDELIVER_INTENT
// Session credentials intentionally stay memory-only. If Android
// cannot redeliver the original START intent, fail closed instead
// of rebuilding a tunnel from sensitive material stored on disk.
clearPersistedDeadline()
cancelSessionExpiryAlarm()
stopSelf()
return START_NOT_STICKY
}
if (intent.getBooleanExtra(EXTRA_SESSION_EXPIRED, false)) {
enforcePersistedDeadline(intent.getStringExtra("RUNTIME_TOKEN").orEmpty())
return START_NOT_STICKY
}
// 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
}
val command = if (Build.VERSION.SDK_INT >= 33) {
intent.getSerializableExtra("COMMAND", AppConfigs.V2RAY_SERVICE_COMMANDS::class.java)
} else {
@Suppress("DEPRECATION")
intent.getSerializableExtra("COMMAND") as? AppConfigs.V2RAY_SERVICE_COMMANDS
}
if (command == AppConfigs.V2RAY_SERVICE_COMMANDS.STOP_SERVICE) {
val requestedToken = intent.getStringExtra("RUNTIME_TOKEN").orEmpty()
val activeToken = currentConfig?.RUNTIME_TOKEN.orEmpty()
if (requestedToken.isEmpty() ||
(activeToken.isNotEmpty() && requestedToken != activeToken)
) {
Log.w(TAG, "Ignoring STOP_SERVICE without matching runtime generation")
return START_NOT_STICKY
}
stopAll(requestedToken, userRequested = true)
return START_NOT_STICKY
}
if (command == AppConfigs.V2RAY_SERVICE_COMMANDS.UPDATE_SESSION_DEADLINE) {
updateSessionDeadline(intent)
return if (isRunning) START_REDELIVER_INTENT else START_NOT_STICKY
}
createNotificationChannel()
val notification = createNotification("VPN Service Running")
try {
if (Build.VERSION.SDK_INT >= 34) {
startForeground(1, notification, FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
} else {
startForeground(1, notification)
}
} catch (e: Exception) {
Log.e(TAG, "Failed to start foreground", e)
clearPersistedDeadline()
cancelSessionExpiryAlarm()
stopSelf()
return START_NOT_STICKY
}
if (command == AppConfigs.V2RAY_SERVICE_COMMANDS.START_SERVICE) {
val config = if (Build.VERSION.SDK_INT >= 33) {
intent.getSerializableExtra("V2RAY_CONFIG", XrayConfig::class.java)
} else {
@Suppress("DEPRECATION")
intent.getSerializableExtra("V2RAY_CONFIG") as? XrayConfig
}
if (config != null) {
if (XrayCoreManager.isXrayRunning()) {
Log.w(TAG, "Stopping stale Xray core before restart")
XrayCoreManager.stopCore(this)
}
cleanup(clearDeadline = true)
RevoltAlerts.cancelAll(this)
shuttingDownIntentionally = false
currentConfig = config
val proxyOnly = intent.getBooleanExtra("PROXY_ONLY", false)
currentProxyOnly = proxyOnly
armSessionDeadline(config, BOOTSTRAP_SESSION_SECONDS)
if (shuttingDownIntentionally) return START_NOT_STICKY
if (XrayCoreManager.startCore(this, config)) {
if (!proxyOnly) {
setupVpn(config)
} else {
isRunning = true
Log.d(TAG, "Starting in PROXY_ONLY mode")
XrayCoreManager.markRuntimeReady(this, config)
}
} else {
stopAll(config.RUNTIME_TOKEN)
return START_NOT_STICKY
}
} else {
Log.e(TAG, "START_SERVICE missing V2RAY_CONFIG")
stopAll()
return START_NOT_STICKY
}
} else {
stopAll()
return START_NOT_STICKY
}
return START_REDELIVER_INTENT
}
private fun setupVpn(config: XrayConfig) {
try {
if (mInterface != null) {
mInterface?.close()
mInterface = null
}
val builder = Builder()
builder.setSession(config.REMARK)
builder.setMtu(1500)
builder.addAddress("26.26.26.1", 30)
builder.addAddress("fd00:26:26::1", 126)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
builder.setMetered(false)
}
if (config.BLOCKED_APPS.isNotEmpty()) {
throw IllegalStateException("Per-app VPN bypass is disabled in ReVolt")
}
try {
builder.addDisallowedApplication(packageName)
} catch (e: Exception) {
throw IllegalStateException("Failed to exclude ReVolt from its own VPN", e)
}
builder.addRoute("0.0.0.0", 0)
builder.addRoute("::", 0)
try {
builder.addDnsServer("8.8.8.8")
builder.addDnsServer("1.1.1.1")
} catch (e: Exception) {
throw IllegalStateException("Failed to configure VPN DNS", e)
}
mInterface = builder.establish()
?: throw IllegalStateException("Android refused to establish VPN interface")
isRunning = true
runTun2socks(config)
} catch (e: Exception) {
Log.e(TAG, "Failed to setup VPN", e)
stopAll()
}
}
private data class SecureSocksCredentials(
val port: Int,
val username: String,
val password: String,
)
private fun secureSocksCredentials(config: XrayConfig): SecureSocksCredentials? {
val inbounds = try {
JSONObject(config.V2RAY_FULL_JSON_CONFIG).optJSONArray("inbounds")
} catch (_: Exception) {
null
} ?: return null
for (i in 0 until inbounds.length()) {
val inbound = inbounds.optJSONObject(i) ?: continue
if (inbound.optString("tag") != "revolt-secure-socks") continue
if (inbound.optString("protocol") != "socks" ||
inbound.optString("listen") != "127.0.0.1"
) return null
val settings = inbound.optJSONObject("settings") ?: return null
if (settings.optString("auth") != "password") return null
val user = settings.optJSONArray("users")?.optJSONObject(0) ?: return null
val port = inbound.optInt("port", -1)
val username = user.optString("user")
val password = user.optString("pass")
if (port <= 1024 || port > 65535 || username.isEmpty() || password.isEmpty()) {
return null
}
return SecureSocksCredentials(port, username, password)
}
return null
}
private fun scheduleTun2socksRecovery(config: XrayConfig, reason: String) {
if (!isRunning || currentConfig !== config || recoveringTun2socks) return
XrayCoreManager.markRuntimeConnecting(this, config)
recoveringTun2socks = true
val attempt = ++tun2socksRecoveryAttempt
val shift = (attempt - 1).coerceIn(0, 6)
val delayMs = (500L * (1L shl shift)).coerceAtMost(30_000L)
Log.w(TAG, "Scheduling tun2socks recovery attempt $attempt in ${delayMs}ms: $reason")
Thread {
try {
Thread.sleep(delayMs)
} catch (_: InterruptedException) {
recoveringTun2socks = false
return@Thread
}
recoveringTun2socks = false
if (isRunning && currentConfig === config) {
runTun2socks(config)
}
}.start()
}
private fun runTun2socks(config: XrayConfig) {
val tun2socksPath = File(applicationInfo.nativeLibraryDir, "libtun2socks.so").absolutePath
val socketFile = File(filesDir, "sock_path")
if (socketFile.exists() && !socketFile.delete()) {
Log.w(TAG, "Could not delete stale tun2socks socket")
}
val sockPath = socketFile.absolutePath
val secure = secureSocksCredentials(config)
?: throw IllegalStateException("Authenticated ReVolt SOCKS5 inbound missing")
config.LOCAL_SOCKS5_PORT = secure.port
val cmd = arrayListOf(
tun2socksPath,
"-sock-path", sockPath,
"-proxy", "socks5://${secure.username}:${secure.password}@127.0.0.1:${secure.port}",
"-mtu", "1500",
"-loglevel", "debug"
)
Log.d(TAG, "Starting tun2socks with authenticated loopback SOCKS5")
try {
val pb = ProcessBuilder(cmd)
pb.redirectErrorStream(true)
pb.directory(filesDir)
val process = pb.start()
tun2socksProcess = process
Thread {
try {
process.inputStream.bufferedReader().use { reader ->
reader.forEachLine { _ -> }
}
process.waitFor()
if (isRunning && tun2socksProcess === process && currentConfig === config) {
Log.e(TAG, "tun2socks exited unexpectedly; keeping TUN fail-closed")
tun2socksProcess = null
scheduleTun2socksRecovery(config, "process exited")
}
} catch (_: java.io.InterruptedIOException) {
// Expected when stopping
} catch (_: InterruptedException) {
// Expected when stopping
} catch (e: Exception) {
Log.e(TAG, "Error reading tun2socks output", e)
}
}.start()
sendFd(process, config)
} catch (e: Exception) {
Log.e(TAG, "Failed to start tun2socks; keeping TUN fail-closed", e)
scheduleTun2socksRecovery(config, "start failure")
}
}
private fun sendFd(process: Process, config: XrayConfig) {
val fd = mInterface?.fileDescriptor ?: return
val sockFile = File(filesDir, "sock_path").absolutePath
Thread {
var tries = 0
while (tries < 10 && isRunning && tun2socksProcess === process && process.isAlive) {
var localSocket: LocalSocket? = null
try {
Thread.sleep(500)
localSocket = LocalSocket()
localSocket.connect(LocalSocketAddress(sockFile, LocalSocketAddress.Namespace.FILESYSTEM))
val out = localSocket.outputStream
localSocket.setFileDescriptorsForSend(arrayOf(fd))
out.write(32)
out.flush()
localSocket.setFileDescriptorsForSend(null)
localSocket.shutdownOutput()
localSocket.close()
if (isRunning && currentConfig === config && tun2socksProcess === process) {
tun2socksRecoveryAttempt = 0
XrayCoreManager.markRuntimeReady(this, config)
}
return@Thread
} catch (_: Exception) {
tries++
try {
localSocket?.close()
} catch (closeError: Exception) {
Log.w(TAG, "Failed to close tun2socks handoff socket", closeError)
}
}
}
if (isRunning && tun2socksProcess === process) {
Log.e(TAG, "FD handoff failed; recycling tun2socks without dropping TUN")
try {
process.destroy()
} catch (e: Exception) {
Log.w(TAG, "Failed to recycle tun2socks after FD handoff failure", e)
}
}
}.start()
}
fun handleXrayCoreExit(config: XrayConfig) {
if (!isRunning || currentConfig !== config || recoveringXray) return
XrayCoreManager.markRuntimeConnecting(this, config)
recoveringXray = true
Thread {
var attempt = 0
try {
while (isRunning && currentConfig === config) {
attempt++
val shift = (attempt - 1).coerceIn(0, 6)
val delayMs = (500L * (1L shl shift)).coerceAtMost(30_000L)
Log.w(TAG, "Recovering Xray core attempt $attempt in ${delayMs}ms")
Thread.sleep(delayMs)
if (!isRunning || currentConfig !== config) break
if (XrayCoreManager.startCore(this, config)) {
Log.w(TAG, "Xray core recovered without dropping TUN")
if (currentProxyOnly || (mInterface != null && tun2socksProcess?.isAlive == true)) {
XrayCoreManager.markRuntimeReady(this, config)
}
return@Thread
}
}
} catch (_: InterruptedException) {
// Expected when stopping
} finally {
recoveringXray = false
}
}.start()
}
private fun cleanup(clearDeadline: Boolean = true) {
isRunning = false
if (clearDeadline) {
clearSessionDeadline()
} else {
deadlineHandler.removeCallbacks(sessionDeadlineRunnable)
sessionDeadlineElapsed = null
sessionDeadlineToken = null
}
recoveringXray = false
recoveringTun2socks = false
tun2socksRecoveryAttempt = 0
currentProxyOnly = false
AppConfigs.RUNTIME_READY = false
tun2socksProcess?.destroy()
tun2socksProcess = null
try {
mInterface?.close()
mInterface = null
} catch (e: Exception) {
Log.w(TAG, "Failed to close VPN interface during cleanup", e)
}
}
// 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,
) {
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) {
val boundedSeconds = remainingSeconds
.coerceAtLeast(0L)
.coerceAtMost(Long.MAX_VALUE / 1000L)
val delayMs = boundedSeconds * 1000L
val nowEpochMs = System.currentTimeMillis()
val epochDeadline = if (Long.MAX_VALUE - nowEpochMs < delayMs) {
Long.MAX_VALUE
} else {
nowEpochMs + delayMs
}
sessionDeadlineToken = config.RUNTIME_TOKEN
sessionDeadlineElapsed = SystemClock.elapsedRealtime() + delayMs
if (!persistDeadline(config.RUNTIME_TOKEN, epochDeadline) ||
!scheduleSessionExpiryAlarm(config.RUNTIME_TOKEN, epochDeadline)
) {
Log.e(TAG, "Could not arm OS-level session expiry; stopping fail-closed")
stopAll(config.RUNTIME_TOKEN)
return
}
armExpiryWarning(config.RUNTIME_TOKEN, epochDeadline)
deadlineHandler.removeCallbacks(sessionDeadlineRunnable)
if (delayMs == 0L) deadlineHandler.post(sessionDeadlineRunnable)
else deadlineHandler.postDelayed(sessionDeadlineRunnable, delayMs)
}
// 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
// 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()
// 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 - keeps this off SCHEDULE_EXACT_ALARM.
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)
}
// 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) {
val config = currentConfig
if (config == null) {
// Woke a process with no live runtime; nothing 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 < WARNING_FLOOR_MS ||
remaining > RevoltAlerts.WARNING_LEAD_MS + WARNING_SLACK_MS
) {
// 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
}
RevoltAlerts.postExpiryWarning(this)
}
private fun clearSessionDeadline() {
deadlineHandler.removeCallbacks(sessionDeadlineRunnable)
sessionDeadlineElapsed = null
sessionDeadlineToken = null
clearPersistedDeadline()
cancelSessionExpiryAlarm()
cancelSessionWarningAlarm()
RevoltAlerts.cancelExpiryWarning(this)
}
private fun enforceSessionDeadline() {
val token = sessionDeadlineToken ?: return
val deadline = sessionDeadlineElapsed ?: return
val config = currentConfig ?: return
if (config.RUNTIME_TOKEN != token) return
val remaining = deadline - SystemClock.elapsedRealtime()
if (remaining > 0L) {
deadlineHandler.postDelayed(sessionDeadlineRunnable, remaining)
return
}
Log.w(TAG, "Native session deadline expired; stopping runtime fail-closed")
stopAll(token)
}
private fun updateSessionDeadline(intent: Intent) {
val config = currentConfig ?: return
val token = intent.getStringExtra("RUNTIME_TOKEN").orEmpty()
if (token.isEmpty() || token != config.RUNTIME_TOKEN) {
Log.w(TAG, "Ignoring session deadline update for stale runtime generation")
return
}
val remainingSeconds = intent.getLongExtra("REMAINING_SECONDS", -1L)
if (remainingSeconds < 0L) {
Log.w(TAG, "Ignoring invalid negative session deadline")
return
}
armSessionDeadline(config, remainingSeconds)
}
private fun persistDeadline(runtimeToken: String, expiresAtEpochMs: Long): Boolean {
return try {
getSharedPreferences(DEADLINE_PREFS, Context.MODE_PRIVATE)
.edit()
.putString(PREF_RUNTIME_TOKEN, runtimeToken)
.putLong(PREF_EXPIRES_AT_MS, expiresAtEpochMs)
.commit()
} catch (e: Exception) {
Log.e(TAG, "Failed to persist non-secret session deadline", e)
false
}
}
private fun clearPersistedDeadline() {
try {
getSharedPreferences(DEADLINE_PREFS, Context.MODE_PRIVATE)
.edit()
.remove(PREF_RUNTIME_TOKEN)
.remove(PREF_EXPIRES_AT_MS)
.apply()
} catch (e: Exception) {
Log.w(TAG, "Failed to clear persisted session deadline", e)
}
}
private fun enforcePersistedDeadline(alarmToken: String) {
val stored = try {
val prefs = getSharedPreferences(DEADLINE_PREFS, Context.MODE_PRIVATE)
prefs.getString(PREF_RUNTIME_TOKEN, null).orEmpty() to
prefs.getLong(PREF_EXPIRES_AT_MS, 0L)
} catch (e: Exception) {
Log.e(TAG, "Failed to read persisted session deadline", e)
clearPersistedDeadline()
cancelSessionExpiryAlarm()
stopSelf()
return
}
val storedToken = stored.first
val storedDeadline = stored.second
if (alarmToken.isEmpty() || storedToken.isEmpty() || alarmToken != storedToken) {
Log.w(TAG, "Ignoring stale session-expiry alarm")
if (currentConfig == null) stopSelf()
return
}
val remaining = storedDeadline - System.currentTimeMillis()
if (storedDeadline > 0L && remaining > 0L) {
if (!scheduleSessionExpiryAlarm(storedToken, storedDeadline)) {
Log.e(TAG, "Failed to re-arm early session-expiry alarm")
val activeToken = currentConfig?.RUNTIME_TOKEN.orEmpty()
if (activeToken == storedToken) stopAll(storedToken) else stopSelf()
return
}
// An alarm can wake a fresh service process after clock changes.
// If there is no live runtime in this process, do not leave a
// background service instance hanging around just to hold a timer.
if (currentConfig == null) stopSelf()
return
}
Log.w(TAG, "OS session-expiry alarm fired; stopping runtime fail-closed")
val activeToken = currentConfig?.RUNTIME_TOKEN.orEmpty()
if (activeToken.isNotEmpty() && activeToken == storedToken) {
stopAll(storedToken)
} else {
clearPersistedDeadline()
cancelSessionExpiryAlarm()
cancelSessionWarningAlarm()
RevoltAlerts.cancelExpiryWarning(this)
stopForeground(true)
stopSelf()
// This arm does not go through stopAll, so it posts for itself.
RevoltAlerts.postDisconnected(this)
}
}
private fun scheduleSessionExpiryAlarm(runtimeToken: String, expiresAtEpochMs: Long): Boolean {
cancelSessionExpiryAlarm()
if (runtimeToken.isEmpty() || expiresAtEpochMs <= 0L) return false
return try {
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pendingIntent = sessionExpiryPendingIntent(runtimeToken)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
expiresAtEpochMs,
pendingIntent,
)
} catch (_: SecurityException) {
Log.w(TAG, "Exact alarm unavailable; using inexact idle-capable expiry alarm")
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
expiresAtEpochMs,
pendingIntent,
)
}
} else {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, expiresAtEpochMs, pendingIntent)
}
true
} catch (e: Exception) {
Log.e(TAG, "Failed to schedule OS session-expiry alarm", e)
false
}
}
private fun cancelSessionExpiryAlarm() {
try {
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(sessionExpiryPendingIntent(""))
} catch (e: Exception) {
Log.w(TAG, "Failed to cancel session-expiry alarm", e)
}
}
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
// 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)
}
}
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)
}
// 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)
.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)
.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_EXPIRY_REQUEST_CODE, intent, flags)
}
override fun onDestroy() {
if (!shuttingDownIntentionally) {
val confirmationToken = currentConfig?.RUNTIME_TOKEN.orEmpty()
cleanup(clearDeadline = false)
currentConfig = null
XrayCoreManager.stopCore(this, confirmationToken)
stopForeground(true)
}
super.onDestroy()
}
override fun onRevoke() {
stopAll(userRequested = true)
super.onRevoke()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "REVOLT_VPN_SERVICE"
val channelName = "VPN Service"
val channel = android.app.NotificationChannel(
channelId,
channelName,
android.app.NotificationManager.IMPORTANCE_LOW
)
val manager = getSystemService(android.app.NotificationManager::class.java)
manager?.createNotificationChannel(channel)
}
}
private fun createNotification(content: String): android.app.Notification {
val channelId = "REVOLT_VPN_SERVICE"
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
android.app.Notification.Builder(this, channelId)
} else {
@Suppress("DEPRECATION")
android.app.Notification.Builder(this)
}
val icon = resources.getIdentifier("notification_icon", "drawable", packageName)
.takeIf { it != 0 } ?: android.R.drawable.ic_dialog_info
val notification = builder
.setContentTitle("VPN Service")
.setContentText(content)
.setSmallIcon(icon)
.setOngoing(true)
.setAutoCancel(false)
.setOnlyAlertOnce(true)
.build()
notification.flags = notification.flags or
android.app.Notification.FLAG_ONGOING_EVENT or
android.app.Notification.FLAG_NO_CLEAR
return notification
}
companion object {
private const val TAG = "XrayVPNService"
private const val FOREGROUND_SERVICE_TYPE_SPECIAL_USE = 0x40000000
private const val BOOTSTRAP_SESSION_SECONDS = 120L
private const val DEADLINE_PREFS = "revolt_session_deadline"
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
// Drift allowed before a warning is treated as belonging elsewhere.
private const val WARNING_SLACK_MS = 60_000L
// 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.
private const val WARNING_FLOOR_MS = 60_000L
}
}
@@ -0,0 +1,49 @@
package com.github.tfox.flutter_vless.xray.utils
import com.github.tfox.flutter_vless.xray.dto.XrayConfig
import java.io.Serializable
/**
* Global application configuration and state.
*
* This object holds:
* 1. Constants for Intent actions and Service commands.
* 2. Enums for connection states and modes.
* 3. Global state variables (current connection state, active config).
* 4. Static storage for notification icon resources (passed from Flutter).
*/
object AppConfigs {
const val V2RAY_CONNECTION_INFO = "com.github.tfox.flutter_vless.xray.V2RAY_CONNECTION_INFO"
/**
* Commands sent to the XrayVPNService via Intent.
*/
enum class V2RAY_SERVICE_COMMANDS : Serializable {
START_SERVICE, STOP_SERVICE, RESTART_SERVICE, UPDATE_SESSION_DEADLINE
}
/**
* Connection states for the Xray Core.
*/
enum class V2RAY_STATES : Serializable {
V2RAY_CONNECTED, V2RAY_DISCONNECTED, V2RAY_CONNECTING
}
/**
* Connection modes:
* - VPN_TUN: Standard VPN mode using Android VpnService (TUN device).
* - PROXY_ONLY: Runs Xray as a local SOCKS/HTTP proxy without establishing a VPN tunnel.
*/
enum class V2RAY_CONNECTION_MODES : Serializable {
VPN_TUN, PROXY_ONLY
}
var V2RAY_STATE: V2RAY_STATES = V2RAY_STATES.V2RAY_DISCONNECTED
@Volatile var RUNTIME_READY: Boolean = false
var V2RAY_CONFIG: XrayConfig? = null
var V2RAY_CONNECTION_MODE: V2RAY_CONNECTION_MODES = V2RAY_CONNECTION_MODES.VPN_TUN
// Stores the resource name and type for the custom notification icon
var NOTIFICATION_ICON_RESOURCE_NAME: String = ""
var NOTIFICATION_ICON_RESOURCE_TYPE: String = ""
}
@@ -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 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
const val WARNING_LEAD_MS = 5 * 60 * 1000L
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 soon",
"Open the app 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)
// A replacing post must not sound again.
.setOnlyAlertOnce(true)
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 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
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)
}
}
@@ -0,0 +1,62 @@
package com.github.tfox.flutter_vless.xray.utils
import android.content.Context
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
object Utilities {
fun getUserAssetsPath(context: Context): String {
val dir = context.filesDir
if (!dir.exists()) {
dir.mkdirs()
}
return dir.absolutePath
}
fun copyAssets(context: Context) {
val assets = context.assets
val files = assets.list("") ?: return
for (filename in files) {
if (filename == "geoip.dat" || filename == "geosite.dat") {
var `in`: InputStream? = null
var out: OutputStream? = null
try {
`in` = assets.open(filename)
val outFile = File(getUserAssetsPath(context), filename)
out = FileOutputStream(outFile)
copyFile(`in`, out)
} catch (e: IOException) {
e.printStackTrace()
} finally {
if (`in` != null) {
try {
`in`.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
if (out != null) {
try {
out.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}
}
}
@Throws(IOException::class)
private fun copyFile(`in`: InputStream, out: OutputStream) {
val buffer = ByteArray(1024)
var read: Int
while (`in`.read(buffer).also { read = it } != -1) {
out.write(buffer, 0, read)
}
}
}
@@ -0,0 +1,178 @@
package com.github.tfox.flutter_vless.xray.core
import com.github.tfox.flutter_vless.xray.dto.XrayConfig
import java.io.File
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test
class XrayCoreManagerTest {
@Test
fun buildRuntimeConfigJson_keepsSecureSocksAndSanitizesLogs() {
val filesDir = File("build/test-files/runtime-secure")
val config = XrayConfig(
V2RAY_FULL_JSON_CONFIG = runtimeConfig(
extraLog = """
"log": {
"access": "/tmp/access.log",
"error": "/tmp/error.log"
},
""".trimIndent(),
)
)
val output = XrayCoreManager.buildRuntimeConfigJson(config, filesDir)
val log = output.getJSONObject("log")
val inbound = output.getJSONArray("inbounds").getJSONObject(0)
val user = output
.getJSONArray("outbounds")
.getJSONObject(0)
.getJSONObject("settings")
.getJSONArray("vnext")
.getJSONObject(0)
.getJSONArray("users")
.getJSONObject(0)
assertFalse(log.has("access"))
assertEquals(File(filesDir, "error.log").absolutePath, log.getString("error"))
assertEquals("revolt-secure-socks", inbound.getString("tag"))
assertEquals("password", inbound.getJSONObject("settings").getString("auth"))
assertEquals(19080, config.LOCAL_SOCKS5_PORT)
assertEquals(0, config.LOCAL_HTTP_PORT)
assertEquals(vlessEncryption, user.getString("encryption"))
assertEquals("xtls-rprx-vision", user.getString("flow"))
}
@Test
fun buildRuntimeConfigJson_rejectsInvalidSecureSocks() {
val config = XrayConfig(
V2RAY_FULL_JSON_CONFIG = """
{
"inbounds": [
{
"tag": "revolt-secure-socks",
"listen": "127.0.0.1",
"port": 19080,
"protocol": "socks",
"settings": { "auth": "noauth", "users": [] }
}
],
"outbounds": []
}
""".trimIndent()
)
try {
XrayCoreManager.buildRuntimeConfigJson(
config,
File("build/test-files/runtime-invalid-socks"),
)
fail("Invalid secure SOCKS5 configuration must fail closed")
} catch (expected: IllegalStateException) {
assertTrue(expected.message.orEmpty().contains("Secure SOCKS5"))
}
}
@Test
fun buildRuntimeConfigJson_normalizesXrayRuntimeAliases() {
val config = XrayConfig(
V2RAY_FULL_JSON_CONFIG = """
{
"inbounds": [
{
"tag": "revolt-secure-socks",
"listen": "127.0.0.1",
"port": 19080,
"protocol": "socks",
"settings": {
"auth": "password",
"users": [{"user": "runtime-user", "pass": "runtime-pass"}]
}
}
],
"outbounds": [
{
"protocol": "vless",
"settings": {
"vnext": [
{
"address": "example.com",
"port": 443,
"users": [{"id": "11111111-1111-4111-8111-111111111111", "encryption": "none"}]
}
]
},
"streamSettings": {
"network": "XHTTP",
"security": "tls",
"tlsSettings": {"allowInsecure": false, "serverName": "example.com"},
"xHTTPSettings": {"path": "/", "mode": "auto"},
"httpUpgradeSettings": {"path": "/upgrade"},
"splitHTTPSettings": {"path": "/split"}
}
}
]
}
""".trimIndent()
)
val output = XrayCoreManager.buildRuntimeConfigJson(
config,
File("build/test-files/runtime-aliases"),
)
val stream = output
.getJSONArray("outbounds")
.getJSONObject(0)
.getJSONObject("streamSettings")
assertEquals("xhttp", stream.getString("network"))
assertTrue(stream.has("xhttpSettings"))
assertTrue(stream.has("httpupgradeSettings"))
assertTrue(stream.has("splithttpSettings"))
assertFalse(stream.has("xHTTPSettings"))
assertFalse(stream.has("httpUpgradeSettings"))
assertFalse(stream.has("splitHTTPSettings"))
assertFalse(stream.getJSONObject("tlsSettings").has("allowInsecure"))
}
private fun runtimeConfig(extraLog: String = ""): String = """
{
$extraLog
"inbounds": [
{
"tag": "revolt-secure-socks",
"listen": "127.0.0.1",
"port": 19080,
"protocol": "socks",
"settings": {
"auth": "password",
"users": [{"user": "runtime-user", "pass": "runtime-pass"}]
}
}
],
"outbounds": [
{
"tag": "proxy",
"protocol": "vless",
"settings": {
"address": "xhttp.example.com",
"port": 443,
"id": "b94da146-a56e-49d7-af4c-a68c9065cbfd",
"encryption": "$vlessEncryption",
"flow": "xtls-rprx-vision",
"level": 8
},
"streamSettings": {"network": "xhttp", "security": "none"}
}
]
}
""".trimIndent()
private companion object {
const val vlessEncryption =
"mlkem768x25519plus.native.1rtt.100-500-2000.75-0-100.80-0-5000.gtmOXB2AN_r905czmOIr6dKq_YDdEJB8RWGqfsXurns"
}
}
@@ -0,0 +1,13 @@
// Copyright (c) 2024-2026 13FOX Studio / tfox.dev.
// SPDX-License-Identifier: MIT
import 'package:flutter_vless_platform_interface/flutter_vless_platform_interface.dart';
/// Android implementation of [VlessPlatform] using MethodChannel.
class FlutterVlessAndroid extends VlessMethodChannelAdapter {
/// Registers this class as the platform implementation.
/// This is called automatically by Flutter's plugin registry.
static void registerWith() {
VlessPlatform.instance = FlutterVlessAndroid();
}
}
@@ -0,0 +1,31 @@
name: flutter_vless_android
description: Android implementation of the flutter_vless plugin.
version: 1.1.5
homepage: https://tfox.dev
repository: https://github.com/XIIIFOX/flutter_vless
issue_tracker: https://github.com/XIIIFOX/flutter_vless/issues
documentation: https://github.com/XIIIFOX/flutter_vless/blob/main/doc/platform/android.md
funding:
- https://tfox.dev
environment:
sdk: '>=3.4.0 <4.0.0'
flutter: '>=3.3.0'
dependencies:
flutter:
sdk: flutter
flutter_vless_platform_interface: ^1.1.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^6.0.0
flutter:
plugin:
implements: flutter_vless_platform_interface
platforms:
android:
package: com.github.tfox.flutter_vless
pluginClass: FlutterVlessPlugin
+41 -106
View File
@@ -65,22 +65,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.7" version: "3.0.7"
cupertino_icons:
dependency: "direct main"
description:
name: cupertino_icons
sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd"
url: "https://pub.dev"
source: hosted
version: "1.0.9"
dbus:
dependency: transitive
description:
name: dbus
sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270
url: "https://pub.dev"
source: hosted
version: "0.7.12"
fake_async: fake_async:
dependency: transitive dependency: transitive
description: description:
@@ -97,14 +81,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.2.0" version: "2.2.0"
ffi_leak_tracker:
dependency: transitive
description:
name: ffi_leak_tracker
sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
file: file:
dependency: transitive dependency: transitive
description: description:
@@ -134,30 +110,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.2" version: "3.0.2"
flutter_local_notifications:
dependency: "direct main"
description:
name: flutter_local_notifications
sha256: "674173fd3c9eda9d4c8528da2ce0ea69f161577495a9cc835a2a4ecd7eadeb35"
url: "https://pub.dev"
source: hosted
version: "17.2.4"
flutter_local_notifications_linux:
dependency: transitive
description:
name: flutter_local_notifications_linux
sha256: c49bd06165cad9beeb79090b18cd1eb0296f4bf4b23b84426e37dd7c027fc3af
url: "https://pub.dev"
source: hosted
version: "4.0.1"
flutter_local_notifications_platform_interface:
dependency: transitive
description:
name: flutter_local_notifications_platform_interface
sha256: "85f8d07fe708c1bdcf45037f2c0109753b26ae077e9d9e899d55971711a4ea66"
url: "https://pub.dev"
source: hosted
version: "7.2.0"
flutter_secure_storage: flutter_secure_storage:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -202,10 +154,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: flutter_secure_storage_windows name: flutter_secure_storage_windows
sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1" sha256: "3b7c8e068875dfd46719ff57c90d8c459c87f2302ed6b00ff006b3c9fcad1613"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.2.2" version: "4.1.0"
flutter_test: flutter_test:
dependency: "direct dev" dependency: "direct dev"
description: flutter description: flutter
@@ -215,26 +167,25 @@ packages:
dependency: "direct main" dependency: "direct main"
description: description:
name: flutter_vless name: flutter_vless
sha256: aa66ea904e7593cc9b2f8f12c291a3a1f404377125d5cd9faa6399d444f511ab sha256: db242f7fe007d35b4d51c5bd5b895d816f141e4d4afc7038c3b6228c1c66dfb5
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.4" version: "1.1.5"
flutter_vless_android: flutter_vless_android:
dependency: transitive dependency: "direct overridden"
description: description:
name: flutter_vless_android path: "local_packages/flutter_vless_android-1.1.5"
sha256: f2f2c81a410a7341ea05dfe3643b213530be44d6574bc91fa29c0bd417d97ac2 relative: true
url: "https://pub.dev" source: path
source: hosted version: "1.1.5"
version: "1.1.4"
flutter_vless_macos: flutter_vless_macos:
dependency: transitive dependency: transitive
description: description:
name: flutter_vless_macos name: flutter_vless_macos
sha256: "096c21bd9728ee2856325c85f60bc7075dda44f99205dd0baa82e5a1223a62a2" sha256: "2651eda1ae75aff8d0acd74f3d38980c71e7629075eee7aa57e52897479f973f"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.4" version: "1.1.5"
flutter_vless_platform_interface: flutter_vless_platform_interface:
dependency: transitive dependency: transitive
description: description:
@@ -256,14 +207,6 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
google_fonts:
dependency: "direct main"
description:
name: google_fonts
sha256: ba03d03bcaa2f6cb7bd920e3b5027181db75ab524f8891c8bc3aa603885b8055
url: "https://pub.dev"
source: hosted
version: "6.3.3"
google_mobile_ads: google_mobile_ads:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -356,10 +299,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: matcher name: matcher
sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.12.19" version: "0.12.20"
material_color_utilities: material_color_utilities:
dependency: transitive dependency: transitive
description: description:
@@ -372,10 +315,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: meta name: meta
sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.18.0" version: "1.19.0"
nested: nested:
dependency: transitive dependency: transitive
description: description:
@@ -400,6 +343,22 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.2.0" version: "2.2.0"
package_info_plus:
dependency: "direct main"
description:
name: package_info_plus
sha256: cb44f49b6e690fa766f023d5b22cac6b9affe741dd792b6ac7ad4fabe0d7b097
url: "https://pub.dev"
source: hosted
version: "6.0.0"
package_info_plus_platform_interface:
dependency: transitive
description:
name: package_info_plus_platform_interface
sha256: "9bc8ba46813a4cc42c66ab781470711781940780fd8beddd0c3da62506d3a6c6"
url: "https://pub.dev"
source: hosted
version: "2.0.1"
path: path:
dependency: transitive dependency: transitive
description: description:
@@ -409,7 +368,7 @@ packages:
source: hosted source: hosted
version: "1.9.1" version: "1.9.1"
path_provider: path_provider:
dependency: "direct main" dependency: transitive
description: description:
name: path_provider name: path_provider
sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
@@ -456,14 +415,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.3.0" version: "2.3.0"
petitparser:
dependency: transitive
description:
name: petitparser
sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675"
url: "https://pub.dev"
source: hosted
version: "7.0.2"
platform: platform:
dependency: transitive dependency: transitive
description: description:
@@ -609,18 +560,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: test_api name: test_api
sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.11" version: "0.7.12"
timezone:
dependency: transitive
description:
name: timezone
sha256: "2236ec079a174ce07434e89fcd3fcda430025eb7692244139a9cf54fdcf1fc7d"
url: "https://pub.dev"
source: hosted
version: "0.9.4"
typed_data: typed_data:
dependency: transitive dependency: transitive
description: description:
@@ -705,10 +648,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: vector_math name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b sha256: f36f9f3be64c6198714492bb455c11056e33e2f85d9a0b676a48301e44fdcf47
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.2.0" version: "2.4.2"
vm_service: vm_service:
dependency: transitive dependency: transitive
description: description:
@@ -721,10 +664,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: web name: web
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.1" version: "0.5.1"
webview_flutter: webview_flutter:
dependency: transitive dependency: transitive
description: description:
@@ -761,10 +704,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: win32 name: win32
sha256: ba6f4bba816c8d7e3c1580e170f3786d216951cc6b94babc3b814c08d2cb2738 sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "6.3.0" version: "5.15.0"
xdg_directories: xdg_directories:
dependency: transitive dependency: transitive
description: description:
@@ -773,14 +716,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.1.0" version: "1.1.0"
xml:
dependency: transitive
description:
name: xml
sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025"
url: "https://pub.dev"
source: hosted
version: "6.6.1"
yaml: yaml:
dependency: transitive dependency: transitive
description: description:
@@ -790,5 +725,5 @@ packages:
source: hosted source: hosted
version: "3.1.3" version: "3.1.3"
sdks: sdks:
dart: ">=3.10.3 <4.0.0" dart: ">=3.11.0-0 <4.0.0"
flutter: ">=3.38.4" flutter: ">=3.38.4"
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more