23 Commits
Author SHA1 Message Date
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
55 changed files with 4389 additions and 874 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
+66 -91
View File
@@ -1,23 +1,60 @@
# ============================================================================= # =============================================================================
# ReVoltVPN — .gitignore # ReVoltVPN — .gitignore
#
# Type-based by design. This repo ships Dart, Kotlin, XML and image assets;
# everything else is excluded by extension or directory rather than by being
# listed individually. A new file is therefore ignored by default instead of
# needing to be named here, and this file does not enumerate what it protects.
# ============================================================================= # =============================================================================
# ── OS & Editor ──────────────────────────────────────────────────────────── # ── Secrets ────────────────────────────────────────────────────────────────
*.swp *.keystore
.DS_Store *.jks
.atom/ android/key.properties
.history android/admob.properties
.svn/
.java-version
.idea/
.vscode/
# ── Python ───────────────────────────────────────────────────────────────── # Real IPs and IDs. app_config.example.dart is the committed template.
__pycache__/ lib/logic/app_config.dart
# ── File types the shipped app does not contain ────────────────────────────
*.py
*.pyc *.pyc
*.json
*.conf
*.sh
*.txt
*.html
*.zip
*.log
*.class
# ── Flutter / Dart ───────────────────────────────────────────────────────── # ── 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/
@@ -26,97 +63,35 @@ build/
**/build/ **/build/
local_packages/*/build/ local_packages/*/build/
local_packages/*/.dart_tool/ local_packages/*/.dart_tool/
*.dart_tool/
**/doc/api/ **/doc/api/
**/ios/Flutter/.last_build_id **/ios/Flutter/.last_build_id
# ── Android ──────────────────────────────────────────────────────────────── # ── 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/
**/android/app/crashlytics-build.properties **/android/app/crashlytics-build.properties
# ── Secrets & Keystores ─────────────────────────────────────────────────── # ── Editors, tooling & OS ──────────────────────────────────────────────────
*.keystore .claude/
*.jks
android/key.properties
android/admob.properties
# App config (contains real IPs/IDs — use example as template)
lib/logic/app_config.dart
# ── Hivemind server (deployed separately, not part of the Flutter repo) ───
hivemind/
server_hivemind_5_0.py
swarm_watch.py
nginx_hivemind_reality.conf
xray_config_reality.json
swarm_total.json
# ── Internal docs (not for public repo) ────────────────────────────────────
AGENTS.md
FRONTEND_POLISH_REVIEW.md
RUNNING.md
SERVER_DEPLOYMENT.md
SERVER_NOTES.md
SERVER_SETUP.md
REALITY_MIGRATION_PLAN.md
SECURITY_HARDENING.md
VLESS_APP_CONTRACT.md
UI_POSITIONING.md
# ── Technical debt & security audits ───────────────────────────────────────
technical_debt_*.md
technical_debt_*_answer.md
# ── Backups & reference files ──────────────────────────────────────────────
backups/
backup/
hivemind_backup.py
server full picture.txt
server_full_picture_2.txt
00-FULL-REPORT.md
XRAY_CONFIG_REFERENCE.md
# ── Logs & temp ────────────────────────────────────────────────────────────
*.log
*.class
server_picture.sh
# ── AI assistant ───────────────────────────────────────────────────────────
.codewhale/ .codewhale/
.idea/
# ── Dev tool config ──────────────────────────────────────────────────────── .vscode/
.atom/
.history
.svn/
.java-version
.DS_Store
*.swp
__pycache__/
devtools_options.yaml devtools_options.yaml
lib/logic/backup/
scraped
scraped.zip
hivemind.zip
XRAY_AUDIT.md
TECHNICAL_DEBT.md
DOCUMENTATION-ARCHITECTURE-V2.md
config.json
RESILIENCE_REVIEW.md
CONFIG_REVIEW.md
SERVER_SELECTION.md
THREAT_MODEL.md
BUSINESS_MODEL.md
DPI_FINGERPRINT_ANALYSIS.md
CODE_FINGERPRINT_AUDIT.md
CONFERENCE_PREP.md
CONVERSION_CHECKLIST.md
HIVEMIND_INTERNALS.md
#why are you even looking at this file? it's a secret. go away. #why are you even looking at this file? it's a secret. go away.
SERVER_ARCHITECTURE.md whatsthis
turbovpn_play.html
supervpn_play.html
hetzner*
DEPLOYMENT_REPORT_FINAL.md
+269
View File
@@ -5,6 +5,275 @@ Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH
--- ---
## [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 ## [3.2.1] — 2026-08-08
### Google Play compliance ### Google Play compliance
+21 -6
View File
@@ -1,33 +1,48 @@
# Privacy Policy # Privacy Policy
**Last updated:** August 2026 **Last updated:** September 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.
## 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 ## 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. This 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. Session data is stored in memory and deleted 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 our server sees
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.
## Session quotas
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.
Support ads (the "Support us" button) extend an active session by 30 minutes and add extra data allowance.
## Operational logs ## Operational logs
We keep a short in-memory log buffer (last 200 lines) for debugging and server health monitoring. These logs include truncated device IDs (first 8 characters only), session start/stop events, and error messages. Logs never leave the server, are not retained after a server restart, and are only accessible to the server operator via local console. 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. Server logs are written to the systemd journal (`journalctl -u hivemind`). 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 systemd 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 ## What we do not collect
- We do not collect your name, email, or any personal information. - We do not collect your name, email, or any personal information.
- We do not log your internet traffic or browsing history. - 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 or share any data with third parties. - We do not sell or share any data with third parties.
## Ads & Consent ## Ads & Consent
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. 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 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 and blocking abusers) — no packet contents, no destination IPs, no DNS queries. 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 ## Contact
+2 -2
View File
@@ -4,7 +4,7 @@
# ReVoltVPN # ReVoltVPN
A free VPN app for Android. Open-source client, transparent infrastructure. Watch an ad, get 60 minutes of full-speed traffic — no accounts, no logs, no subscriptions. 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.
--- ---
@@ -23,7 +23,7 @@ No email. No password. No payment. The ad pays for the server.
## Protocol ## Protocol
- **Transport** — VLESS over XHTTP (HTTP/2 multiplexed, path-hidden behind `/revolt`) - **Transport** — VLESS over XHTTP (HTTP/2 multiplexed, path-hidden behind `/revolt`)
- **Obfuscation** — Xray Reality spoofs `www.github.com` TLS. To any DPI box, your tunnel looks like a browser visiting GitHub - **Obfuscation** — Xray Reality spoofs a real website's TLS. To any DPI box, your tunnel looks like a browser visiting that website
- **Encryption** — TLS 1.3 with borrowed certificate (Reality). No certbot, no domain ownership required - **Encryption** — TLS 1.3 with borrowed certificate (Reality). No certbot, no domain ownership required
- **API** — Standard HTTPS to a separate domain. Tunnel destination is IP-pinned — domain compromise is DoS only - **API** — Standard HTTPS to a separate domain. Tunnel destination is IP-pinned — domain compromise is DoS only
+10
View File
@@ -0,0 +1,10 @@
include: package:flutter_lints/flutter.yaml
analyzer:
exclude:
- local_packages/**
- whatsthis/**
linter:
rules:
avoid_print: true
+123
View File
@@ -1,4 +1,5 @@
import java.util.Properties import java.util.Properties
import java.io.File
import java.io.FileInputStream import java.io.FileInputStream
plugins { plugins {
@@ -6,6 +7,128 @@ plugins {
id("dev.flutter.flutter-gradle-plugin") id("dev.flutter.flutter-gradle-plugin")
} }
val projectRootDir = rootProject.projectDir.parentFile
val localPropertiesFile = rootProject.file("local.properties")
val localProperties = Properties().apply {
if (localPropertiesFile.exists()) {
localPropertiesFile.inputStream().use { load(it) }
}
}
val flutterSdkPath = localProperties.getProperty("flutter.sdk")
?: throw GradleException("flutter.sdk not set in android/local.properties")
val dartExecutable = File(
flutterSdkPath,
if (System.getProperty("os.name").lowercase().contains("windows")) {
"bin/cache/dart-sdk/bin/dart.exe"
} else {
"bin/cache/dart-sdk/bin/dart"
},
)
val flutterVlessRecoveryPatchScript = File(
projectRootDir,
"tool/patch_flutter_vless_runtime_recovery.dart",
)
val flutterVlessSecureSocksPatchScript = File(
projectRootDir,
"tool/patch_flutter_vless_secure_socks_v2.dart",
)
val flutterVlessSecureSocksScopeFixScript = File(
projectRootDir,
"tool/patch_flutter_vless_secure_socks_scope_fix.dart",
)
val patchFlutterVlessRuntimeRecovery = tasks.register<Exec>("patchFlutterVlessRuntimeRecovery") {
group = "build setup"
description = "Recover stale Xray core and tun2socks socket before restart"
workingDir(projectRootDir)
doFirst {
if (!dartExecutable.isFile) {
throw GradleException("Flutter Dart executable not found: ${dartExecutable.absolutePath}")
}
if (!flutterVlessRecoveryPatchScript.isFile) {
throw GradleException("flutter_vless recovery patch script missing: ${flutterVlessRecoveryPatchScript.absolutePath}")
}
if (!File(projectRootDir, ".dart_tool/package_config.json").isFile) {
throw GradleException("Flutter package metadata missing. Run `flutter pub get` before Android compilation.")
}
}
commandLine(
dartExecutable.absolutePath,
"run",
flutterVlessRecoveryPatchScript.absolutePath,
)
}
val patchFlutterVlessSecureSocks = tasks.register<Exec>("patchFlutterVlessSecureSocks") {
group = "build setup"
description = "Add authenticated ephemeral SOCKS5 and fail-closed process recovery to pinned flutter_vless_android 1.1.5"
workingDir(projectRootDir)
dependsOn(patchFlutterVlessRuntimeRecovery)
doFirst {
if (!dartExecutable.isFile) {
throw GradleException("Flutter Dart executable not found: ${dartExecutable.absolutePath}")
}
if (!flutterVlessSecureSocksPatchScript.isFile) {
throw GradleException("secure SOCKS patch script missing: ${flutterVlessSecureSocksPatchScript.absolutePath}")
}
if (!File(projectRootDir, ".dart_tool/package_config.json").isFile) {
throw GradleException("Flutter package metadata missing. Run `flutter pub get` before Android compilation.")
}
}
commandLine(
dartExecutable.absolutePath,
"run",
flutterVlessSecureSocksPatchScript.absolutePath,
)
}
val patchFlutterVlessSecureSocksScopeFix = tasks.register<Exec>("patchFlutterVlessSecureSocksScopeFix") {
group = "build setup"
description = "Repair the secure Xray process monitor capture without changing stock 1.1.5 runtime sequencing"
workingDir(projectRootDir)
dependsOn(patchFlutterVlessSecureSocks)
doFirst {
if (!dartExecutable.isFile) {
throw GradleException("Flutter Dart executable not found: ${dartExecutable.absolutePath}")
}
if (!flutterVlessSecureSocksScopeFixScript.isFile) {
throw GradleException("secure SOCKS scope fix script missing: ${flutterVlessSecureSocksScopeFixScript.absolutePath}")
}
if (!File(projectRootDir, ".dart_tool/package_config.json").isFile) {
throw GradleException("Flutter package metadata missing. Run `flutter pub get` before Android compilation.")
}
}
commandLine(
dartExecutable.absolutePath,
"run",
flutterVlessSecureSocksScopeFixScript.absolutePath,
)
}
// App compilation and the transitive Android plugin compilation must both wait
// for the pinned runtime patches. Plain `flutter build apk` must behave like CI
// instead of relying on a hidden manual pre-build step.
tasks.configureEach {
if (name == "preBuild") {
dependsOn(patchFlutterVlessSecureSocksScopeFix)
}
}
gradle.projectsEvaluated {
rootProject.findProject(":flutter_vless_android")
?.tasks
?.matching { it.name == "preBuild" }
?.configureEach {
dependsOn(patchFlutterVlessSecureSocksScopeFix)
}
}
android { android {
namespace = "com.paladinvpn.app" namespace = "com.paladinvpn.app"
compileSdk = flutter.compileSdkVersion compileSdk = flutter.compileSdkVersion
+31 -20
View File
@@ -1,19 +1,32 @@
<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"/>
<queries> <!-- Doze/App Standby stop background services of non-exempt apps. A VPN
<intent> cannot stay up without this; Play allows it for VPN functionality. -->
<action android:name="android.intent.action.VIEW"/> <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<data android:scheme="https"/> <!-- OS-level session-expiry alarm. Auto-granted on 31-32; on 33+ the daemon
</intent> falls back to setAndAllowWhileIdle if exact alarms aren't granted. -->
</queries> <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
<application <!-- 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>
<intent>
<action android:name="android.intent.action.VIEW"/>
<data android:scheme="https"/>
</intent>
</queries>
<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"
@@ -21,7 +34,6 @@
android:allowBackup="false" android:allowBackup="false"
android:extractNativeLibs="true"> 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,17 +47,16 @@
android:hardwareAccelerated="true" android:hardwareAccelerated="true"
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>
@@ -1,5 +1,479 @@
package com.paladinvpn.app package com.paladinvpn.app
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.ActivityManager
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.service.XrayVPNService
import com.github.tfox.flutter_vless.xray.utils.AppConfigs
import io.flutter.embedding.android.FlutterActivity 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() 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) {
// Doze and App Standby stop background services of apps that
// are not exempt. A VPN has to be exempt to survive the screen
// going off, so surface the real state rather than guessing.
"isIgnoringBatteryOptimizations" ->
result.success(isIgnoringBatteryOptimizations())
"requestIgnoreBatteryOptimizations" ->
result.success(requestIgnoreBatteryOptimizations())
"setSessionExpiry" -> {
val expiresAtMs = call.argument<Number>("expiresAtMs")?.toLong() ?: 0L
if (expiresAtMs > 0) {
sendSessionExpiryToDaemon(expiresAtMs)
}
result.success(null)
}
// Is our VPN runtime actually alive? The service lives in
// :RunSoLibXrayDaemon, a separate process, so its statics are
// NOT visible here -- this is the only honest check.
"isVpnRuntimeAlive" -> result.success(isVpnRuntimeAlive())
else -> result.notImplemented()
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, notificationChannel)
.setMethodCallHandler { call, result ->
if (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)
} 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()
}
/** True when the OS has exempted us from Doze / App Standby. */
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
}
}
/**
* Opens the system exemption prompt. Android shows this as a single dialog;
* it cannot be granted silently, so the caller must treat a false return as
* "ask again later" rather than a denial.
*/
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) {
// Some OEM builds hide the direct intent; fall back to the list.
try {
startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS))
true
} catch (_: Exception) {
false
}
}
}
/** Pushes the session-expiry deadline to the VPN service process. */
private fun sendSessionExpiryToDaemon(expiresAtMs: Long) {
try {
val intent = Intent(this, XrayVPNService::class.java)
intent.putExtra("SESSION_EXPIRES_AT_MS", expiresAtMs)
startService(intent)
} catch (_: Exception) {
// Daemon not reachable; its persisted expiry still applies.
}
}
/**
* Whether the VPN runtime is genuinely alive.
*
* The Xray service runs in :RunSoLibXrayDaemon, a separate process, so its
* statics (AppConfigs.V2RAY_CONFIG, V2RAY_STATE) are NOT visible from here --
* reading them yields a fresh, empty copy. getRunningAppProcesses still
* returns our *own* processes, which makes it the one reliable signal.
*/
private fun isVpnRuntimeAlive(): Map<String, Any> {
var processAlive = false
try {
val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
processAlive = am.runningAppProcesses
?.any { it.processName.endsWith(VPN_PROCESS_SUFFIX) } == true
} catch (_: Exception) {
}
var vpnTransport = false
try {
val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
vpnTransport = cm.allNetworks.any { network ->
cm.getNetworkCapabilities(network)
?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
}
} catch (_: Exception) {
}
return mapOf(
"processAlive" to processAlive,
"vpnTransport" to vpnTransport,
)
}
/** Removes a notification left behind by a runtime that is no longer alive. */
private fun cancelVpnNotification() {
try {
NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID)
} catch (_: Exception) {
}
}
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
}
// The foreground notification (id 1) is owned by XrayVPNService via
// startForeground. Posting to it from this process while the service is
// gone leaves a frozen countdown nothing will ever update again.
val alive = isVpnRuntimeAlive()["processAlive"] == true
if (!alive) {
cancelVpnNotification()
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?.action = "FROM_DISCONNECT_BTN"
launchIntent?.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or
Intent.FLAG_ACTIVITY_CLEAR_TOP or
Intent.FLAG_ACTIVITY_NEW_TASK
val stopIntent = Intent(this, XrayVPNService::class.java)
stopIntent.putExtra("COMMAND", AppConfigs.V2RAY_SERVICE_COMMANDS.STOP_SERVICE)
val stopPendingIntent = PendingIntent.getService(this, 0, stopIntent, flags)
// Public lock-screen preview: keep the VPN status visible but hide the
// session countdown/speed so usage metadata never reaches the lock screen.
val publicVersion = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.notification_status_icon)
.setContentTitle("Revolt VPN")
.setContentText("VPN is active")
.build()
val builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.notification_status_icon)
.setContentTitle(title)
.setContentText(text)
.addAction(0, actionLabel, stopPendingIntent)
.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 (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 VPN_PROCESS_SUFFIX = ":RunSoLibXrayDaemon"
private const val NOTIFICATION_CHANNEL_ID = "XRAY_SERVICE_CHANNEL"
}
}
@@ -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>
+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
+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
+65 -36
View File
@@ -1,11 +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/screens/settings/in_settings/haptic.dart'; import 'package:revoltvpn/logic/haptic_settings.dart';
class ConnectButton extends StatefulWidget { class ConnectButton extends StatefulWidget {
const ConnectButton({super.key}); const ConnectButton({super.key});
@@ -15,9 +14,9 @@ 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;
@@ -26,16 +25,23 @@ class _ConnectButtonState extends State<ConnectButton>
@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) context.read<VpnConnection>().addListener(_onVpnChanged);
}); });
} }
@override @override
void dispose() { void dispose() {
WidgetsBinding.instance.removeObserver(this);
context.read<VpnConnection>().removeListener(_onVpnChanged); context.read<VpnConnection>().removeListener(_onVpnChanged);
_pulse?.dispose(); _pulse?.dispose();
super.dispose(); super.dispose();
@@ -51,8 +57,21 @@ class _ConnectButtonState extends State<ConnectButton>
} }
} }
Future<void> _handleTap() async { @override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (!mounted) return;
if (state == AppLifecycleState.paused ||
state == AppLifecycleState.detached) {
_pulse?.stop();
} else if (state == AppLifecycleState.resumed) {
final vpn = context.read<VpnConnection>();
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;
@@ -61,31 +80,24 @@ class _ConnectButtonState extends State<ConnectButton>
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;
await timer.disconnect(); await timer.disconnect();
if (hapticEnabled) HapticFeedback.lightImpact(); 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 adWatched = await ad.showAd('main');
if (!adWatched && AdManager.adsEnabled) { if (!adWatched && AdManager.adsEnabled) return;
setState(() => _busy = false);
return;
}
final ok = await vpn.connect(); final ok = await vpn.connect();
if (ok) { if (ok) {
timer.start(); await timer.start();
if (hapticEnabled) HapticFeedback.lightImpact(); HapticSettings.success();
} }
} finally { } finally {
if (mounted) setState(() => _busy = false); if (mounted) setState(() => _busy = false);
@@ -105,15 +117,36 @@ 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;
@@ -128,21 +161,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),
child: Image.asset('assets/brand.png', fit: BoxFit.contain),
),
); );
} }
} }
+5 -4
View File
@@ -64,10 +64,11 @@ class _DisclosureDialog extends StatelessWidget {
const Text( const Text(
'Revolt VPN creates a secure VPN tunnel to protect your ' 'Revolt VPN creates a secure VPN tunnel to protect your '
'traffic. To enforce your data/time quota, we log your ' 'traffic. To enforce your data/time quota, we log your '
'connection duration and data usage, linked to your ' 'connection duration and data usage, linked to a randomly '
'account. We do not log or monitor the content of your ' 'generated device ID — not to your identity. We do not log '
'traffic. We do not share your data with third parties.' 'or monitor the content of your traffic. We do not share '
'If you have more questions, visit our website.', 'your data with third parties. The full policy is in the '
'sidebar menu under "Privacy Policy".',
style: TextStyle( style: TextStyle(
color: AppColors.textMuted, color: AppColors.textMuted,
fontSize: 14, fontSize: 14,
+17 -4
View File
@@ -37,11 +37,24 @@ class _LightningEffectState extends State<LightningEffect>
void initState() { void initState() {
super.initState(); super.initState();
_ctrl = AnimationController(vsync: this, duration: const Duration(milliseconds: 400)); _ctrl = AnimationController(vsync: this, duration: const Duration(milliseconds: 400));
_scheduleNext(); lightningEnabled.addListener(_onEnabledChanged);
if (lightningEnabled.value) _scheduleNext();
}
void _onEnabledChanged() {
if (lightningEnabled.value) {
_scheduleNext();
} else {
_timer?.cancel();
_ctrl.stop();
_bolt = null;
}
if (mounted) setState(() {});
} }
@override @override
void dispose() { void dispose() {
lightningEnabled.removeListener(_onEnabledChanged);
_timer?.cancel(); _timer?.cancel();
_ctrl.dispose(); _ctrl.dispose();
super.dispose(); super.dispose();
@@ -54,13 +67,13 @@ class _LightningEffectState extends State<LightningEffect>
} }
void _strike() { void _strike() {
if (!mounted) return; if (!mounted || !lightningEnabled.value) return;
_bolt = LightningBolt.random(_random); _bolt = LightningBolt.random(_random);
_ctrl.forward(from: 0.0); _ctrl.forward(from: 0.0);
if (_random.nextDouble() < widget.doubleChance) { if (_random.nextDouble() < widget.doubleChance) {
Future.delayed(const Duration(milliseconds: 120), () { Future.delayed(const Duration(milliseconds: 120), () {
if (mounted) { if (mounted && lightningEnabled.value) {
_bolt = LightningBolt.random(_random); _bolt = LightningBolt.random(_random);
_ctrl.forward(from: 0.0); _ctrl.forward(from: 0.0);
} }
@@ -78,7 +91,7 @@ class _LightningEffectState extends State<LightningEffect>
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (!lightningEnabled) return const SizedBox.shrink(); if (!lightningEnabled.value) return const SizedBox.shrink();
return AnimatedBuilder( return AnimatedBuilder(
animation: _ctrl, animation: _ctrl,
builder: (_, child) { builder: (_, child) {
-93
View File
@@ -1,93 +0,0 @@
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class VpnNotificationManager {
static final FlutterLocalNotificationsPlugin _plugin =
FlutterLocalNotificationsPlugin();
static bool _initialized = false;
static String? _lastTimeLeft;
static String? _lastSpeedKbps;
// Android channels are immutable — bump this if settings change.
static const _channelId = 'revolt_vpn_v4';
static const _channelName = 'Revolt VPN';
static const _notifId = 888;
static Future<void> init() async {
if (_initialized) return;
const androidSettings =
AndroidInitializationSettings('@drawable/notification_icon');
const initSettings = InitializationSettings(android: androidSettings);
await _plugin.initialize(initSettings);
if (Platform.isAndroid) {
final androidPlugin = _plugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>();
await androidPlugin?.requestNotificationsPermission();
}
_initialized = true;
}
static Future<void> showOrUpdateStatus({
required String timeLeft,
required String speedKbps,
}) async {
if (timeLeft == _lastTimeLeft && speedKbps == _lastSpeedKbps) return;
_lastTimeLeft = timeLeft;
_lastSpeedKbps = speedKbps;
if (!_initialized) await init();
final bodyText = 'Time: $timeLeft • $speedKbps';
final bigPictureStyle = BigPictureStyleInformation(
const DrawableResourceAndroidBitmap('notification_banner'),
largeIcon: const DrawableResourceAndroidBitmap('notification_icon'),
contentTitle: 'Revolt VPN',
summaryText: bodyText,
htmlFormatContentTitle: false,
htmlFormatSummaryText: false,
);
final androidDetails = AndroidNotificationDetails(
_channelId,
_channelName,
channelDescription: 'Session timer and speed',
importance: Importance.low,
priority: Priority.low,
ongoing: true,
autoCancel: false,
playSound: false,
enableVibration: false,
showWhen: false,
visibility: NotificationVisibility.public,
usesChronometer: false,
category: AndroidNotificationCategory.service,
colorized: true,
color: const ui.Color(0xFF0D1117),
styleInformation: bigPictureStyle,
);
final details = NotificationDetails(android: androidDetails);
try {
await _plugin.show(_notifId, _channelName, bodyText, details);
} catch (e) {
_initialized = false;
try {
await init();
await _plugin.show(_notifId, _channelName, bodyText, details);
} catch (_) {}
}
}
static Future<void> cancel() async {
if (!_initialized) return;
await _plugin.cancel(_notifId);
}
}
+39 -23
View File
@@ -36,6 +36,7 @@ class _RainEffectState extends State<RainEffect>
late final Ticker _ticker; late final Ticker _ticker;
final _drops = <_Drop>[]; final _drops = <_Drop>[];
final _random = Random(); final _random = Random();
final _repaint = ValueNotifier<int>(0);
Duration _last = Duration.zero; Duration _last = Duration.zero;
// Lifecycle // Lifecycle
@@ -44,47 +45,63 @@ class _RainEffectState extends State<RainEffect>
void initState() { void initState() {
super.initState(); super.initState();
for (int i = 0; i < widget.dropCount; i++) { for (int i = 0; i < widget.dropCount; i++) {
_drops.add(_Drop.spawn(_random, widget.minLength, widget.maxLength)); _drops.add(
_Drop.spawn(_random, widget.minLength, widget.maxLength, widget.color));
} }
_ticker = createTicker(_onTick)..start(); _ticker = createTicker(_onTick);
rainEnabled.addListener(_onEnabledChanged);
if (rainEnabled.value) _ticker.start();
} }
@override @override
void dispose() { void dispose() {
rainEnabled.removeListener(_onEnabledChanged);
_ticker.dispose(); _ticker.dispose();
_repaint.dispose();
super.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 // Tick
void _onTick(Duration now) { void _onTick(Duration now) {
double dt = 0.016; // ~60 fps fallback on first tick double dt = 0.016; // ~60 fps fallback on first tick
if (_last != Duration.zero) { if (_last != Duration.zero) {
dt = (now - _last).inMicroseconds / 1000000.0; dt = (now - _last).inMicroseconds / 1000000.0;
dt = dt.clamp(0.0, 0.1); dt = dt.clamp(0.0, 0.1);
} }
_last = now; _last = now;
for (final d in _drops) { for (final d in _drops) {
d.y += d.speed * dt; d.y += d.speed * dt;
if (d.y > 1.08) { if (d.y > 1.08) {
d.spawn(_random, widget.minLength, widget.maxLength); d.spawn(_random, widget.minLength, widget.maxLength, widget.color);
d.y = -0.06 - _random.nextDouble() * 0.08; d.y = -0.06 - _random.nextDouble() * 0.08;
} }
} }
setState(() {}); _repaint.value++;
} }
// Build // Build
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (!rainEnabled) return const SizedBox.shrink(); if (!rainEnabled.value) return const SizedBox.shrink();
return CustomPaint( return CustomPaint(
painter: _RainPainter( painter: _RainPainter(
drops: _drops, drops: _drops,
color: widget.color,
windDrift: widget.windDrift, windDrift: widget.windDrift,
repaint: _repaint,
), ),
size: Size.infinite, size: Size.infinite,
); );
@@ -96,37 +113,37 @@ class _RainEffectState extends State<RainEffect>
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
class _Drop { class _Drop {
double x; double x;
double y; double y;
double speed; double speed;
double length; double length;
double opacity; Color color;
_Drop({ _Drop({
required this.x, required this.x,
required this.y, required this.y,
required this.speed, required this.speed,
required this.length, required this.length,
required this.opacity, required this.color,
}); });
/// Create a drop at a random position anywhere on screen. /// Create a drop at a random position anywhere on screen.
factory _Drop.spawn(Random r, double minLen, double maxLen) { factory _Drop.spawn(Random r, double minLen, double maxLen, Color base) {
return _Drop( return _Drop(
x: r.nextDouble(), x: r.nextDouble(),
y: r.nextDouble(), y: r.nextDouble(),
speed: 0.30 + r.nextDouble() * 0.55, speed: 0.30 + r.nextDouble() * 0.55,
length: minLen + r.nextDouble() * (maxLen - minLen), length: minLen + r.nextDouble() * (maxLen - minLen),
opacity: 0.05 + r.nextDouble() * 0.12, color: base.withAlpha(((0.05 + r.nextDouble() * 0.12) * 255).round()),
); );
} }
/// Re-randomise all properties (call when recycling a drop to the top). /// Re-randomise all properties (call when recycling a drop to the top).
void spawn(Random r, double minLen, double maxLen) { void spawn(Random r, double minLen, double maxLen, Color base) {
x = r.nextDouble(); x = r.nextDouble();
speed = 0.30 + r.nextDouble() * 0.55; speed = 0.30 + r.nextDouble() * 0.55;
length = minLen + r.nextDouble() * (maxLen - minLen); length = minLen + r.nextDouble() * (maxLen - minLen);
opacity = 0.05 + r.nextDouble() * 0.12; color = base.withAlpha(((0.05 + r.nextDouble() * 0.12) * 255).round());
} }
} }
@@ -136,14 +153,13 @@ class _Drop {
class _RainPainter extends CustomPainter { class _RainPainter extends CustomPainter {
final List<_Drop> drops; final List<_Drop> drops;
final Color color;
final double windDrift; final double windDrift;
_RainPainter({ _RainPainter({
required this.drops, required this.drops,
required this.color,
required this.windDrift, required this.windDrift,
}); required Listenable repaint,
}) : super(repaint: repaint);
@override @override
void paint(Canvas canvas, Size size) { void paint(Canvas canvas, Size size) {
@@ -157,11 +173,11 @@ class _RainPainter extends CustomPainter {
final ex = sx - windDrift; // slight leftward slant final ex = sx - windDrift; // slight leftward slant
final ey = sy + d.length; final ey = sy + d.length;
paint.color = color.withAlpha((d.opacity * 255).round()); paint.color = d.color;
canvas.drawLine(Offset(sx, sy), Offset(ex, ey), paint); canvas.drawLine(Offset(sx, sy), Offset(ex, ey), paint);
} }
} }
@override @override
bool shouldRepaint(_RainPainter old) => true; // always animating bool shouldRepaint(_RainPainter old) => false; // repaint listenable drives frames
} }
+13 -9
View File
@@ -12,9 +12,7 @@ class SettingsButton extends StatelessWidget {
// Opens the settings page sliding in from the right — matches the // Opens the settings page sliding in from the right — matches the
// sidebar end-drawer animation so it feels like one continuous motion. // sidebar end-drawer animation so it feels like one continuous motion.
static void open(BuildContext context) { static PageRoute<void> _route() => PageRouteBuilder<void>(
Navigator.of(context).push(
PageRouteBuilder(
transitionDuration: const Duration(milliseconds: 300), transitionDuration: const Duration(milliseconds: 300),
reverseTransitionDuration: const Duration(milliseconds: 250), reverseTransitionDuration: const Duration(milliseconds: 250),
pageBuilder: (_, __, ___) => const SettingsScreen(), pageBuilder: (_, __, ___) => const SettingsScreen(),
@@ -23,15 +21,21 @@ class SettingsButton extends StatelessWidget {
position: Tween<Offset>( position: Tween<Offset>(
begin: const Offset(1.0, 0.0), begin: const Offset(1.0, 0.0),
end: Offset.zero, end: Offset.zero,
).animate(CurvedAnimation( ).animate(
parent: animation, CurvedAnimation(parent: animation, curve: Curves.easeOut),
curve: Curves.easeOut, ),
)),
child: child, 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 @override
+11 -2
View File
@@ -1,3 +1,4 @@
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart'; import 'package:package_info_plus/package_info_plus.dart';
import 'package:revoltvpn/logic/app_colors.dart'; import 'package:revoltvpn/logic/app_colors.dart';
@@ -126,8 +127,9 @@ class _SidebarDrawerState extends State<SidebarDrawer> {
icon: Icons.settings, icon: Icons.settings,
label: 'Settings', label: 'Settings',
onTap: () { onTap: () {
final navigator = Navigator.of(context, rootNavigator: true);
Navigator.of(context).pop(); Navigator.of(context).pop();
SettingsButton.open(context); SettingsButton.openWithNavigator(navigator);
}, },
), ),
@@ -135,8 +137,15 @@ class _SidebarDrawerState extends State<SidebarDrawer> {
icon: Icons.system_update_alt, icon: Icons.system_update_alt,
label: 'Check for updates', label: 'Check for updates',
onTap: () { onTap: () {
final navigator = Navigator.of(context, rootNavigator: true);
final messenger = ScaffoldMessenger.of(context);
Navigator.of(context).pop(); Navigator.of(context).pop();
Updater.check(context); unawaited(
Updater.checkWithHandles(
navigator: navigator,
messenger: messenger,
),
);
}, },
), ),
+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(
+39 -32
View File
@@ -7,16 +7,6 @@ import 'package:revoltvpn/logic/server_list.dart';
import 'package:revoltvpn/components/online_dot.dart'; import 'package:revoltvpn/components/online_dot.dart';
import 'package:revoltvpn/screens/server_selector/selection_screen.dart'; import 'package:revoltvpn/screens/server_selector/selection_screen.dart';
// ── lib/components/status_bar.dart ──────────────────────────────────────────
// Two-card layout at the bottom of the main screen.
//
// Top card: server location from ServerList provider (flag + city).
// Tappable → opens server selector. Always visible.
// Bottom card: connection status (health dot + label + lock icon).
//
// Separated into two rows — no more RenderFlex overflow and ready for
// multi-server picker.
class StatusBar extends StatelessWidget { class StatusBar extends StatelessWidget {
const StatusBar({super.key}); const StatusBar({super.key});
@@ -28,15 +18,14 @@ class StatusBar extends StatelessWidget {
final isConnecting = vpn.status == VpnStatus.connecting; final isConnecting = vpn.status == VpnStatus.connecting;
final serverHealthy = final serverHealthy =
vpn.serverReachable || (isConnected && timer.hasSyncedOnce); vpn.serverReachable || (isConnected && timer.hasSyncedOnce);
final sessionOrTunnelHealthy = timer.hasSyncedOnce || vpn.serverReachable;
final statusLabel = isConnected final statusLabel = isConnected
? (timer.hasSyncedOnce ? 'Online' : 'Syncing…') ? (sessionOrTunnelHealthy ? 'Online' : 'Syncing…')
: (isConnecting : (isConnecting
? 'Connecting…' ? 'Connecting…'
: (vpn.serverReachable ? 'Ready' : 'Offline')); : (vpn.serverReachable ? 'Ready' : 'Offline'));
// Read from the ServerList provider — the source of truth for
// which server is selected and what it looks like.
final server = context.watch<ServerList>().selected; final server = context.watch<ServerList>().selected;
return Padding( return Padding(
@@ -44,7 +33,6 @@ class StatusBar extends StatelessWidget {
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
// ── Server location ──────────────────────────────────────────
GestureDetector( GestureDetector(
onTap: () { onTap: () {
Navigator.of(context).push( Navigator.of(context).push(
@@ -56,10 +44,12 @@ class StatusBar extends StatelessWidget {
position: Tween<Offset>( position: Tween<Offset>(
begin: const Offset(1.0, 0.0), begin: const Offset(1.0, 0.0),
end: Offset.zero, end: Offset.zero,
).animate(CurvedAnimation( ).animate(
parent: animation, CurvedAnimation(
curve: Curves.easeOut, parent: animation,
)), curve: Curves.easeOut,
),
),
child: child, child: child,
); );
}, },
@@ -79,24 +69,26 @@ class StatusBar extends StatelessWidget {
Image.asset(server.flagAsset, width: 20, height: 20), Image.asset(server.flagAsset, width: 20, height: 20),
const SizedBox(width: 8), const SizedBox(width: 8),
Expanded( Expanded(
child: Text(server.name, child: Text(
style: const TextStyle( server.name,
color: AppColors.accent, style: const TextStyle(
fontWeight: FontWeight.w600, color: AppColors.accent,
fontSize: 13, fontWeight: FontWeight.w600,
letterSpacing: 0.5, fontSize: 13,
)), letterSpacing: 0.5,
),
),
),
const Icon(
Icons.chevron_right,
color: AppColors.textDim,
size: 20,
), ),
const Icon(Icons.chevron_right,
color: AppColors.textDim, size: 20),
], ],
), ),
), ),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
// ── Connection status ────────────────────────────────────────
Container( Container(
padding: padding:
const EdgeInsets.symmetric(horizontal: 20, vertical: 10), const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
@@ -112,9 +104,24 @@ class StatusBar extends StatelessWidget {
label: statusLabel, label: statusLabel,
), ),
const Spacer(), 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) if (isConnected)
const Icon(Icons.lock, const Icon(
color: AppColors.green50, size: 14), Icons.lock,
color: AppColors.green50,
size: 14,
),
], ],
), ),
), ),
+59 -35
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');
if (rewarded) {
await timer.markSupportRewardClaimed();
await timer.syncNow();
}
} finally { } finally {
if (mounted) setState(() => _busy = false); if (mounted) setState(() => _busy = false);
} }
@@ -40,41 +49,56 @@ 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: Container( child: Opacity(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), opacity: disabled ? 0.55 : 1.0,
decoration: BoxDecoration( child: Container(
color: AppColors.glassBg, padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
borderRadius: BorderRadius.circular(24), decoration: BoxDecoration(
border: Border.all( color: AppColors.glassBg,
color: AppColors.accent.withAlpha(100), borderRadius: BorderRadius.circular(24),
width: 1, border: Border.all(
color: AppColors.accent.withAlpha(100),
width: 1,
),
), ),
), child: Row(
child: Row( mainAxisSize: MainAxisSize.min,
mainAxisSize: MainAxisSize.min, children: [
children: [ Icon(
const Icon(Icons.favorite_border, color: AppColors.accent, size: 20), claimed ? Icons.check_circle_outline : Icons.favorite_border,
const SizedBox(width: 8), color: AppColors.accent,
_busy size: 20,
? const SizedBox( ),
width: 18, const SizedBox(width: 8),
height: 18, _busy
child: CircularProgressIndicator( ? const SizedBox(
strokeWidth: 2, width: 18,
color: AppColors.accent, height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
color: AppColors.accent,
),
)
: Text(
!stateLoaded
? 'Checking support bonus…'
: claimed
? 'Support bonus used'
: 'Support us — 30 min!',
style: const TextStyle(
color: AppColors.textWhite,
fontSize: 14,
fontWeight: FontWeight.w600,
),
), ),
) ],
: const Text( ),
'Support us \u2014 30 min!',
style: TextStyle(
color: AppColors.textWhite,
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
],
), ),
), ),
); );
+24
View File
@@ -6,6 +6,7 @@ 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';
class AdManager extends ChangeNotifier { class AdManager extends ChangeNotifier {
static const bool adsEnabled = false; static const bool adsEnabled = false;
@@ -27,8 +28,29 @@ class AdManager extends ChangeNotifier {
if (adsEnabled) preloadAd(); if (adsEnabled) preloadAd();
} }
static Future<void>? _sdkInit;
static Future<void> ensureSdkInitialized() {
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;
await ensureSdkInitialized();
if (_isAdLoaded) return true; if (_isAdLoaded) return true;
if (_isAdLoading) return _loadCompleter?.future ?? Future.value(false); if (_isAdLoading) return _loadCompleter?.future ?? Future.value(false);
@@ -101,6 +123,8 @@ class AdManager extends ChangeNotifier {
if (!adsEnabled) return false; if (!adsEnabled) return false;
await ensureSdkInitialized();
if (!_isAdLoaded || _rewardedAd == null) { if (!_isAdLoaded || _rewardedAd == null) {
final loaded = await preloadAd(); final loaded = await preloadAd();
if (!loaded || _rewardedAd == null) { if (!loaded || _rewardedAd == null) {
+5 -23
View File
@@ -8,29 +8,11 @@ abstract final class AppConfig {
// ── Server ─────────────────────────────────────────────────────────── // ── Server ───────────────────────────────────────────────────────────
/// Your server's public IP. The VPN tunnel is pinned to this. /// Your server's public IP. The VPN tunnel is pinned to this.
static const String serverIp = '0.0.0.0'; // ◄── REPLACE static const String serverIp = '0.0.0.0'; // ◄── REPLACE
static const String hivemindApiPublic = 'https://YOUR_DOMAIN/api'; // ◄── REPLACE
/// API base — routed through the tunnel to Flask via Xray "api" outbound.
static const String hivemindApiBase = 'http://10.254.254.1:5000/api';
// ── Bootstrap (first-connect config fetch) ────────────────────────────
/// Hardcoded Reality config. App connects with this, fetches the real
/// per-session VLESS URL through the tunnel, then reconnects.
static String get bootstrapVlessUrl =>
'vless://$bootstrapUuid@$serverIp:8443'
'?security=reality&type=xhttp&path=/revolt'
'&pbk=$realityPbk&sni=www.github.com&sid=$realitySid&fp=chrome'
'#ReVoltVPN';
/// Generate with `xray uuid` on the server. Must match xray_config_reality.json.
static const String bootstrapUuid = '00000000-0000-0000-0000-000000000000'; // ◄── REPLACE
/// Server's Reality public key (from `xray x25519`).
static const String realityPbk = 'REPLACE_WITH_YOUR_PUBLIC_KEY';
/// Must be in xray_config_reality.json shortIds[].
static const String realitySid = 'abc123';
// ── Reality (VPN tunnel) ────────────────────────────────────────────── // ── Reality (VPN tunnel) ──────────────────────────────────────────────
// Credentials (public key, shortId) come from /session/status, not from
// here. Only the transport parameters below are compiled in.
/// The server picks a random SNI per session from REALITY_SNI_POOL. /// 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. /// The client does NOT hardcode one — server is always the source of truth.
@@ -47,8 +29,8 @@ abstract final class AppConfig {
// ── Updates ──────────────────────────────────────────────────────────── // ── Updates ────────────────────────────────────────────────────────────
/// Used by the updater. /// Used by the updater.
static const String applicationId = 'com.paladinvpn.app'; // ◄── REPLACE static const String applicationId = 'com.paladinvpn.app'; // ◄── REPLACE
static const String githubOwner = 'YOUR_USERNAME'; // ◄── REPLACE static const String githubOwner = 'YOUR_GITHUB_USERNAME'; // ◄── REPLACE (current: 'esefxdz')
static const String githubRepo = 'revoltvpn'; // ◄── REPLACE static const String githubRepo = 'YOUR_REPO_NAME'; // ◄── REPLACE (current: 'ReVoltVPN')
/// Fallback URL if the GitHub API call fails. /// Fallback URL if the GitHub API call fails.
static const String githubReleasesUrl = 'https://github.com/$githubOwner/$githubRepo/releases/latest'; static const String githubReleasesUrl = 'https://github.com/$githubOwner/$githubRepo/releases/latest';
+40
View File
@@ -0,0 +1,40 @@
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);
// Any unrecognized value (including the pre-V3 'auto') is TUN. 'proxy' is
// the only persisted value that selects the SOCKS5 mode.
_mode = storedMode == ConnectionMode.proxy.name
? ConnectionMode.proxy
: ConnectionMode.tun;
if (storedMode != _mode.name) {
await prefs.setString(_modeKey, _mode.name);
}
_initialized = true;
}
static Future<void> setMode(ConnectionMode mode) async {
_mode = mode;
_initialized = true;
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_modeKey, mode.name);
}
}
+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();
}
}
+149 -131
View File
@@ -1,7 +1,7 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io';
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';
@@ -13,74 +13,21 @@ class HivemindService {
static const _ua = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 ' static const _ua = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36'; '(KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36';
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)}) { static Future<http.Response> directGet(
Uri uri, {
Duration timeout = const Duration(seconds: 5),
}) {
return http.get(uri, headers: {'User-Agent': _ua}).timeout(timeout); return http.get(uri, headers: {'User-Agent': _ua}).timeout(timeout);
} }
static Future<http.Response> directPost(Uri uri, String body, {Duration timeout = const Duration(seconds: 5)}) { static void cancel() => _currentCallId++;
return http.post(uri, headers: {
'Content-Type': 'application/json',
'User-Agent': _ua,
}, body: body).timeout(timeout);
}
static Future<http.Response> proxyGet(Uri uri, {Duration timeout = const Duration(seconds: 5)}) {
return _proxyRequest('GET', uri, timeout: timeout);
}
static Future<http.Response> proxyPost(Uri uri, String body, {Duration timeout = const Duration(seconds: 5)}) {
return _proxyRequest('POST', uri, body: body, timeout: timeout);
}
static Future<http.Response> _proxyRequest(String method, Uri uri,
{String? body, Duration timeout = const Duration(seconds: 5)}) async {
final socket = await Socket.connect('127.0.0.1', 10808, timeout: timeout);
try {
final target = uri.toString();
final headers = <String, String>{
'Host': '${uri.host}:${uri.port}',
'User-Agent': _ua,
'Accept': '*/*',
'Connection': 'close',
};
if (body != null) {
headers['Content-Type'] = 'application/json';
headers['Content-Length'] = body.length.toString();
}
final reqBuf = StringBuffer();
reqBuf.write('$method $target HTTP/1.1\r\n');
headers.forEach((k, v) => reqBuf.write('$k: $v\r\n'));
reqBuf.write('\r\n');
if (body != null) reqBuf.write(body);
socket.write(reqBuf.toString());
await socket.flush();
final response = await socket.fold<String>(
'',
(prev, chunk) => prev + String.fromCharCodes(chunk),
).timeout(timeout);
final parts = response.split('\r\n\r\n');
if (parts.length < 2) throw Exception('Invalid proxy response');
final headerBlock = parts[0];
final respBody = parts.sublist(1).join('\r\n\r\n');
final headerLines = headerBlock.split('\r\n');
final statusParts = headerLines[0].split(' ');
final statusCode = int.parse(statusParts[1]);
return http.Response(respBody, statusCode);
} finally {
socket.destroy();
}
}
static void cancel() {
_currentCallId++;
}
static void setExpectedNonce(String nonce) { static void setExpectedNonce(String nonce) {
_expectedNonce = nonce; _expectedNonce = nonce;
@@ -91,66 +38,34 @@ class HivemindService {
bool skipAdBypass = false, bool skipAdBypass = false,
}) async { }) async {
final deviceId = await CryptoService.getDeviceId(); final deviceId = await CryptoService.getDeviceId();
final callId = ++_currentCallId; final callId = ++_currentCallId;
final nonce = '${Random().nextInt(0x7FFFFFFF)}-${DateTime.now().millisecondsSinceEpoch}'; final nonce = _newNonce();
_expectedNonce = nonce; _expectedNonce = nonce;
debugPrint('[HivemindService] Call #$callId — nonce: $nonce');
final url = _publicUrl('/session/status?device_id=$deviceId');
if (!skipAdBypass) { if (!skipAdBypass) {
try { await _runConfiguredBypass(deviceId, nonce);
final customData = jsonEncode({'device_id': deviceId, 'nonce': nonce});
final fakeUrl = _publicUrl(
'/admob/callback?signature=test&key_id=test&custom_data=${Uri.encodeComponent(customData)}');
await directGet(fakeUrl, timeout: const Duration(seconds: 8));
} catch (_) {}
} }
const maxAttempts = 5; const maxAttempts = 5;
for (int i = 1; i <= maxAttempts; i++) { for (var attempt = 1; attempt <= maxAttempts; attempt++) {
if (_currentCallId != callId) throw Exception('Cancelled'); _throwIfCancelled(callId);
onAttempt?.call(attempt, maxAttempts);
onAttempt?.call(i, maxAttempts);
try { try {
final response = await directGet(url); final session = await _fetchActiveSession(deviceId, nonce);
if (response.statusCode == 200) { if (session != null) {
final data = jsonDecode(response.body); _expectedNonce = null;
return session.toVlessUrl();
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'];
final vlessIp = data['vless_ip'] ?? AppConfig.serverIp;
final vlessPort = data['vless_port'] ?? 443;
final pbk = data['reality_pbk'] ?? '';
final sid = data['reality_sid'] ?? '';
final sni = data['reality_sni'];
if (sni == null) throw Exception('Server did not provide reality_sni');
final fp = data['reality_fp'] ?? AppConfig.realityFp;
final xhttpPath = data['xhttp_path'] ?? AppConfig.vlessPath;
final vlessUrl = 'vless://$vlessUuid@$vlessIp:$vlessPort'
'?security=${AppConfig.vlessSecurity}'
'&type=${AppConfig.vlessType}'
'&path=$xhttpPath'
'&pbk=${Uri.encodeComponent(pbk)}'
'&sni=${Uri.encodeComponent(sni)}'
'&sid=${Uri.encodeComponent(sid)}'
'&fp=${Uri.encodeComponent(fp)}'
'#Revolt VPN';
_expectedNonce = null;
return vlessUrl;
}
} }
} 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[attempt - 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.');
@@ -158,36 +73,139 @@ class HivemindService {
static Future<bool> checkHealth() async { static Future<bool> checkHealth() async {
try { try {
final url = Uri.parse('${AppConfig.hivemindApiPublic}/health'); final response = await directGet(
final response = await directGet(url, timeout: const Duration(seconds: 3)); _publicUrl('/health'),
timeout: const Duration(seconds: 3),
);
return response.statusCode == 200; return response.statusCode == 200;
} catch (_) { } catch (_) {
return false; return false;
} }
} }
static Future<bool> verifySession() async { static String _newNonce() {
try { final random = Random.secure();
final deviceId = await CryptoService.getDeviceId(); final high = random.nextInt(0x7FFFFFFF);
final url = _tunnelUrl('/session/status?device_id=$deviceId'); final low = random.nextInt(0x7FFFFFFF);
final response = await proxyGet(url); return '$high-$low-${DateTime.now().microsecondsSinceEpoch}';
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
return data['active'] == true;
}
} catch (_) {}
return false;
} }
// Idle sessions are culled server-side by the management loop static Future<void> _runConfiguredBypass(String deviceId, String nonce) async {
// after 2 minutes of no /status polls (user disconnected). try {
static void disconnectAndCleanup() {} final customData = jsonEncode({'device_id': deviceId, 'nonce': nonce});
final callback = _publicUrl(
'/admob/callback?signature=test&key_id=test&custom_data=${Uri.encodeComponent(customData)}',
);
await directGet(callback, timeout: const Duration(seconds: 8));
} catch (_) {
// Validation bypass behavior is intentionally best-effort in this build.
}
}
// ── URL builders ────────────────────────────────────────────────── static Future<_HivemindSessionConfig?> _fetchActiveSession(
String deviceId,
String nonce,
) async {
final statusUri = _publicUrl('/session/status').replace(
queryParameters: {'device_id': deviceId},
);
final response = await directGet(statusUri);
if (response.statusCode != 200) return null;
final decoded = jsonDecode(response.body);
if (decoded is! Map<String, dynamic>) return null;
final serverNonce = decoded['nonce'];
if (_expectedNonce != null &&
serverNonce is String &&
serverNonce != nonce) {
return null;
}
if (decoded['active'] != true || decoded['vless_uuid'] == null) {
return null;
}
return _HivemindSessionConfig.fromJson(decoded);
}
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) => static Uri _publicUrl(String path) =>
Uri.parse('${AppConfig.hivemindApiPublic}$path'); Uri.parse('${AppConfig.hivemindApiPublic}$path');
}
static Uri _tunnelUrl(String path) => class _HivemindSessionConfig {
Uri.parse('${AppConfig.hivemindApiBase}$path'); 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');
final host = _stringOr(json['vless_ip'], AppConfig.serverIp);
final port = _portOr(json['vless_port'], 443);
final sni = _requiredString(json, 'reality_sni');
return _HivemindSessionConfig(
uuid: uuid,
host: host,
port: port,
publicKey: _stringOr(json['reality_pbk'], ''),
shortId: _stringOr(json['reality_sid'], ''),
sni: sni,
fingerprint: _stringOr(json['reality_fp'], AppConfig.realityFp),
path: _stringOr(json['xhttp_path'], AppConfig.vlessPath),
);
}
String toVlessUrl() {
return 'vless://$uuid@$host:$port'
'?security=${AppConfig.vlessSecurity}'
'&type=${AppConfig.vlessType}'
'&path=$path'
'&pbk=${Uri.encodeComponent(publicKey)}'
'&sni=${Uri.encodeComponent(sni)}'
'&sid=${Uri.encodeComponent(shortId)}'
'&fp=${Uri.encodeComponent(fingerprint)}'
'#Revolt VPN';
}
static String _requiredString(Map<String, dynamic> json, String key) {
final value = json[key];
if (value is String && value.trim().isNotEmpty) return value.trim();
throw FormatException('Missing required session field: $key');
}
static String _stringOr(Object? value, String fallback) {
return value is String && value.isNotEmpty ? value : fallback;
}
static int _portOr(Object? value, int fallback) {
final parsed = value is num ? value.toInt() : fallback;
if (parsed <= 0 || parsed > 65535) {
throw const FormatException('Invalid VLESS port');
}
return parsed;
}
} }
+274
View File
@@ -0,0 +1,274 @@
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 SOCKS5 authentication. Startup must not depend on an
/// unrelated external host being reachable.
static Future<LocalSocksTestResult> testListener({
String host = '127.0.0.1',
int port = 10807,
String? username,
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 plus outbound
/// CONNECT. Credentials are optional so the helper remains usable for legacy
/// no-auth diagnostic builds.
static Future<LocalSocksTestResult> test({
String host = '127.0.0.1',
int port = 10807,
String? username,
String? password,
String targetHost = 'paladinvpn.duckdns.org',
int targetPort = 443,
}) async {
final stopwatch = Stopwatch()..start();
Socket? socket;
_SocketReader? reader;
try {
socket = await Socket.connect(
host,
port,
timeout: const Duration(seconds: 3),
);
socket.setOption(SocketOption.tcpNoDelay, true);
reader = _SocketReader(socket);
final authenticated = await _authenticate(
reader,
socket,
username: username,
password: password,
);
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);
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]);
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 passwordAuth = username != null && password != null;
if ((username == null) != (password == null)) return false;
socket.add(passwordAuth
? const <int>[0x05, 0x01, 0x02]
: const <int>[0x05, 0x01, 0x00]);
await socket.flush();
final greeting = await reader.readExactly(2, timeout: timeout);
if (greeting[0] != 0x05) return false;
if (!passwordAuth) return greeting[1] == 0x00;
if (greeting[1] != 0x02) return false;
final userBytes = utf8.encode(username);
final passBytes = utf8.encode(password);
if (userBytes.isEmpty ||
passBytes.isEmpty ||
userBytes.length > 255 ||
passBytes.length > 255) {
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) async {
if (addressType == 0x01) {
await reader.readExactly(4 + 2);
return;
}
if (addressType == 0x04) {
await reader.readExactly(16 + 2);
return;
}
if (addressType == 0x03) {
final length = (await reader.readExactly(1)).first;
await reader.readExactly(length + 2);
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 {
while (_buffer.length < count) {
final hasNext = await _iterator.moveNext().timeout(timeout);
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>),
);
}
}
+37
View File
@@ -0,0 +1,37 @@
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.
static Future<void> updateTimer(String text) async {
if (text == _lastText) return;
_lastText = text;
try {
await _channel.invokeMethod<void>('updateNotificationText', {
'title': 'Revolt VPN',
'text': text,
'disconnectLabel': 'Disconnect',
});
} catch (_) {
// Cosmetic.
}
}
/// Forces the next connect to re-post even if the countdown resumes on the
/// same value.
static void reset() => _lastText = null;
}
+93
View File
@@ -0,0 +1,93 @@
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;
}
}
/// Whether the VPN runtime is genuinely alive.
///
/// The Xray service runs in a separate process, so nothing it stores in
/// statics is visible to us. This asks the OS instead: is our service process
/// running, and (for TUN) is there an active VPN transport?
static Future<VpnRuntimeState> runtimeState() async {
if (kIsWeb) return const VpnRuntimeState(processAlive: false, vpnTransport: false);
try {
final result = await _channel.invokeMapMethod<String, dynamic>(
'isVpnRuntimeAlive',
);
return VpnRuntimeState(
processAlive: result?['processAlive'] == true,
vpnTransport: result?['vpnTransport'] == true,
);
} catch (_) {
return const VpnRuntimeState(processAlive: false, vpnTransport: false);
}
}
/// Pushes the absolute session-expiry timestamp (epoch ms) to the VPN
/// service so it can tear the tunnel down even when the UI process is gone.
static Future<void> setSessionExpiry(int expiresAtMs) async {
if (kIsWeb) return;
try {
await _channel.invokeMethod<void>('setSessionExpiry', {
'expiresAtMs': expiresAtMs,
});
} catch (_) {
// Best-effort. The daemon also keeps its last persisted expiry.
}
}
}
@immutable
class VpnRuntimeState {
final bool processAlive;
final bool vpnTransport;
const VpnRuntimeState({
required this.processAlive,
required this.vpnTransport,
});
/// TUN needs both a live service and a real VPN interface. Proxy mode has no
/// VPN interface at all, so the service process is the whole signal.
bool aliveFor({required bool tunMode}) =>
processAlive && (!tunMode || vpnTransport);
}
+89
View File
@@ -0,0 +1,89 @@
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);
final sourceInbounds = decoded['inbounds'];
final inbounds = <dynamic>[];
if (sourceInbounds is List) {
for (final value in sourceInbounds) {
if (value is Map) {
final protocol = value['protocol']?.toString().toLowerCase();
// ReVolt owns local proxy ingress on Android. Drop imported SOCKS/HTTP
// listeners so a stale no-auth proxy cannot remain reachable beside
// the authenticated session listener.
if (protocol == 'socks' || protocol == 'http') continue;
}
inbounds.add(value);
}
}
inbounds.add(<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'],
},
});
decoded['inbounds'] = inbounds;
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();
}
}
+3 -3
View File
@@ -5,9 +5,9 @@ import 'package:shared_preferences/shared_preferences.dart';
// Server data model and ChangeNotifier — shared by StatusBar (shows current // Server data model and ChangeNotifier — shared by StatusBar (shows current
// server name/flag) and SelectionScreen (lets user pick a server). // server name/flag) and SelectionScreen (lets user pick a server).
// //
// Each server is defined by its tunnel IP/port. Reality keys (public key, // Each server is defined by its tunnel IP/port. Reality credentials (public
// shortId, fingerprint) come from AppConfig — all servers share the same // key, shortId) come from /session/status per session; only the transport
// Reality keypair and bootstrap UUID (same operator, different locations). // parameters live in AppConfig.
// //
// When multi-server ships: // When multi-server ships:
// - _all becomes a fetched list (from /api/servers or bundled config) // - _all becomes a fetched list (from /api/servers or bundled config)
+258 -70
View File
@@ -1,44 +1,73 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:revoltvpn/logic/hivemind_service.dart';
import 'package:revoltvpn/logic/app_config.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
import 'package:revoltvpn/logic/crypto_service.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/power_settings.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
class SessionTimer extends ChangeNotifier with WidgetsBindingObserver {
Timer? _timer; Timer? _timer;
int _tickCount = 0; int _tickCount = 0;
int _lastPushedExpiryAtMs = 0;
bool _appBackgrounded = false;
final VpnConnection vpnConnection; final VpnConnection vpnConnection;
int _remainingSeconds = 0; int _remainingSeconds = 0;
int _usedBytes = 0; int _remainingAtLastSync = 0;
int _usedBytes = 0;
bool _hasSyncedOnce = false; bool _hasSyncedOnce = false;
int _consecutiveFailures = 0; int _consecutiveFailures = 0;
bool _isDisconnecting = false; bool _isDisconnecting = false;
bool _syncInProgress = false; bool _syncInProgress = false;
bool _supportRewardClaimed = false;
bool _supportRewardStateLoaded = false;
int _supportStateEpoch = 0;
static const String _supportRewardClaimKey =
'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 _maxOfflineSeconds = 120;
int _offlineSeconds = 0; int _offlineSeconds = 0;
static const int _pollIntervalSeconds = 5; // The countdown ticks locally every second; these only drive the slow
// server heartbeat that catches server-side changes (support-ad extension,
// 10 GB cap, session-ended). Keeping it slow avoids a chatty /session/status
// beacon (see internal/LAUNCH_READINESS.md "cut the beacon rate").
static const int _pollIntervalSeconds = 60;
static const int _backgroundPollIntervalSeconds = 60;
int _lastUsedBytes = 0; int _lastUsedBytes = 0;
double _currentSpeedKBps = 0.0; DateTime? _lastSuccessfulSyncAt;
double _currentSpeedKBps = 0.0;
SessionTimer({required this.vpnConnection}) { SessionTimer({required this.vpnConnection}) {
WidgetsBinding.instance.addObserver(this);
vpnConnection.addListener(_onVpnConnectionChanged); vpnConnection.addListener(_onVpnConnectionChanged);
unawaited(_loadSupportRewardState());
// This provider is built lazily, so the tunnel may already be up and
// VpnConnection may already have fired its change before we attached.
// A listener does not replay history -- evaluate the current state once.
// Deferred so we never notify during the build that created us.
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;
String get formatted { String get formatted {
@@ -48,77 +77,153 @@ class SessionTimer extends ChangeNotifier {
return '$h:$m:$s'; return '$h:$m:$s';
} }
void _onVpnConnectionChanged() { Future<void> _loadSupportRewardState() async {
// Restore timer if VPN was already running at app launch. final epoch = _supportStateEpoch;
if (vpnConnection.status == VpnStatus.connected && var claimed = false;
!isRunning && try {
vpnConnection.isStartupRestoration) { claimed =
_resumeTicking(); (await _supportStorage.read(key: _supportRewardClaimKey)) == '1';
return; } catch (e) {
debugPrint('[Timer] Failed to load support reward state: $e');
} }
// Resume after brief tunnel disconnection. if (epoch != _supportStateEpoch) return;
if (vpnConnection.status == VpnStatus.connected && _supportRewardClaimed = claimed;
!isRunning && _supportRewardStateLoaded = true;
!_isDisconnecting && notifyListeners();
_hasSyncedOnce) { }
debugPrint('[Timer] VPN reconnected after blip — resuming.');
_resumeTicking();
return;
}
if (vpnConnection.status == VpnStatus.disconnected && !_isDisconnecting) { Future<void> _persistSupportRewardState(bool value) async {
_doDisconnect('VPN tunnel dropped'); try {
await _supportStorage.write(
key: _supportRewardClaimKey,
value: value ? '1' : '0',
);
} catch (e) {
debugPrint('[Timer] Failed to persist support reward state: $e');
} }
} }
Future<void> start() async { Future<void> markSupportRewardClaimed() async {
_remainingSeconds = 0; if (_supportRewardClaimed) return;
_usedBytes = 0; _supportRewardClaimed = true;
_lastUsedBytes = 0; _supportRewardStateLoaded = true;
_currentSpeedKBps = 0.0; notifyListeners();
_tickCount = 0; await _persistSupportRewardState(true);
_hasSyncedOnce = false; }
void _onVpnConnectionChanged() {
// A live tunnel with a stopped clock is always wrong, however we got here:
// adopting a tunnel that outlived the UI process, recovering from a blip, or
// attaching late to one that was already up. Previously this required either
// adoptedRunningRuntime or _hasSyncedOnce, both false on a fresh process, so
// the clock stayed at 00:00:00 and the notification countdown froze with it.
if (vpnConnection.status == VpnStatus.connected &&
!isRunning &&
!_isDisconnecting) {
debugPrint('[Timer] Connected with a stopped clock - resuming.');
_resumeTicking();
return;
}
final hadActiveSession = isRunning || _hasSyncedOnce;
if (!hadActiveSession || _isDisconnecting) return;
if (vpnConnection.status == VpnStatus.error) {
_stopForVpnFailure('VPN entered error state');
return;
}
if (vpnConnection.status == VpnStatus.disconnected) {
unawaited(_doDisconnect('VPN tunnel dropped'));
}
}
void _stopForVpnFailure(String reason) {
if (_isDisconnecting) return;
_isDisconnecting = true;
debugPrint('[Timer] Stopping after VPN failure: $reason');
_timer?.cancel();
_timer = null;
_currentSpeedKBps = 0.0;
_remainingSeconds = 0;
_remainingAtLastSync = 0;
_hasSyncedOnce = false;
_lastSuccessfulSyncAt = null;
_consecutiveFailures = 0; _consecutiveFailures = 0;
_offlineSeconds = 0; _offlineSeconds = 0;
_isDisconnecting = false; NotificationService.reset();
notifyListeners();
}
Future<void> start() async {
_remainingSeconds = 0;
_remainingAtLastSync = 0;
_usedBytes = 0;
_lastUsedBytes = 0;
_lastSuccessfulSyncAt = null;
_currentSpeedKBps = 0.0;
_tickCount = 0;
_lastPushedExpiryAtMs = 0;
_hasSyncedOnce = false;
_consecutiveFailures = 0;
_offlineSeconds = 0;
_isDisconnecting = false;
_appBackgrounded = false;
NotificationService.reset();
_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();
_syncWithHivemind(); unawaited(_syncWithHivemind());
} }
void _tick(Timer t) { void _tick(Timer t) {
if (_isDisconnecting) return; if (_isDisconnecting) return;
if (_hasSyncedOnce && _consecutiveFailures < _maxConsecutiveFailures) { if (_hasSyncedOnce && _consecutiveFailures < _maxConsecutiveFailures) {
if (_remainingSeconds > 0) { _reconcileElapsedTime();
_remainingSeconds--;
}
} }
if (_consecutiveFailures >= _maxConsecutiveFailures) { if (_consecutiveFailures >= _maxConsecutiveFailures) {
_offlineSeconds++; _offlineSeconds++;
if (_offlineSeconds >= _maxOfflineSeconds) { if (_offlineSeconds >= _maxOfflineSeconds) {
_doDisconnect('Server unreachable'); unawaited(_doDisconnect('Server unreachable'));
return; return;
} }
} }
if (_hasSyncedOnce && _remainingSeconds <= 0) { if (_hasSyncedOnce && _remainingSeconds <= 0) {
_doDisconnect('Session expired'); unawaited(_doDisconnect('Session expired'));
return; return;
} }
_tickCount++; _tickCount++;
if (_tickCount % _pollIntervalSeconds == 0) { final pollInterval = _appBackgrounded
_syncWithHivemind(); ? _backgroundPollIntervalSeconds
: _pollIntervalSeconds;
if (_tickCount % pollInterval == 0) {
unawaited(_syncWithHivemind());
} }
notifyListeners(); notifyListeners();
if (_hasSyncedOnce && vpnConnection.status == VpnStatus.connected) {
NotificationService.updateTimer(formatted);
}
} }
/// Force an immediate server sync (e.g. after a support-ad extension so the
/// countdown reflects the new expiry without waiting for the next heartbeat).
Future<void> syncNow() => _syncWithHivemind();
Future<void> disconnect({String reason = 'User requested'}) async { Future<void> disconnect({String reason = 'User requested'}) async {
await _doDisconnect(reason); await _doDisconnect(reason);
} }
@@ -132,7 +237,10 @@ class SessionTimer extends ChangeNotifier {
_timer = null; _timer = null;
_currentSpeedKBps = 0.0; _currentSpeedKBps = 0.0;
_remainingSeconds = 0; _remainingSeconds = 0;
_remainingAtLastSync = 0;
_hasSyncedOnce = false; _hasSyncedOnce = false;
_lastSuccessfulSyncAt = null;
NotificationService.reset();
notifyListeners(); notifyListeners();
await vpnConnection.disconnect(); await vpnConnection.disconnect();
@@ -142,37 +250,80 @@ class SessionTimer extends ChangeNotifier {
notifyListeners(); 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 {
if (_isDisconnecting || _syncInProgress) return; if (_isDisconnecting || _syncInProgress) return;
_syncInProgress = true; _syncInProgress = true;
try { try {
final deviceId = await CryptoService.getDeviceId(); final deviceId = await CryptoService.getDeviceId();
final url = Uri.parse( final base = Uri.parse('${AppConfig.hivemindApiPublic}/session/status');
'${AppConfig.hivemindApiPublic}/session/status?device_id=$deviceId'); final url = base.replace(queryParameters: {'device_id': deviceId});
final response = await HivemindService.directGet(url); final response = await HivemindService.directGet(url);
if (_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();
return;
}
final data = decoded;
final bool active = data['active'] ?? false; final activeValue = data['active'];
if (!active) { if (activeValue is! bool) {
debugPrint('[Timer] Session payload missing boolean active state.');
_markSyncFailure();
return;
}
if (!activeValue) {
await _doDisconnect('Server ended session'); await _doDisconnect('Server ended session');
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();
return;
}
final int deltaBytes = _usedBytes - _lastUsedBytes; _remainingAtLastSync = expiresValue.toInt();
if (_hasSyncedOnce && deltaBytes > 0) { _remainingSeconds = _remainingAtLastSync;
_currentSpeedKBps = (deltaBytes / _pollIntervalSeconds) / 1000; // Push the absolute deadline to the VPN service so it can tear the
} else if (!_hasSyncedOnce) { // tunnel down on its own clock, even if this UI process is gone.
final expiresAtMs =
DateTime.now().millisecondsSinceEpoch + _remainingSeconds * 1000;
if ((expiresAtMs - _lastPushedExpiryAtMs).abs() > 5000) {
_lastPushedExpiryAtMs = expiresAtMs;
unawaited(PowerSettings.setSessionExpiry(expiresAtMs));
}
_usedBytes = _readNonNegativeInt(data['used_bytes'], _usedBytes);
final now = DateTime.now();
final previousSyncAt = _lastSuccessfulSyncAt;
final deltaBytes = _usedBytes - _lastUsedBytes;
if (_hasSyncedOnce && previousSyncAt != null) {
final elapsedMs = now.difference(previousSyncAt).inMilliseconds;
if (deltaBytes > 0 && elapsedMs > 0) {
_currentSpeedKBps = (deltaBytes / (elapsedMs / 1000.0)) / 1000.0;
} else {
_currentSpeedKBps = 0.0;
}
} else {
_currentSpeedKBps = 0.0; _currentSpeedKBps = 0.0;
} }
_lastUsedBytes = _usedBytes; _lastUsedBytes = _usedBytes;
_lastSuccessfulSyncAt = now;
final capExhausted = data['cap_exhausted'] ?? false; if (data['cap_exhausted'] == true) {
if (capExhausted) {
await _doDisconnect('Data cap reached'); await _doDisconnect('Data cap reached');
return; return;
} }
@@ -185,8 +336,10 @@ class SessionTimer extends ChangeNotifier {
_markSyncFailure(); _markSyncFailure();
} }
} catch (e) { } catch (e) {
debugPrint('Hivemind sync error: $e'); if (!_isDisconnecting) {
_markSyncFailure(); debugPrint('Hivemind sync error: $e');
_markSyncFailure();
}
} finally { } finally {
_syncInProgress = false; _syncInProgress = false;
} }
@@ -199,16 +352,51 @@ class SessionTimer extends ChangeNotifier {
} }
} }
void _reconcileElapsedTime() {
final syncedAt = _lastSuccessfulSyncAt;
if (!_hasSyncedOnce || syncedAt == null) return;
final elapsed = DateTime.now().difference(syncedAt).inSeconds;
_remainingSeconds =
(_remainingAtLastSync - elapsed).clamp(0, 1 << 31).toInt();
}
@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();
}
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(); notifyListeners();
} }
@override @override
void dispose() { void dispose() {
WidgetsBinding.instance.removeObserver(this);
vpnConnection.removeListener(_onVpnConnectionChanged); vpnConnection.removeListener(_onVpnConnectionChanged);
_timer?.cancel(); _timer?.cancel();
super.dispose(); super.dispose();
+171 -41
View File
@@ -13,6 +13,78 @@ enum UpdateStatus { upToDate, updateAvailable, checkFailed }
enum InstallSource { playStore, sideload } 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 { class PlayStoreUpdater {
PlayStoreUpdater._(); PlayStoreUpdater._();
@@ -20,9 +92,13 @@ class PlayStoreUpdater {
'https://play.google.com/store/apps/details?id=${AppConfig.applicationId}'; 'https://play.google.com/store/apps/details?id=${AppConfig.applicationId}';
static Future<bool> open() async { 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 { try {
return await launchUrl(Uri.parse(_url), return await launchUrl(uri, mode: LaunchMode.externalApplication);
mode: LaunchMode.externalApplication);
} catch (e) { } catch (e) {
debugPrint('[Updater] Failed to open Play Store: $e'); debugPrint('[Updater] Failed to open Play Store: $e');
return false; return false;
@@ -36,13 +112,14 @@ class GitHubUpdater {
static String? _cachedDownloadUrl; static String? _cachedDownloadUrl;
static Future<String?> fetchLatestVersion() async { static Future<String?> fetchLatestVersion() async {
final url = final apiUri = Uri.https(
'https://api.github.com/repos/${AppConfig.githubOwner}/${AppConfig.githubRepo}/releases/latest'; 'api.github.com',
'/repos/${AppConfig.githubOwner}/${AppConfig.githubRepo}/releases/latest',
);
try { try {
final response = await http final response = await http
.get(Uri.parse(url), .get(apiUri, headers: {'Accept': 'application/vnd.github+json'})
headers: {'Accept': 'application/vnd.github+json'})
.timeout(const Duration(seconds: 8)); .timeout(const Duration(seconds: 8));
if (response.statusCode != 200) { if (response.statusCode != 200) {
@@ -50,11 +127,32 @@ class GitHubUpdater {
return null; return null;
} }
final data = jsonDecode(response.body) as Map<String, dynamic>; final decoded = jsonDecode(response.body);
_cachedDownloadUrl = data['html_url'] as String?; if (decoded is! Map<String, dynamic>) {
debugPrint('[Updater] Invalid GitHub release payload.');
return null;
}
final tag = data['tag_name'] as String? ?? '0.0.0'; final htmlUrl = decoded['html_url'];
return tag.startsWith('v') ? tag.substring(1) : tag; 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) { } catch (e) {
debugPrint('[Updater] GitHub API error: $e'); debugPrint('[Updater] GitHub API error: $e');
return null; return null;
@@ -62,10 +160,15 @@ class GitHubUpdater {
} }
static Future<bool> open() async { static Future<bool> open() async {
final url = _cachedDownloadUrl ?? AppConfig.githubReleasesUrl; 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 { try {
return await launchUrl(Uri.parse(url), return await launchUrl(uri, mode: LaunchMode.externalApplication);
mode: LaunchMode.externalApplication);
} catch (e) { } catch (e) {
debugPrint('[Updater] Failed to open GitHub: $e'); debugPrint('[Updater] Failed to open GitHub: $e');
return false; return false;
@@ -100,14 +203,13 @@ class Updater {
} }
static int _compareVersions(String a, String b) { static int _compareVersions(String a, String b) {
final aParts = a.split('.').map((p) => int.tryParse(p) ?? 0).toList(); final left = _ParsedVersion.tryParse(a);
final bParts = b.split('.').map((p) => int.tryParse(p) ?? 0).toList(); final right = _ParsedVersion.tryParse(b);
for (int i = 0; i < 3; i++) { if (left == null || right == null) {
final diff = (aParts.length > i ? aParts[i] : 0) - // Invalid local metadata should not invent an ordering.
(bParts.length > i ? bParts[i] : 0); return 0;
if (diff != 0) return diff;
} }
return 0; return left.compareTo(right);
} }
static String _versionLabel(String v, bool isLocal) { static String _versionLabel(String v, bool isLocal) {
@@ -115,36 +217,54 @@ class Updater {
return '$prefix$v${isLocal ? ' (installed)' : ''}'; return '$prefix$v${isLocal ? ' (installed)' : ''}';
} }
static Future<void> check(BuildContext context) async { 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 info = await PackageInfo.fromPlatform();
final localVersion = info.version; final localVersion = info.version;
if (localVersion.isEmpty) { if (localVersion.isEmpty || _ParsedVersion.tryParse(localVersion) == null) {
_showSnackBar(context, 'Could not determine app version', _showSnackBar(
isError: true); messenger,
'Could not determine app version',
isError: true,
);
return; return;
} }
final latestVersion = await GitHubUpdater.fetchLatestVersion(); final latestVersion = await GitHubUpdater.fetchLatestVersion();
if (latestVersion == null) { if (latestVersion == null) {
_showSnackBar(context, 'Could not reach GitHub', isError: true); _showSnackBar(messenger, 'Could not reach GitHub', isError: true);
return; return;
} }
if (_compareVersions(localVersion, latestVersion) >= 0) { if (_compareVersions(localVersion, latestVersion) >= 0) {
_showSnackBar(context, 'Up to date'); _showSnackBar(messenger, 'Up to date');
return; return;
} }
final source = await installSource; final source = await installSource;
final storeName = source == InstallSource.playStore ? 'Play Store' : 'GitHub'; final storeName =
if (!context.mounted) return; source == InstallSource.playStore ? 'Play Store' : 'GitHub';
if (!navigator.mounted) return;
showDialog( showDialog(
context: context, context: navigator.context,
builder: (ctx) => AlertDialog( builder: (ctx) => AlertDialog(
backgroundColor: AppColors.bgCard, backgroundColor: AppColors.bgCard,
title: const Text('Update available', title: const Text(
style: TextStyle(color: AppColors.textWhite)), 'Update available',
style: TextStyle(color: AppColors.textWhite),
),
content: Text( content: Text(
'${_versionLabel(latestVersion, false)} is available on $storeName.\n' '${_versionLabel(latestVersion, false)} is available on $storeName.\n'
'You have ${_versionLabel(localVersion, true)}.', 'You have ${_versionLabel(localVersion, true)}.',
@@ -153,8 +273,10 @@ class Updater {
actions: [ actions: [
TextButton( TextButton(
onPressed: () => Navigator.pop(ctx), onPressed: () => Navigator.pop(ctx),
child: const Text('Later', child: const Text(
style: TextStyle(color: AppColors.slate70)), 'Later',
style: TextStyle(color: AppColors.slate70),
),
), ),
TextButton( TextButton(
onPressed: () { onPressed: () {
@@ -163,23 +285,31 @@ class Updater {
? PlayStoreUpdater.open() ? PlayStoreUpdater.open()
: GitHubUpdater.open(); : GitHubUpdater.open();
}, },
child: Text('Open $storeName', child: Text(
style: const TextStyle(color: AppColors.accent)), 'Open $storeName',
style: const TextStyle(color: AppColors.accent),
),
), ),
], ],
), ),
); );
} }
static void _showSnackBar(BuildContext context, String message, static void _showSnackBar(
{bool isError = false}) { ScaffoldMessengerState messenger,
ScaffoldMessenger.of(context).showSnackBar( String message, {
bool isError = false,
}) {
if (!messenger.mounted) return;
messenger.showSnackBar(
SnackBar( SnackBar(
content: Row( content: Row(
children: [ children: [
Icon(isError ? Icons.error_outline : Icons.check_circle, Icon(
color: isError ? AppColors.red : AppColors.green, isError ? Icons.error_outline : Icons.check_circle,
size: 18), color: isError ? AppColors.red : AppColors.green,
size: 18,
),
const SizedBox(width: 8), const SizedBox(width: 8),
Text(message), Text(message),
], ],
+254 -64
View File
@@ -1,8 +1,13 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.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/power_settings.dart';
import 'package:revoltvpn/logic/secure_socks_session.dart';
enum VpnStatus { enum VpnStatus {
disconnected, disconnected,
@@ -23,28 +28,83 @@ class VpnConnection extends ChangeNotifier {
String? _errorMessage; String? _errorMessage;
String? get errorMessage => _errorMessage; String? get errorMessage => _errorMessage;
bool _isStartupRestoration = false; /// True when the UI attached to a tunnel that was already running, rather
bool get isStartupRestoration => _isStartupRestoration; /// than starting one itself. The session timer uses this to resume ticking.
bool _adoptedRunningRuntime = false;
bool get adoptedRunningRuntime => _adoptedRunningRuntime;
bool _serverReachable = false; bool _serverReachable = false;
bool get serverReachable => _serverReachable; bool get serverReachable => _serverReachable;
ConnectionMode _activeMode = ConnectionMode.tun;
ConnectionMode get activeMode => _activeMode;
String _networkTransport = 'unknown';
String get networkTransport => _networkTransport;
SecureSocksSession? get activeSocksSession => _lastSecureSocks;
bool get canTestActiveLocalSocks =>
_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,
);
}
Timer? _healthTimer; Timer? _healthTimer;
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 {
try {
await _startEngine();
} catch (e) {
debugPrint('[VPN] Engine init failed: $e');
} finally {
if (!_readyCompleter.isCompleted) _readyCompleter.complete();
}
}
Future<void> _startEngine() async {
if (kIsWeb) return; if (kIsWeb) return;
await ConnectionSettings.initialize();
_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);
}, },
); );
@@ -53,45 +113,88 @@ class VpnConnection extends ChangeNotifier {
await _vless.initializeVless( await _vless.initializeVless(
providerBundleIdentifier: 'com.paladinvpn.app', providerBundleIdentifier: 'com.paladinvpn.app',
notificationIconResourceType: 'drawable', notificationIconResourceType: 'drawable',
notificationIconResourceName: 'notification_icon', notificationIconResourceName: 'notification_status_icon',
); );
_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');
} }
_checkHealth(); _networkSubscription = NetworkMonitor.changes.listen(
_healthTimer = (snapshot) {
Timer.periodic(const Duration(seconds: 30), (_) => _checkHealth()); // 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');
},
);
unawaited(_checkHealth());
_healthTimer = Timer.periodic(const Duration(seconds: 30), (_) {
unawaited(_checkHealth());
});
try { try {
final coreVersion = await _vless.getCoreVersion(); final coreVersion = await _vless.getCoreVersion();
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 (_) {}
await _adoptRunningRuntime();
}
/// Reflect a tunnel that is already up when the UI starts.
///
/// This asks the OS whether our VPN service process is alive, rather than
/// probing a local SOCKS port. The old probe called getConnectedServerDelay(),
/// which reads AppConfigs.V2RAY_CONFIG?.LOCAL_SOCKS5_PORT ?: 10807 — but
/// AppConfigs lives in the VPN's own process, so from here it is always null
/// and the port always fell back to 10807. That was correct only while the
/// SOCKS port was fixed; per-session ephemeral ports made it permanently
/// wrong, so the app reported "connected" against a dead tunnel.
Future<void> _adoptRunningRuntime() async {
if (kIsWeb) return;
try {
final state = await PowerSettings.runtimeState();
if (state.aliveFor(tunMode: _activeMode == ConnectionMode.tun)) {
_adoptedRunningRuntime = true;
_setStatus(VpnStatus.connected, _connectedLabel);
}
} catch (e) {
debugPrint('[VPN] Runtime liveness check failed: $e');
}
}
String get _connectedLabel {
switch (_activeMode) {
case ConnectionMode.proxy:
return 'SOCKS5 gateway active';
case ConnectionMode.tun:
return 'Secured';
}
} }
void _mapStatus(VlessStatus status) { void _mapStatus(VlessStatus status) {
switch (status.connectionState) { switch (status.connectionState) {
case VlessConnectionState.connected: case VlessConnectionState.connected:
_setStatus(VpnStatus.connected, 'Secured'); _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:
_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:
if (_status != VpnStatus.connected && if (_status != VpnStatus.connected &&
_status != VpnStatus.disconnected) { _status != VpnStatus.disconnected) {
@@ -101,22 +204,16 @@ class VpnConnection extends ChangeNotifier {
} }
} }
// ── Connect ──────────────────────────────────────────────────────── Future<bool> connect({bool skipAdBypass = false}) async {
//
// 1. Direct HTTPS to the public API → get per-user VLESS URL
// 2. Start tunnel directly with that URL (no bootstrap, no switch)
//
// The only hardcoded data in the APK is the Reality public key and
// shortId (needed for every Reality handshake — unavoidable).
// The tunnel UUID is per-user, assigned by Hivemind via AdMob SSV.
Future<bool> connect({
bool skipAdBypass = false,
}) async {
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) { if (_status == VpnStatus.connected || _status == VpnStatus.connecting) {
return false; return false;
} }
_cancelled = false; _cancelled = false;
_userDisconnecting = false;
await ConnectionSettings.initialize();
_activeMode = ConnectionSettings.mode;
if (!kIsWeb && !_initialized) { if (!kIsWeb && !_initialized) {
_errorMessage = 'VPN service unavailable.'; _errorMessage = 'VPN service unavailable.';
@@ -124,7 +221,9 @@ class VpnConnection extends ChangeNotifier {
return false; return false;
} }
if (!kIsWeb) { // TUN needs the Android VPN permission; SOCKS5 proxy mode runs a local
// authenticated proxy without a VpnService, so no VPN permission is needed.
if (!kIsWeb && _activeMode == ConnectionMode.tun) {
final ok = await _vless.requestPermission(); final ok = await _vless.requestPermission();
if (!ok) { if (!ok) {
_errorMessage = 'VPN permission denied.'; _errorMessage = 'VPN permission denied.';
@@ -133,7 +232,11 @@ class VpnConnection extends ChangeNotifier {
} }
} }
_setStatus(VpnStatus.connecting, 'Establishing secure channel…'); 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) {
@@ -150,7 +253,9 @@ class VpnConnection extends ChangeNotifier {
skipAdBypass: skipAdBypass, skipAdBypass: skipAdBypass,
onAttempt: (attempt, total) { onAttempt: (attempt, total) {
_setStatus( _setStatus(
VpnStatus.connecting, 'Contacting server ($attempt/$total)…'); VpnStatus.connecting,
'Contacting server ($attempt/$total)…',
);
}, },
); );
} catch (e) { } catch (e) {
@@ -162,7 +267,7 @@ class VpnConnection extends ChangeNotifier {
'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 { } else {
_errorMessage = e.toString().replaceAll('Exception: ', ''); _errorMessage = raw;
_setStatus(VpnStatus.error, 'Config fetch error'); _setStatus(VpnStatus.error, 'Config fetch error');
} }
return false; return false;
@@ -173,43 +278,115 @@ class VpnConnection extends ChangeNotifier {
return false; return false;
} }
_setStatus(VpnStatus.connecting, 'Securing connection…'); _setStatus(VpnStatus.connecting, 'Starting secure route…');
try { try {
final parsed = FlutterVless.parse(realUrl); final parsed = FlutterVless.parse(realUrl);
final configJson = final baseConfig = parsed.getFullConfiguration();
jsonDecode(parsed.getFullConfiguration()) as Map<String, dynamic>; final remark = parsed.remark.isNotEmpty ? parsed.remark : 'Revolt VPN';
final secureSocks = await SecureSocksSession.create(baseConfig);
final verifyLocalSocks = _activeMode == ConnectionMode.proxy;
// Inject HTTP inbound for tunnel-internal API calls. await _startRuntime(
final inbounds = (configJson['inbounds'] as List?) ?? []; config: secureSocks.configJson,
inbounds.add({ remark: remark,
'tag': 'http-proxy', proxyOnly: verifyLocalSocks,
'port': 10808,
'listen': '127.0.0.1',
'protocol': 'http',
});
configJson['inbounds'] = inbounds;
await _vless.startVless(
remark: parsed.remark.isNotEmpty ? parsed.remark : 'Revolt VPN',
config: jsonEncode(configJson),
); );
_setStatus(
VpnStatus.connecting,
verifyLocalSocks ? 'Waiting for local SOCKS5…' : 'Waiting for VPN interface…',
);
if (!await _waitForNativeConnected()) {
throw StateError('VPN runtime did not report CONNECTED');
}
if (verifyLocalSocks) {
_setStatus(VpnStatus.connecting, 'Checking Local SOCKS5…');
if (!await _waitForLocalSocksListener(secureSocks)) {
throw StateError('Local SOCKS5 listener did not become ready');
}
}
_lastSecureSocks = secureSocks;
} catch (e) { } catch (e) {
debugPrint('[VPN] Tunnel start error: $e'); debugPrint('[VPN] Tunnel start error: $e');
_errorMessage = 'Tunnel failed to start.\nTry reconnecting.'; await _stopRuntime();
_clearRuntimeSnapshot();
_errorMessage = _activeMode == ConnectionMode.proxy
? 'SOCKS5 gateway failed to start.\nTry reconnecting.'
: 'Connection failed to start.\nTry reconnecting.';
_setStatus(VpnStatus.error, 'Connection failed'); _setStatus(VpnStatus.error, 'Connection failed');
return false; return false;
} }
_setStatus(VpnStatus.connected, 'Secured'); _setStatus(VpnStatus.connected, _connectedLabel);
return true; return true;
} }
Future<void> _startRuntime({
required String config,
required String remark,
required bool proxyOnly,
}) async {
await _vless.startVless(
remark: remark,
config: config,
proxyOnly: proxyOnly,
);
}
Future<bool> _waitForLocalSocksListener([
SecureSocksSession? session,
]) async {
final active = session ?? _lastSecureSocks;
if (active == null) return false;
for (var attempt = 0; attempt < 4; attempt++) {
final result = await LocalSocksTester.testListener(
host: '127.0.0.1',
port: active.port,
username: active.username,
password: active.password,
);
if (result.ok) {
return true;
}
if (attempt < 3) {
await Future.delayed(const Duration(milliseconds: 250));
}
}
return false;
}
Future<bool> _waitForNativeConnected() async {
// startVless() queues the Android foreground service. Wait for the native
// service/core broadcast rather than treating MethodChannel completion as
// proof that a TUN interface was established.
for (var attempt = 0; attempt < 24; attempt++) {
if (_status == VpnStatus.connected) return true;
if (_status == VpnStatus.error) return false;
if (_cancelled || _userDisconnecting) return false;
await Future.delayed(const Duration(milliseconds: 250));
}
return _status == VpnStatus.connected;
}
Future<void> _stopRuntime() async {
try {
await _vless.stopVless().timeout(const Duration(seconds: 5));
} catch (_) {}
}
Future<void> disconnect() async { Future<void> disconnect() async {
_cancelled = true; _cancelled = true;
_userDisconnecting = true;
HivemindService.cancel(); HivemindService.cancel();
if (_status == VpnStatus.disconnected || if (_status == VpnStatus.disconnected ||
_status == VpnStatus.disconnecting) { _status == VpnStatus.disconnecting) {
_clearRuntimeSnapshot();
_userDisconnecting = false;
return; return;
} }
@@ -217,7 +394,9 @@ class VpnConnection extends ChangeNotifier {
if (kIsWeb) { if (kIsWeb) {
await Future.delayed(const Duration(milliseconds: 500)); await Future.delayed(const Duration(milliseconds: 500));
_clearRuntimeSnapshot();
_setStatus(VpnStatus.disconnected, 'Tap to connect'); _setStatus(VpnStatus.disconnected, 'Tap to connect');
_userDisconnecting = false;
return; return;
} }
@@ -230,29 +409,42 @@ class VpnConnection extends ChangeNotifier {
} catch (e) { } catch (e) {
debugPrint('[VPN] VLESS stop error: $e'); debugPrint('[VPN] VLESS stop error: $e');
_errorMessage = 'VPN shutdown error.\nPlease restart the app.'; _errorMessage = 'VPN shutdown error.\nPlease restart the app.';
_clearRuntimeSnapshot();
_setStatus(VpnStatus.error, 'Shutdown failed'); _setStatus(VpnStatus.error, 'Shutdown failed');
_userDisconnecting = false;
return; return;
} }
if (timedOut) { if (timedOut) {
debugPrint('[VPN] stopVless() timed out after 5 s — ' debugPrint('[VPN] stopVless() timed out after 5 s.');
'tunnel may still be active.'); _errorMessage = 'VPN did not shut down cleanly.\nPlease restart the app.';
_errorMessage = 'VPN did not shut down cleanly.\n' _clearRuntimeSnapshot();
'Please restart the app.';
_setStatus(VpnStatus.error, 'Shutdown failed'); _setStatus(VpnStatus.error, 'Shutdown failed');
_userDisconnecting = false;
return; return;
} }
_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;
}
void _setStatus(VpnStatus status, String message) {
_status = status;
_statusMessage = message;
notifyListeners(); notifyListeners();
} }
Future<void> _checkHealth() async { Future<void> _checkHealth() async {
// A live tunnel already proves reachability; only probe while disconnected
// so we don't add direct /health traffic while the VPN is active.
if (_status == VpnStatus.connected) return;
_serverReachable = await HivemindService.checkHealth(); _serverReachable = await HivemindService.checkHealth();
notifyListeners(); notifyListeners();
} }
@@ -260,11 +452,9 @@ class VpnConnection extends ChangeNotifier {
@override @override
void dispose() { void dispose() {
_healthTimer?.cancel(); _healthTimer?.cancel();
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) { _networkSubscription?.cancel();
try { // Provider/UI disposal is not a user disconnect command. Keeping teardown
_vless.stopVless(); // in disconnect() prevents lifecycle churn from silently dropping the VPN.
} catch (_) {}
}
super.dispose(); super.dispose();
} }
} }
+23 -24
View File
@@ -1,22 +1,23 @@
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:package_info_plus/package_info_plus.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/server_list.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/server_list.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,
@@ -34,33 +35,31 @@ void main() async {
return true; return true;
}; };
await ConsentManager.requestConsentIfNeeded();
await MobileAds.instance.initialize();
final packageInfo = await PackageInfo.fromPlatform();
ReVoltApp.appVersion = packageInfo.version;
runApp(const ReVoltApp()); runApp(const ReVoltApp());
} }
class ReVoltApp extends StatelessWidget { class ReVoltApp extends StatelessWidget {
const ReVoltApp({super.key}); const ReVoltApp({super.key});
/// Set at startup from PackageInfo — used by sidebar and anywhere
/// the app version needs to be displayed.
static String appVersion = '';
@override @override
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()),
ChangeNotifierProvider(create: (_) => ServerList()..init()), ChangeNotifierProvider(
create: (_) => ServerList()..init(),
lazy: false,
),
], ],
child: MaterialApp( child: MaterialApp(
title: 'ReVolt VPN', title: 'ReVolt VPN',
+70 -19
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');
} }
}
void _scheduleNavigation() { try {
// Brief natural pause — just long enough to perceive the logo. await settingsPrefs;
Timer(const Duration(milliseconds: 1200), () { } catch (e) {
if (!mounted) return; debugPrint('[Boot] Settings prefs load failed, using defaults: $e');
if (WidgetsBinding.instance.lifecycleState == AppLifecycleState.paused) { }
// App is backgrounded — defer navigation until resumed.
return;
}
_navigateToMain();
});
}
void _navigateToMain() {
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) {
return;
}
_navigated = true;
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,
@@ -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),
], ],
@@ -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,288 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.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;
}
await ConnectionSettings.setMode(next);
if (!mounted) return;
setState(() {
_mode = next;
_lastSocksTest = null;
});
widget.onChanged?.call(next);
}
/// Recovers from an orphaned proxy: tear the runtime down and start a fresh
/// session so a readable set of credentials exists again. No rewarded ad —
/// the user is repairing a connection they already paid for, not opening a
/// new one.
Future<void> _reconnect() async {
if (_reconnecting) return;
final vpn = context.read<VpnConnection>();
final timer = context.read<SessionTimer>();
setState(() => _reconnecting = true);
try {
await timer.disconnect();
if (!mounted) return;
if (await vpn.connect()) {
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,
),
),
),
],
],
);
}
}
+19 -16
View File
@@ -1,8 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:revoltvpn/logic/app_colors.dart'; import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/logic/haptic_settings.dart';
bool hapticEnabled = false;
class HapticFeedbackTile extends StatefulWidget { class HapticFeedbackTile extends StatefulWidget {
const HapticFeedbackTile({super.key}); const HapticFeedbackTile({super.key});
@@ -12,7 +10,8 @@ class HapticFeedbackTile extends StatefulWidget {
} }
class _HapticFeedbackTileState extends State<HapticFeedbackTile> { class _HapticFeedbackTileState extends State<HapticFeedbackTile> {
bool _on = false; bool _on = HapticSettings.enabled;
bool _saving = false;
@override @override
void initState() { void initState() {
@@ -20,21 +19,25 @@ class _HapticFeedbackTileState extends State<HapticFeedbackTile> {
_load(); _load();
} }
// Loads persisted state and syncs the top-level bool.
Future<void> _load() async { Future<void> _load() async {
final prefs = await SharedPreferences.getInstance(); await HapticSettings.initialize();
final value = prefs.getBool('haptic_feedback_enabled') ?? false; if (mounted) setState(() => _on = HapticSettings.enabled);
hapticEnabled = value;
if (mounted) setState(() => _on = value);
} }
// Writes to SharedPreferences AND updates the live bool so the connect
// button sees the change immediately — no restart needed.
Future<void> _toggle(bool value) async { Future<void> _toggle(bool value) async {
final prefs = await SharedPreferences.getInstance(); if (_saving) return;
await prefs.setBool('haptic_feedback_enabled', value); setState(() {
hapticEnabled = value; _saving = true;
setState(() => _on = value); _on = value;
});
try {
await HapticSettings.setEnabled(value);
} catch (_) {
if (mounted) setState(() => _on = HapticSettings.enabled);
} finally {
if (mounted) setState(() => _saving = false);
}
} }
@override @override
@@ -45,7 +48,7 @@ class _HapticFeedbackTileState extends State<HapticFeedbackTile> {
style: TextStyle(color: AppColors.textWhite, fontSize: 15), style: TextStyle(color: AppColors.textWhite, fontSize: 15),
), ),
value: _on, value: _on,
onChanged: _toggle, onChanged: _saving ? null : _toggle,
activeTrackColor: AppColors.accent.withAlpha(80), activeTrackColor: AppColors.accent.withAlpha(80),
activeThumbColor: AppColors.accent, activeThumbColor: AppColors.accent,
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4), contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
@@ -4,12 +4,13 @@ import 'package:revoltvpn/logic/app_colors.dart';
// ── lib/screens/settings/in_settings/lightning.dart ───────────────────────── // ── lib/screens/settings/in_settings/lightning.dart ─────────────────────────
// Toggle for the lightning strike overlay on the main screen. // Toggle for the lightning strike overlay on the main screen.
//
// Same architecture as haptic.dart: exports a top-level bool read synchronously
// by lib/components/lightning.dart. Default: true (lightning is on — opt-out).
// lib/components/lightning.dart reads this in its build method. final ValueNotifier<bool> lightningEnabled = ValueNotifier(true);
bool lightningEnabled = true;
Future<void> loadLightningPref() async {
final prefs = await SharedPreferences.getInstance();
lightningEnabled.value = prefs.getBool('lightning_effect_enabled') ?? true;
}
class LightningToggleTile extends StatefulWidget { class LightningToggleTile extends StatefulWidget {
const LightningToggleTile({super.key}); const LightningToggleTile({super.key});
@@ -28,16 +29,14 @@ class _LightningToggleTileState extends State<LightningToggleTile> {
} }
Future<void> _load() async { Future<void> _load() async {
final prefs = await SharedPreferences.getInstance(); await loadLightningPref();
final value = prefs.getBool('lightning_effect_enabled') ?? true; if (mounted) setState(() => _on = lightningEnabled.value);
lightningEnabled = value;
if (mounted) setState(() => _on = value);
} }
Future<void> _toggle(bool value) async { Future<void> _toggle(bool value) async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.setBool('lightning_effect_enabled', value); await prefs.setBool('lightning_effect_enabled', value);
lightningEnabled = value; lightningEnabled.value = value;
setState(() => _on = value); setState(() => _on = value);
} }
+9 -10
View File
@@ -4,12 +4,13 @@ import 'package:revoltvpn/logic/app_colors.dart';
// ── lib/screens/settings/in_settings/rain.dart ────────────────────────────── // ── lib/screens/settings/in_settings/rain.dart ──────────────────────────────
// Toggle for the animated rain overlay on the main screen. // Toggle for the animated rain overlay on the main screen.
//
// Same architecture as haptic.dart: exports a top-level bool read synchronously
// by lib/components/rain.dart. Default: true (rain is on — opt-out).
// lib/components/rain.dart reads this in its build method. final ValueNotifier<bool> rainEnabled = ValueNotifier(true);
bool rainEnabled = true;
Future<void> loadRainPref() async {
final prefs = await SharedPreferences.getInstance();
rainEnabled.value = prefs.getBool('rain_effect_enabled') ?? true;
}
class RainToggleTile extends StatefulWidget { class RainToggleTile extends StatefulWidget {
const RainToggleTile({super.key}); const RainToggleTile({super.key});
@@ -28,16 +29,14 @@ class _RainToggleTileState extends State<RainToggleTile> {
} }
Future<void> _load() async { Future<void> _load() async {
final prefs = await SharedPreferences.getInstance(); await loadRainPref();
final value = prefs.getBool('rain_effect_enabled') ?? true; if (mounted) setState(() => _on = rainEnabled.value);
rainEnabled = value;
if (mounted) setState(() => _on = value);
} }
Future<void> _toggle(bool value) async { Future<void> _toggle(bool value) async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.setBool('rain_effect_enabled', value); await prefs.setBool('rain_effect_enabled', value);
rainEnabled = value; rainEnabled.value = value;
setState(() => _on = value); setState(() => _on = value);
} }
+5 -18
View File
@@ -1,23 +1,10 @@
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/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/haptic.dart';
import 'package:revoltvpn/screens/settings/in_settings/rain.dart';
import 'package:revoltvpn/screens/settings/in_settings/lightning.dart'; import 'package:revoltvpn/screens/settings/in_settings/lightning.dart';
import 'package:revoltvpn/screens/settings/in_settings/rain.dart';
// ── lib/screens/settings/settings_screen.dart ────────────────────────────────
// Settings shell — full-screen page reached from the sidebar.
//
// Folder layout:
// lib/screens/settings/ ← this folder: settings family
// settings_screen.dart ← shell: Scaffold + AppBar + ListView (this file)
// *_tile.dart ← one file per setting feature (add below)
// lib/components/sidebar_contents/
// settings.dart ← thin sidebar row that navigates here
//
// To add a setting:
// 1. Create a new file in this folder, e.g. appearance_tile.dart
// 2. Import it below
// 3. Append it to the children list
class SettingsScreen extends StatelessWidget { class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key}); const SettingsScreen({super.key});
@@ -44,11 +31,11 @@ class SettingsScreen extends StatelessWidget {
body: ListView( body: ListView(
padding: const EdgeInsets.symmetric(vertical: 8), padding: const EdgeInsets.symmetric(vertical: 8),
children: const [ children: const [
ConnectionModeTile(),
BackgroundReliabilityTile(),
HapticFeedbackTile(), HapticFeedbackTile(),
RainToggleTile(), RainToggleTile(),
LightningToggleTile(), LightningToggleTile(),
// ── Add setting tiles here ────────────────────────────────────────
// Each tile imports from its own file in this folder.
], ],
), ),
); );
-56
View File
@@ -73,14 +73,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.0.9" 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:
@@ -126,30 +118,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:
@@ -464,14 +432,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:
@@ -621,14 +581,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.11" version: "0.7.11"
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:
@@ -781,14 +733,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:
+1 -2
View File
@@ -15,7 +15,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion. # In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at # Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 3.2.1+24 version: 3.3.4+30
environment: environment:
sdk: ">=3.0.0 <4.0.0" sdk: ">=3.0.0 <4.0.0"
@@ -36,7 +36,6 @@ dependencies:
url_launcher: ^6.3.2 url_launcher: ^6.3.2
flutter_secure_storage: ^10.3.1 flutter_secure_storage: ^10.3.1
uuid: ^4.5.3 uuid: ^4.5.3
flutter_local_notifications: ^17.0.0
path_provider: ^2.1.5 path_provider: ^2.1.5
package_info_plus: ^6.0.0 package_info_plus: ^6.0.0
@@ -0,0 +1,119 @@
import 'dart:convert';
import 'dart:io';
const packageName = 'flutter_vless_android';
const expectedVersionFragment = 'flutter_vless_android-1.1.5';
Never fail(String message) {
stderr.writeln('[flutter_vless recovery patch] $message');
exit(1);
}
Directory packageRoot() {
final configFile = File('.dart_tool/package_config.json');
if (!configFile.existsSync()) {
fail('.dart_tool/package_config.json is missing; run flutter pub get first');
}
final decoded = jsonDecode(configFile.readAsStringSync());
if (decoded is! Map<String, dynamic> || decoded['packages'] is! List) {
fail('package_config.json is invalid');
}
Map<String, dynamic>? package;
for (final item in decoded['packages'] as List) {
if (item is Map && item['name'] == packageName) {
package = Map<String, dynamic>.from(item);
break;
}
}
if (package == null) fail('$packageName was not found');
final rootUriValue = package['rootUri'];
if (rootUriValue is! String || rootUriValue.isEmpty) {
fail('$packageName has no rootUri');
}
final rootUri = Uri.parse(rootUriValue);
final resolved = rootUri.hasScheme
? rootUri
: configFile.parent.absolute.uri.resolveUri(rootUri);
if (resolved.scheme != 'file') fail('unsupported package URI: $resolved');
final root = Directory.fromUri(resolved);
final normalized = root.absolute.path.replaceAll('\\', '/');
if (!normalized.contains(expectedVersionFragment)) {
fail('expected flutter_vless_android 1.1.5, got ${root.path}');
}
if (!root.existsSync()) fail('package root does not exist: ${root.path}');
return root;
}
void replaceOnce(
File file,
String oldValue,
String newValue,
String marker,
) {
if (!file.existsSync()) fail('missing upstream source: ${file.path}');
final text = file.readAsStringSync();
if (text.contains(marker)) {
stdout.writeln('[flutter_vless recovery patch] already current: ${file.path}');
return;
}
if (!text.contains(oldValue)) {
fail('upstream source changed; expected block not found in ${file.path}');
}
file.writeAsStringSync(text.replaceFirst(oldValue, newValue));
stdout.writeln('[flutter_vless recovery patch] patched: ${file.path}');
}
void main() {
final root = packageRoot();
final kotlin = Directory(
'${root.path}/android/src/main/kotlin/com/github/tfox/flutter_vless',
);
final serviceFile = File('${kotlin.path}/xray/service/XrayVPNService.kt');
if (!serviceFile.existsSync()) {
fail('pinned Android runtime service source is missing');
}
// A fast reconnect must not leave the previous Xray process owning the local
// SOCKS/HTTP ports.
replaceOnce(
serviceFile,
''' if (config != null) {
// Ensure clean state before starting
cleanup()
''',
''' if (config != null) {
// A fast reconnect must not leave the previous Xray process
// owning the local SOCKS/HTTP ports.
if (XrayCoreManager.isXrayRunning()) {
Log.w(TAG, "Stopping stale Xray core before restart")
XrayCoreManager.stopCore(this)
}
cleanup()
''',
'Stopping stale Xray core before restart',
);
// The tun2socks Unix socket must not survive a previous session.
replaceOnce(
serviceFile,
''' val tun2socksPath = File(applicationInfo.nativeLibraryDir, "libtun2socks.so").absolutePath
val sockPath = File(filesDir, "sock_path").absolutePath
''',
''' 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
''',
'Could not delete stale tun2socks socket',
);
stdout.writeln('[flutter_vless recovery patch] runtime recovery patch is ready');
}
@@ -0,0 +1,154 @@
import 'dart:convert';
import 'dart:io';
const packageName = 'flutter_vless_android';
const expectedVersionFragment = 'flutter_vless_android-1.1.5';
Never fail(String message) {
stderr.writeln('[secure-socks scope fix] $message');
exit(1);
}
Directory packageRoot() {
final configFile = File('.dart_tool/package_config.json');
if (!configFile.existsSync()) {
fail('.dart_tool/package_config.json is missing; run flutter pub get first');
}
final decoded = jsonDecode(configFile.readAsStringSync());
if (decoded is! Map<String, dynamic> || decoded['packages'] is! List) {
fail('package_config.json is invalid');
}
Map<String, dynamic>? package;
for (final item in decoded['packages'] as List) {
if (item is Map && item['name'] == packageName) {
package = Map<String, dynamic>.from(item);
break;
}
}
if (package == null) fail('$packageName was not found');
final rootUriValue = package['rootUri'];
if (rootUriValue is! String || rootUriValue.isEmpty) {
fail('$packageName has no rootUri');
}
final rootUri = Uri.parse(rootUriValue);
final resolved = rootUri.hasScheme
? rootUri
: configFile.parent.absolute.uri.resolveUri(rootUri);
if (resolved.scheme != 'file') fail('unsupported package URI: $resolved');
final root = Directory.fromUri(resolved);
final normalized = root.absolute.path.replaceAll('\\', '/');
if (!normalized.contains(expectedVersionFragment)) {
fail('expected flutter_vless_android 1.1.5, got ${root.path}');
}
return root;
}
void patchCoreScope(File core) {
final before = core.readAsStringSync();
// The primary secure patcher used a file-wide check for
// `val process = pb.start()`. Stock 1.1.5 already contains that exact line
// in getV2rayTraffic(), so the startCore() capture could be skipped while
// its monitor was still rewritten to use `process`. Capture the active Xray
// process immediately before its monitor thread instead. This is deliberately
// a scope-only correction and does not alter the stable runtime sequence.
const directCapture =
' val process = pb.start()\n xrayProcess = process\n';
const scopedCapture =
' val process = xrayProcess ?: return false\n // Monitor process in a separate thread to detect crash\n';
const monitorMarker =
' // Monitor process in a separate thread to detect crash\n';
if (before.contains(directCapture) || before.contains(scopedCapture)) {
stdout.writeln('[secure-socks scope fix] core already current: ${core.path}');
return;
}
if (!before.contains('process.inputStream.bufferedReader().use { reader ->') ||
!before.contains('val exitCode = process.waitFor()') ||
!before.contains('xrayProcess === process')) {
fail('secure Xray monitor patch is not in the expected state');
}
if (!before.contains(' xrayProcess = pb.start()\n')) {
fail('stock Xray start assignment is missing');
}
if (!before.contains(monitorMarker)) {
fail('Xray monitor insertion point is missing');
}
final after = before.replaceFirst(monitorMarker, scopedCapture);
core.writeAsStringSync(after);
stdout.writeln('[secure-socks scope fix] captured Xray process for monitor scope');
}
void patchOngoingNotification(File service) {
final before = service.readAsStringSync();
const marker = '.setOngoing(true)';
if (before.contains(marker) &&
before.contains('Notification.FLAG_NO_CLEAR') &&
before.contains('.setAutoCancel(false)')) {
stdout.writeln('[secure-socks scope fix] notification already ongoing: ${service.path}');
return;
}
const oldBlock = r''' return builder
.setContentTitle("VPN Service")
.setContentText(content)
.setSmallIcon(icon)
.build()
''';
const newBlock = r''' val notification = builder
.setContentTitle("VPN Service")
.setContentText(content)
.setSmallIcon(icon)
.setOngoing(true)
.setAutoCancel(false)
.setOnlyAlertOnce(true)
.build()
// Keep the active VPN notification attached to the foreground service
// and resistant to bulk clearing on Android versions that honor these
// flags. Android 14+ may still allow an explicit user swipe while the
// device is unlocked; apps are not allowed to override that system UI.
notification.flags = notification.flags or
android.app.Notification.FLAG_ONGOING_EVENT or
android.app.Notification.FLAG_NO_CLEAR
return notification
''';
if (!before.contains(oldBlock)) {
fail('VPN notification builder is not in the expected stock 1.1.5 state');
}
final after = before.replaceFirst(oldBlock, newBlock);
if (!after.contains(marker) ||
!after.contains('Notification.FLAG_NO_CLEAR') ||
!after.contains('.setAutoCancel(false)')) {
fail('ongoing VPN notification invariant failed');
}
service.writeAsStringSync(after);
stdout.writeln('[secure-socks scope fix] VPN notification marked ongoing/no-clear');
}
void main() {
final root = packageRoot();
final kotlin =
'${root.path}/android/src/main/kotlin/com/github/tfox/flutter_vless';
final core = File('$kotlin/xray/core/XrayCoreManager.kt');
final service = File('$kotlin/xray/service/XrayVPNService.kt');
if (!core.existsSync()) fail('XrayCoreManager.kt is missing');
if (!service.existsSync()) fail('XrayVPNService.kt is missing');
patchCoreScope(core);
patchOngoingNotification(service);
stdout.writeln('[secure-socks scope fix] scope and notification patch ready');
}
@@ -0,0 +1,746 @@
import 'dart:convert';
import 'dart:io';
const packageName = 'flutter_vless_android';
const expectedVersionFragment = 'flutter_vless_android-1.1.5';
Never fail(String message) {
stderr.writeln('[secure-socks patch] $message');
exit(1);
}
Directory packageRoot() {
final configFile = File('.dart_tool/package_config.json');
if (!configFile.existsSync()) {
fail('.dart_tool/package_config.json is missing; run flutter pub get first');
}
final decoded = jsonDecode(configFile.readAsStringSync());
if (decoded is! Map<String, dynamic> || decoded['packages'] is! List) {
fail('package_config.json is invalid');
}
Map<String, dynamic>? package;
for (final item in decoded['packages'] as List) {
if (item is Map && item['name'] == packageName) {
package = Map<String, dynamic>.from(item);
break;
}
}
if (package == null) fail('$packageName was not found');
final rootUriValue = package['rootUri'];
if (rootUriValue is! String || rootUriValue.isEmpty) {
fail('$packageName has no rootUri');
}
final rootUri = Uri.parse(rootUriValue);
final resolved = rootUri.hasScheme
? rootUri
: configFile.parent.absolute.uri.resolveUri(rootUri);
if (resolved.scheme != 'file') fail('unsupported package URI: $resolved');
final root = Directory.fromUri(resolved);
final normalized = root.absolute.path.replaceAll('\\', '/');
if (!normalized.contains(expectedVersionFragment)) {
fail('expected flutter_vless_android 1.1.5, got ${root.path}');
}
return root;
}
String replaceOnce(
String text,
String oldValue,
String newValue,
String label,
) {
if (text.contains(newValue)) return text;
if (!text.contains(oldValue)) fail('missing expected source block: $label');
return text.replaceFirst(oldValue, newValue);
}
void writeIfChanged(File file, String before, String after) {
if (before == after) {
stdout.writeln('[secure-socks patch] already current: ${file.path}');
return;
}
file.writeAsStringSync(after);
stdout.writeln('[secure-socks patch] patched: ${file.path}');
}
void patchCore(File file) {
final before = file.readAsStringSync();
var text = before;
const secureValidation = r''' 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
}
''';
if (!text.contains('var secureSocksEnabled = false')) {
text = replaceOnce(
text,
' val usedPorts = mutableSetOf<Int>()\n',
'$secureValidation val usedPorts = mutableSetOf<Int>()\n',
'secure SOCKS validation insertion',
);
}
text = replaceOnce(
text,
' if (!hasHttpOnLocalPort) {\n',
' if (!secureSocksEnabled && !hasHttpOnLocalPort) {\n',
'disable unauthenticated HTTP proxy in secure mode',
);
if (!text.contains('val process = pb.start()')) {
text = replaceOnce(
text,
' xrayProcess = pb.start()\n',
' val process = pb.start()\n xrayProcess = process\n',
'capture Xray process identity',
);
text = replaceOnce(
text,
' if (xrayProcess?.isAlive != true) {\n',
' if (!process.isAlive) {\n',
'Xray startup liveness',
);
text = replaceOnce(
text,
' val output = xrayProcess?.inputStream?.bufferedReader()?.readText().orEmpty()\n',
' val output = process.inputStream.bufferedReader().readText()\n',
'Xray startup output',
);
}
if (!text.contains('Could not delete ephemeral Xray config')) {
const connectedLine =
' AppConfigs.V2RAY_STATE = AppConfigs.V2RAY_STATES.V2RAY_CONNECTED\n';
const deleteConfig = r''' // 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)
}
''';
text = replaceOnce(
text,
connectedLine,
'$deleteConfig$connectedLine',
'ephemeral config deletion',
);
}
if (!text.contains('context.handleXrayCoreExit(config)')) {
text = replaceOnce(
text,
' xrayProcess?.inputStream?.bufferedReader()?.use { reader ->\n',
' process.inputStream.bufferedReader().use { reader ->\n',
'Xray monitor process stream',
);
text = replaceOnce(
text,
' val exitCode = xrayProcess?.waitFor()\n',
' val exitCode = process.waitFor()\n',
'Xray monitor process wait',
);
const oldExit = r''' if (AppConfigs.V2RAY_STATE == AppConfigs.V2RAY_STATES.V2RAY_CONNECTED) {
// Unexpected exit
stopCore(context)
}
''';
const newExit = r''' if (xrayProcess === process &&
AppConfigs.V2RAY_STATE == AppConfigs.V2RAY_STATES.V2RAY_CONNECTED
) {
// Hold the Android TUN while the core is recovered. Killing
// the VPN service here would allow direct-network fallback.
xrayProcess = null
AppConfigs.V2RAY_STATE = AppConfigs.V2RAY_STATES.V2RAY_CONNECTING
if (context is XrayVPNService) {
context.handleXrayCoreExit(config)
} else {
stopCore(context)
}
}
''';
text = replaceOnce(text, oldExit, newExit, 'Xray fail-closed recovery');
}
writeIfChanged(file, before, text);
}
void patchService(File file) {
final before = file.readAsStringSync();
var text = before;
if (!text.contains('private var recoveringXray = false')) {
text = replaceOnce(
text,
' private var isRunning = false\n',
' @Volatile private var isRunning = false\n'
' @Volatile private var recoveringXray = false\n'
' private var currentConfig: XrayConfig? = null\n',
'service recovery fields',
);
}
if (!text.contains('private data class PersistedSession(')) {
const persistenceHelpers = r''' private data class PersistedSession(
val proxyOnly: Boolean,
val config: XrayConfig,
val sessionExpiresAtMs: Long,
) : java.io.Serializable
private var proxyOnlyMode = false
private var sessionExpiresAtMs = 0L
private val expiryHandler = android.os.Handler(android.os.Looper.getMainLooper())
private val expiryRunnable = Runnable {
if (sessionExpiresAtMs > 0 && System.currentTimeMillis() >= sessionExpiresAtMs) {
Log.w(TAG, "Session expired; tearing down VPN")
sessionExpiresAtMs = 0L
cancelExpiryAlarm()
postSessionExpiredNotification()
deletePersistedSession()
stopAll()
}
}
private fun scheduleExpiryCheck() {
expiryHandler.removeCallbacks(expiryRunnable)
if (sessionExpiresAtMs > 0) {
val delay = (sessionExpiresAtMs - System.currentTimeMillis()).coerceAtLeast(0)
expiryHandler.postDelayed(expiryRunnable, delay)
}
scheduleExpiryAlarm()
}
private fun scheduleExpiryAlarm() {
cancelExpiryAlarm()
if (sessionExpiresAtMs <= 0) return
try {
val alarmManager = getSystemService(android.content.Context.ALARM_SERVICE) as android.app.AlarmManager
try {
alarmManager.setExactAndAllowWhileIdle(
android.app.AlarmManager.RTC_WAKEUP,
sessionExpiresAtMs,
sessionExpiredPendingIntent(),
)
} catch (e: SecurityException) {
alarmManager.setAndAllowWhileIdle(
android.app.AlarmManager.RTC_WAKEUP,
sessionExpiresAtMs,
sessionExpiredPendingIntent(),
)
}
} catch (e: Exception) {
Log.w(TAG, "Failed to schedule expiry alarm", e)
}
}
private fun cancelExpiryAlarm() {
try {
val alarmManager = getSystemService(android.content.Context.ALARM_SERVICE) as android.app.AlarmManager
alarmManager.cancel(sessionExpiredPendingIntent())
} catch (e: Exception) {
}
}
private fun sessionExpiredPendingIntent(): android.app.PendingIntent {
val intent = Intent(this, XrayVPNService::class.java)
intent.putExtra("SESSION_EXPIRED", true)
val flags = android.app.PendingIntent.FLAG_UPDATE_CURRENT or
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
android.app.PendingIntent.FLAG_IMMUTABLE
} else {
0
}
return android.app.PendingIntent.getService(this, 1001, intent, flags)
}
private fun persistSession() {
val config = currentConfig ?: return
try {
java.io.ObjectOutputStream(
java.io.FileOutputStream(File(filesDir, "active_session.bin")),
).use { it.writeObject(PersistedSession(proxyOnlyMode, config, sessionExpiresAtMs)) }
} catch (e: Exception) {
Log.w(TAG, "Failed to persist active session", e)
}
}
private fun loadPersistedSession(): PersistedSession? {
return try {
val file = File(filesDir, "active_session.bin")
if (!file.exists()) return null
java.io.ObjectInputStream(java.io.FileInputStream(file)).use {
it.readObject() as? PersistedSession
}
} catch (e: Exception) {
Log.w(TAG, "Failed to restore persisted session", e)
null
}
}
private fun deletePersistedSession() {
try {
File(filesDir, "active_session.bin").delete()
} catch (e: Exception) {
Log.w(TAG, "Failed to delete persisted session", e)
}
}
private fun postSessionExpiredNotification() {
try {
createNotificationChannel()
val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
android.app.PendingIntent.FLAG_IMMUTABLE or android.app.PendingIntent.FLAG_UPDATE_CURRENT
} else {
android.app.PendingIntent.FLAG_UPDATE_CURRENT
}
val contentIntent = if (launchIntent != null) {
android.app.PendingIntent.getActivity(this, 0, launchIntent, flags)
} else {
null
}
val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
android.app.Notification.Builder(this, "vpn_service_channel")
} else {
@Suppress("DEPRECATION")
android.app.Notification.Builder(this)
}
builder
.setContentTitle("Revolt VPN")
.setContentText("Session expired. Reconnect to continue.")
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setAutoCancel(true)
if (contentIntent != null) {
builder.setContentIntent(contentIntent)
}
val manager = getSystemService(android.app.NotificationManager::class.java)
manager?.notify(2, builder.build())
} catch (e: Exception) {
Log.w(TAG, "Failed to post session expired notification", e)
}
}
''';
text = replaceOnce(
text,
' override fun onCreate() {\n super.onCreate()\n }\n',
' override fun onCreate() {\n super.onCreate()\n }\n\n$persistenceHelpers',
'session persistence helpers',
);
}
// Snapshot the running config so a START_STICKY restart can re-establish it.
if (!text.contains(' currentConfig = config\n')) {
text = replaceOnce(
text,
' cleanup()\n',
' cleanup()\n currentConfig = config\n',
'runtime config snapshot',
);
}
text = replaceOnce(
text,
' val proxyOnly = intent.getBooleanExtra("PROXY_ONLY", false)\n',
' val proxyOnly = intent.getBooleanExtra("PROXY_ONLY", false)\n proxyOnlyMode = proxyOnly\n persistSession()\n',
'persist session snapshot',
);
text = replaceOnce(
text,
' if (command == AppConfigs.V2RAY_SERVICE_COMMANDS.STOP_SERVICE) {\n stopAll()\n return START_NOT_STICKY\n }\n',
' if (command == AppConfigs.V2RAY_SERVICE_COMMANDS.STOP_SERVICE) {\n deletePersistedSession()\n stopAll()\n return START_NOT_STICKY\n }\n',
'delete session on explicit stop',
);
const oldNullIntent = r''' if (intent == null) {
stopSelf()
return START_NOT_STICKY
}
''';
const newNullIntent = r''' if (intent == null) {
if (isRunning && currentConfig != null) return START_STICKY
val persisted = loadPersistedSession()
if (persisted != null) {
Log.w(TAG, "Re-establishing VPN from persisted session")
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)
}
if (XrayCoreManager.isXrayRunning()) {
Log.w(TAG, "Stopping stale Xray core before restart")
XrayCoreManager.stopCore(this)
}
cleanup()
currentConfig = persisted.config
proxyOnlyMode = persisted.proxyOnly
sessionExpiresAtMs = persisted.sessionExpiresAtMs
if (XrayCoreManager.startCore(this, persisted.config)) {
if (!persisted.proxyOnly) {
setupVpn(persisted.config)
} else {
isRunning = true
}
scheduleExpiryCheck()
} else {
stopSelf()
return START_NOT_STICKY
}
return START_STICKY
}
stopSelf()
return START_NOT_STICKY
}
''';
text = replaceOnce(
text,
oldNullIntent,
newNullIntent,
'null intent lifecycle',
);
text = replaceOnce(
text,
' val command = if (Build.VERSION.SDK_INT >= 33) {\n',
' if (intent.getBooleanExtra("SESSION_EXPIRED", false)) {\n Log.w(TAG, "Session-expiry alarm fired; tearing down VPN")\n sessionExpiresAtMs = 0L\n cancelExpiryAlarm()\n deletePersistedSession()\n postSessionExpiredNotification()\n stopAll()\n return START_NOT_STICKY\n }\n\n if (intent.hasExtra("SESSION_EXPIRES_AT_MS")) {\n sessionExpiresAtMs = intent.getLongExtra("SESSION_EXPIRES_AT_MS", 0L)\n scheduleExpiryCheck()\n persistSession()\n return if (isRunning && currentConfig != null) START_STICKY else START_NOT_STICKY\n }\n\n val command = if (Build.VERSION.SDK_INT >= 33) {\n',
'session expiry update',
);
if (!text.contains('private data class SecureSocksCredentials(')) {
const credentialsHelper = r''' 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
}
''';
const runComment = r''' /**
* Starts the tun2socks process and initiates the FD transfer.
*/
private fun runTun2socks(config: XrayConfig) {
''';
text = replaceOnce(
text,
runComment,
'$credentialsHelper$runComment',
'secure credentials helper',
);
}
if (!text.contains('Authenticated ReVolt SOCKS5 inbound missing')) {
const commandComment = r''' // Command to start tun2socks.
// Note: We pass -sock-path to tell it where to listen for the FD.
''';
const securePrelude = r''' val secure = secureSocksCredentials(config)
?: throw IllegalStateException("Authenticated ReVolt SOCKS5 inbound missing")
config.LOCAL_SOCKS5_PORT = secure.port
''';
text = replaceOnce(
text,
commandComment,
'$securePrelude$commandComment',
'secure tun2socks credentials',
);
text = replaceOnce(
text,
r''' "-proxy", "socks5://127.0.0.1:${config.LOCAL_SOCKS5_PORT}",
''',
r''' "-proxy", "socks5://${secure.username}:${secure.password}@127.0.0.1:${secure.port}",
''',
'authenticated tun2socks URL',
);
text = replaceOnce(
text,
r''' Log.d(TAG, "tun2socks command: ${cmd.joinToString(" ")}")
''',
' Log.d(TAG, "Starting tun2socks with authenticated loopback SOCKS5")\n',
'credential-safe logging',
);
}
if (!text.contains('val process = pb.start()\n tun2socksProcess = process')) {
text = replaceOnce(
text,
' tun2socksProcess = pb.start()\n',
' val process = pb.start()\n tun2socksProcess = process\n',
'capture tun2socks process identity',
);
text = replaceOnce(
text,
' tun2socksProcess?.inputStream?.bufferedReader()?.use { reader ->\n',
' process.inputStream.bufferedReader().use { reader ->\n',
'tun2socks monitor stream',
);
text = replaceOnce(
text,
' tun2socksProcess?.waitFor()\n',
' process.waitFor()\n',
'tun2socks monitor wait',
);
const oldRestart = r''' if (isRunning) {
// Restart if crashed and still supposed to be running
Log.e(TAG, "tun2socks exited unexpectedly, restarting...")
runTun2socks(config)
}
''';
const newRestart = r''' if (isRunning && tun2socksProcess === process && currentConfig === config) {
Log.e(TAG, "tun2socks exited unexpectedly, recycling without dropping TUN")
Thread.sleep(350)
if (isRunning && currentConfig === config) runTun2socks(config)
}
''';
text = replaceOnce(
text,
oldRestart,
newRestart,
'tun2socks crash recovery',
);
text = replaceOnce(
text,
' sendFd()\n',
' sendFd(process)\n',
'FD handoff process identity',
);
}
const oldStartFailure = r''' } catch (e: Exception) {
Log.e(TAG, "Failed to start tun2socks", e)
stopAll()
}
''';
const newStartFailure = r''' } catch (e: Exception) {
Log.e(TAG, "Failed to start tun2socks; retrying with TUN held", e)
if (isRunning && currentConfig === config) {
Thread {
try {
Thread.sleep(600)
if (isRunning && currentConfig === config) runTun2socks(config)
} catch (_: InterruptedException) {}
}.start()
}
}
''';
text = replaceOnce(
text,
oldStartFailure,
newStartFailure,
'tun2socks start failure recovery',
);
if (!text.contains('FD handoff failed; recycling tun2socks without dropping TUN')) {
const oldSendFd = r''' private fun sendFd() {
val fd = mInterface?.fileDescriptor ?: return
val sockFile = File(filesDir, "sock_path").absolutePath
Thread {
var tries = 0
while (tries < 10) {
try {
Thread.sleep(500)
val localSocket = LocalSocket()
localSocket.connect(LocalSocketAddress(sockFile, LocalSocketAddress.Namespace.FILESYSTEM))
val out = localSocket.outputStream
// This magic call attaches the FD to the socket message
localSocket.setFileDescriptorsForSend(arrayOf(fd))
out.write(32) // Send a dummy byte to trigger the transfer
localSocket.setFileDescriptorsForSend(null)
localSocket.shutdownOutput()
localSocket.close()
break
} catch (e: Exception) {
tries++
}
}
}.start()
}
''';
const newSendFd = r''' private fun sendFd(process: Process) {
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()
return@Thread
} catch (_: Exception) {
tries++
try { localSocket?.close() } catch (_: Exception) {}
}
}
if (isRunning && tun2socksProcess === process) {
Log.e(TAG, "FD handoff failed; recycling tun2socks without dropping TUN")
try { process.destroy() } catch (_: Exception) {}
}
}.start()
}
''';
text = replaceOnce(text, oldSendFd, newSendFd, 'bounded FD recovery');
}
if (!text.contains('fun handleXrayCoreExit(config: XrayConfig)')) {
const cleanupComment = r''' /**
* Cleans up resources (tun2socks process, VPN interface) without stopping the service completely.
* Used when restarting or switching configurations.
*/
''';
const recovery = r''' fun handleXrayCoreExit(config: XrayConfig) {
if (!isRunning || currentConfig !== config || recoveringXray) return
recoveringXray = true
Thread {
var attempt = 0
try {
while (isRunning && currentConfig === config) {
attempt++
Thread.sleep(400L * attempt.coerceAtMost(5))
if (!isRunning || currentConfig !== config) break
Log.w(TAG, "Recovering Xray core attempt $attempt")
if (XrayCoreManager.startCore(this, config)) {
Log.w(TAG, "Xray core recovered without dropping TUN")
return@Thread
}
if (attempt >= 3) {
attempt = 0
Thread.sleep(3000)
}
}
} catch (_: InterruptedException) {
} finally {
recoveringXray = false
}
}.start()
}
''';
text = replaceOnce(
text,
cleanupComment,
'$recovery$cleanupComment',
'Xray recovery loop',
);
}
if (!text.contains(' cancelExpiryAlarm()\n tun2socksProcess?.destroy()')) {
text = replaceOnce(
text,
' isRunning = false\n tun2socksProcess?.destroy()\n',
' isRunning = false\n recoveringXray = false\n expiryHandler.removeCallbacks(expiryRunnable)\n cancelExpiryAlarm()\n tun2socksProcess?.destroy()\n',
'cancel recovery and expiry on cleanup',
);
}
if (!text.contains(' currentConfig = null\n XrayCoreManager.stopCore(this)')) {
text = replaceOnce(
text,
' cleanup()\n XrayCoreManager.stopCore(this)\n',
' cleanup()\n currentConfig = null\n XrayCoreManager.stopCore(this)\n',
'clear config on explicit stop',
);
}
writeIfChanged(file, before, text);
}
void main() {
final root = packageRoot();
final kotlin = Directory(
'${root.path}/android/src/main/kotlin/com/github/tfox/flutter_vless',
);
final core = File('${kotlin.path}/xray/core/XrayCoreManager.kt');
final service = File('${kotlin.path}/xray/service/XrayVPNService.kt');
if (!core.existsSync() || !service.existsSync()) {
fail('pinned Android runtime sources are missing');
}
patchCore(core);
patchService(service);
stdout.writeln('[secure-socks patch] stable-core security patch is ready');
}