Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ac236a981 | ||
|
|
dfeb7f161c | ||
|
|
186dc906da | ||
|
|
ac52681452 | ||
|
|
ebaa2fc516 | ||
|
|
6fcde9dd7b | ||
|
|
a71161e7e5 | ||
|
|
da82a833cb | ||
|
|
0ab008b80b | ||
|
|
f7f425517c | ||
|
|
76bf84453f | ||
|
|
6c99366602 | ||
|
|
8ead3ff249 | ||
|
|
371db8da9f | ||
|
|
8a89af3c62 | ||
|
|
62104d5730 | ||
|
|
4eb1fca666 | ||
|
|
71468f7594 | ||
|
|
6adf03f920 | ||
|
|
5642b0b811 | ||
|
|
096fbf5a97 | ||
|
|
6c137245fd | ||
|
|
cc819abc41 | ||
|
|
d696bda63f | ||
|
|
61c72b2200 | ||
|
|
54f949ca8e | ||
|
|
cf50c3a01b | ||
|
|
04ec8ac5d1 | ||
|
|
56ea53e73b | ||
|
|
143f5f4eff | ||
|
|
abcb41fb06 | ||
|
|
e2359419bc | ||
|
|
2d0628c5bb | ||
|
|
4fde4a9217 | ||
|
|
75cf59f22c | ||
|
|
c1ec77a075 | ||
|
|
1b8a67cecb | ||
|
|
c5148e138d | ||
|
|
832c2d0a2d | ||
|
|
7f40a82997 | ||
|
|
fd6b358929 | ||
|
|
4555911ee8 | ||
|
|
54609a3119 | ||
|
|
e1c5d5b106 | ||
|
|
adf6de5dc0 | ||
|
|
81d0387612 | ||
|
|
33522dfeaf | ||
|
|
f8abda9323 | ||
|
|
f01a610182 | ||
|
|
d6c56e8345 | ||
|
|
96584082cf | ||
|
|
66e89d8d28 |
No files matched your search
@@ -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
|
||||
@@ -1,38 +1,60 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
.java-version
|
||||
# =============================================================================
|
||||
# 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.
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
# =============================================================================
|
||||
|
||||
# The .vscode folder contains configure files for the Visual Studio Code
|
||||
# editor. Although we may keep it, we often ignore it.
|
||||
.vscode/
|
||||
# ── Secrets ────────────────────────────────────────────────────────────────
|
||||
*.keystore
|
||||
*.jks
|
||||
android/key.properties
|
||||
android/admob.properties
|
||||
|
||||
# Python cache & User files
|
||||
TECHNICAL_DEBT.md
|
||||
RUNNING.md
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# App Config (Hide real IPs/IDs from GitHub)
|
||||
# Real IPs and IDs. app_config.example.dart is the committed template.
|
||||
lib/logic/app_config.dart
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
**/doc/api/
|
||||
**/ios/Flutter/.last_build_id
|
||||
# ── File types the shipped app does not contain ────────────────────────────
|
||||
*.py
|
||||
*.pyc
|
||||
*.json
|
||||
*.conf
|
||||
*.sh
|
||||
*.txt
|
||||
*.html
|
||||
*.zip
|
||||
*.log
|
||||
*.class
|
||||
|
||||
# ── Documentation ──────────────────────────────────────────────────────────
|
||||
# The published set is allow-listed; anything else, at any depth, is not.
|
||||
# Leading slashes anchor these to the repo root so a same-named file in a
|
||||
# subdirectory is NOT re-included by the negation.
|
||||
*.md
|
||||
!/README.md
|
||||
!/CHANGELOG.md
|
||||
!/CONTRIBUTING.md
|
||||
!/PRIVACY_POLICY.md
|
||||
|
||||
# ── Working directories ────────────────────────────────────────────────────
|
||||
# Material that is not part of the app. These need directory rules rather
|
||||
# than type rules, because they can hold source-file types the rules above
|
||||
# deliberately do not cover.
|
||||
.local/
|
||||
internal/
|
||||
hivemind/
|
||||
scraped/
|
||||
backup/
|
||||
backups/
|
||||
lib/logic/backup/
|
||||
server_files/
|
||||
|
||||
# ── Flutter / Dart build output ────────────────────────────────────────────
|
||||
.dart_tool/
|
||||
*.dart_tool/
|
||||
.flutter-plugins
|
||||
.flutter-plugins-dependencies
|
||||
.pub-cache/
|
||||
@@ -41,50 +63,35 @@ build/
|
||||
**/build/
|
||||
local_packages/*/build/
|
||||
local_packages/*/.dart_tool/
|
||||
*.dart_tool/
|
||||
**/doc/api/
|
||||
**/ios/Flutter/.last_build_id
|
||||
|
||||
# Android related
|
||||
**/android/**/gradle-wrapper.jar
|
||||
# ── Android build output ───────────────────────────────────────────────────
|
||||
**/android/.gradle
|
||||
**/android/.cxx/
|
||||
**/android/app/build/
|
||||
**/android/captures/
|
||||
**/android/gradlew
|
||||
**/android/gradlew.bat
|
||||
**/android/local.properties
|
||||
**/android/**/gradle-wrapper.jar
|
||||
**/android/**/GeneratedPluginRegistrant.java
|
||||
**/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java
|
||||
**/android/.cxx/
|
||||
**/android/app/build/
|
||||
|
||||
# Keystore files
|
||||
*.keystore
|
||||
*.jks
|
||||
|
||||
# Crashlytics cache
|
||||
**/android/app/crashlytics-build.properties
|
||||
|
||||
# Shell scripts (dev only, not for public)
|
||||
server_picture.sh
|
||||
XRAY_CONFIG_REFERENCE.md
|
||||
# ── Editors, tooling & OS ──────────────────────────────────────────────────
|
||||
.claude/
|
||||
.codewhale/
|
||||
.idea/
|
||||
.vscode/
|
||||
.atom/
|
||||
.history
|
||||
.svn/
|
||||
.java-version
|
||||
.DS_Store
|
||||
*.swp
|
||||
__pycache__/
|
||||
devtools_options.yaml
|
||||
|
||||
# Secrets
|
||||
android/key.properties
|
||||
android/admob.properties
|
||||
SECURITY_HARDENING.md
|
||||
VLESS_APP_CONTRACT.md
|
||||
AGENTS.md
|
||||
SERVER_NOTES.md
|
||||
lib/logic/backup/
|
||||
00-FULL-REPORT.md
|
||||
server full picture.txt
|
||||
technical_debt_*.md
|
||||
server_full_picture_2.txt
|
||||
hivemind_backup.py
|
||||
UI_POSITIONING.md
|
||||
SERVER_SETUP.md
|
||||
REALITY_MIGRATION_PLAN.md
|
||||
xray_config_reality.json
|
||||
SERVER_DEPLOYMENT.md
|
||||
swarm_watch.py
|
||||
nginx_hivemind_reality.conf
|
||||
nginx_hivemind_reality.conf
|
||||
nginx_hivemind_reality.conf
|
||||
#why are you even looking at this file? it's a secret. go away.
|
||||
whatsthis
|
||||
@@ -0,0 +1,414 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to the ReVoltVPN Flutter app.
|
||||
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
|
||||
|
||||
### Google Play compliance
|
||||
- Added first-launch data disclosure dialog ("Before you connect") explaining
|
||||
that connection duration and data usage are logged for quota enforcement, and
|
||||
that traffic content is never monitored.
|
||||
|
||||
## [3.2.0] — 2026-08-08
|
||||
|
||||
### DPI hardening
|
||||
- Spoof Chrome-on-Android User-Agent on all API calls instead of `Dart/3.x`.
|
||||
- Renamed domain from `getrevolt.app` to `userevolt.app`.
|
||||
|
||||
### Branding
|
||||
- App name changed from "REVOLT VPN" to "Revolt VPN" across manifest, splash,
|
||||
notification, and VLESS URL remark.
|
||||
|
||||
### Notification
|
||||
- Removed duplicate `flutter_local_notifications` notification. Only the
|
||||
Android VPN foreground-service notification remains — non-swipeable.
|
||||
- Patched `flutter_vless` native code to use custom notification icon
|
||||
(`@drawable/notification_icon`) with dark background (`#0D1117`).
|
||||
|
||||
### Connection reliability
|
||||
- Merged five separate disconnect paths into a single idempotent
|
||||
`_doDisconnect()` gate. Eliminated race between timer ticks and VPN
|
||||
teardown where the countdown could briefly show -1.
|
||||
- `stopVless()` timeout (5 s) now correctly shows an error instead of
|
||||
silently pretending the VPN disconnected while the tunnel was still alive.
|
||||
|
||||
### AdMob bypass
|
||||
- `kDebugMode` guard removed — the debug AdMob callback now fires in release
|
||||
builds so release APKs can create sessions without real ads during testing.
|
||||
The real gate is `ADMOB_BYPASS` on the server.
|
||||
|
||||
### Fixed
|
||||
- **Notification icon:** Replaced five density-specific `ic_launcher.png`
|
||||
files with `notification_icon.png`, then reverted to avoid changing the
|
||||
home-screen icon. The custom icon is now injected through flutter_vless's
|
||||
`initializeVless()` parameters.
|
||||
|
||||
## [3.1.0] — 2026-08-06
|
||||
|
||||
### Architecture — domain-free client
|
||||
- **Zero domain strings in APK.** RKN has nothing to DNS-block. API calls go
|
||||
through the Reality tunnel to `10.254.254.1:5000`, redirected to Flask by
|
||||
Xray's `api` freedom outbound (`redirect: 127.0.0.1:5000`).
|
||||
- **Bootstrap tunnel.** Bundled Reality config in APK → connect → fetch real
|
||||
per-session VLESS URL from inside the tunnel → reconnect. Bootstrap client
|
||||
permanently in `xray_config_reality.json`, restricted by Xray routing to
|
||||
internal API only.
|
||||
- `serverDomain` removed from `AppConfig`. `fetchConfigThroughTunnel()`
|
||||
replaces `fetchConfigWithPolling()`. `connect()` rewritten.
|
||||
|
||||
### Protocol — TCP to XHTTP
|
||||
- Transport: TCP → XHTTP (H2 stream-up with Reality). No more XTLS-Vision,
|
||||
no `flow` field. Path-hidden behind `/revolt`.
|
||||
|
||||
### Fixed
|
||||
- **RenderFlex overflow** — status bar text wrapped in `Flexible` with
|
||||
`TextOverflow.ellipsis` to prevent overflow on narrow screens (≤360dp).
|
||||
- **Circular import** — removed `import 'package:revoltvpn/main.dart'` from
|
||||
`sidebar_drawer.dart`. `SidebarDrawer` converted to `StatefulWidget`;
|
||||
version footer loaded via `PackageInfo.fromPlatform()`.
|
||||
- Client hot-reload was silently broken — `xray api adi` no-op. Fixed:
|
||||
`adu`/`rmu` commands per Xray HandlerService spec.
|
||||
- Missing XHTTP `path` param in VLESS URL — now reads `xhttp_path` from
|
||||
`/session/status`.
|
||||
- `providerBundleIdentifier` was `com.revoltvpn.app` — must match
|
||||
`com.paladinvpn.app` for VPN service registration.
|
||||
- Reality keypair generated (was placeholder). Throttle `uplinkOnly`/`downlinkOnly`
|
||||
corrected (seconds, not bytes/sec). Fallback rate limits removed (fingerprint).
|
||||
|
||||
### Added
|
||||
- **Settings screen** — reached from a new sidebar row (between Website and
|
||||
Check for updates). Slide-from-right navigation via `PageRouteBuilder`.
|
||||
Folder: `lib/screens/settings/` with one file per feature in `in_settings/`.
|
||||
- **Haptic feedback toggle** — on/off switch in Settings for `lightImpact()`
|
||||
vibration on successful connect/disconnect. Default: off. Uses sync-bool
|
||||
pattern (no await on tap, no SharedPreferences in connect button).
|
||||
- **Rain/Lightning effect toggles** — two switches in Settings to control
|
||||
the animated background effects. Default: on. Effects detect the toggle
|
||||
within one frame (no Provider/notifier needed).
|
||||
|
||||
### Changed
|
||||
- **Timer box spinner removed** — the "Connecting…"/"Syncing…" spinner under
|
||||
the countdown was redundant with the connect button's spinner. Timer card
|
||||
is now a clean countdown only (gray '00:00:00' when idle).
|
||||
- **Sidebar** now has 7 rows (added Settings). `FRONTEND_POLISH_REVIEW.md`
|
||||
fully triaged: 4 items fixed, 11 skipped.
|
||||
|
||||
### Server
|
||||
- `api` outbound + 3 routing rules in `xray_config_reality.json` (bootstrap
|
||||
isolation + API routing). Permanent bootstrap client. Hivemind unchanged.
|
||||
- `xhttp_path` in `/session/status` response.
|
||||
- Full deployment guide: `SERVER_DEPLOYMENT.md`.
|
||||
|
||||
---
|
||||
|
||||
## [2.0.7] — 2026-07-31
|
||||
|
||||
### Fixed
|
||||
- **Notification bug** — `SessionTimer.stop()` now cancels the persistent
|
||||
Android notification on user-initiated disconnect.
|
||||
- **Concurrent sync guard** — `_syncInProgress` flag prevents duplicate
|
||||
HTTP requests from overlapping in `_syncWithHivemind()`.
|
||||
- **Debug bypass gate** — `AppConfig.enableAdBypass` replaces `kDebugMode`
|
||||
for fake AdMob callback. Tree-shaken in release builds.
|
||||
|
||||
### Changed
|
||||
- **Responsive layout** — main screen uses `LayoutBuilder` with proportional
|
||||
fractions. Scales to any screen size.
|
||||
- **Dynamic version** — sidebar footer reads from `PackageInfo` instead of
|
||||
hardcoded string.
|
||||
- **Swarm/log blocked** — nginx returns 404 for `/api/swarm` and `/api/log`.
|
||||
Monitoring runs locally via `swarm_watch.py`.
|
||||
|
||||
### Added
|
||||
- **Update checker** in sidebar — polls GitHub Releases API.
|
||||
- **Website button** in sidebar → opens `https://userevolt.app`.
|
||||
- **Timer syncing indicator** — spinner during handshake.
|
||||
- Dependency: `package_info_plus`.
|
||||
|
||||
### Server
|
||||
- `/session/stop` fetches stats BEFORE popping session (race fix).
|
||||
- `XrayManager._stats_lock` for diagnostic counter thread safety.
|
||||
- `ManagementLoop._start_lock` prevents TOCTOU on daemon startup.
|
||||
|
||||
---
|
||||
|
||||
## [1.0.6] — 2026-06
|
||||
|
||||
- Initial VLESS + Xray Reality tunnel
|
||||
- 60 min session, 4 GB throttle, support top-up
|
||||
- Server health dot, speed display, countdown timer
|
||||
- Persistent Android notification
|
||||
- Glass-morphism dark UI with yellow accent
|
||||
- Right-edge sidebar with Ad Consent, Privacy, About, Discord
|
||||
@@ -0,0 +1,83 @@
|
||||
# Contributing to ReVoltVPN
|
||||
|
||||
We would love for you to contribute to ReVoltVPN and help make it even better than it is today!
|
||||
As a contributor, here are the guidelines we would like you to follow:
|
||||
|
||||
## <a name="commit"></a> Commit Message Format
|
||||
|
||||
*This specification is inspired by the Angular commit message format.*
|
||||
|
||||
#### <a name="commit-header"></a>Commit Message Header
|
||||
|
||||
```
|
||||
<type>(<scope>): <short summary>
|
||||
│ │ │
|
||||
│ │ └─⫸ Summary in present tense. Not capitalized. No period at the end.
|
||||
│ │
|
||||
│ └─⫸ Commit Scope: app|server|xray|nginx|docs|config
|
||||
│
|
||||
└─⫸ Commit Type: build|ci|docs|feat|fix|perf|refactor|test
|
||||
```
|
||||
|
||||
The `<type>` and `<summary>` fields are mandatory, the `(<scope>)` field is optional.
|
||||
|
||||
##### Type
|
||||
|
||||
Must be one of the following:
|
||||
|
||||
* **build**: Changes that affect the build system or external dependencies (example: Flutter, pub, Gradle)
|
||||
* **ci**: Changes to CI configuration files and scripts
|
||||
* **docs**: Documentation only changes (README, AGENTS.md, comments)
|
||||
* **feat**: A new feature
|
||||
* **fix**: A bug fix
|
||||
* **perf**: A code change that improves performance
|
||||
* **refactor**: A code change that neither fixes a bug nor adds a feature
|
||||
* **test**: Adding missing tests or correcting existing tests
|
||||
* **style**: Changes that do not affect the meaning of the code (formatting, whitespace)
|
||||
|
||||
##### Scope
|
||||
|
||||
The scope should be the part of the project affected:
|
||||
|
||||
* `app` — Flutter client (screens, components, logic)
|
||||
* `server` — Python Hivemind backend
|
||||
* `xray` — Xray Reality config or tunnel behavior
|
||||
* `nginx` — nginx routing, SSL, auth
|
||||
* `docs` — documentation files
|
||||
* `config` — app_config, .gitignore, pubspec
|
||||
|
||||
##### Summary
|
||||
|
||||
Use the summary field to provide a succinct description of the change:
|
||||
|
||||
* use the imperative, present tense: "change" not "changed" nor "changes"
|
||||
* don't capitalize the first letter
|
||||
* no dot (.) at the end
|
||||
|
||||
|
||||
#### <a name="commit-body"></a>Commit Message Body
|
||||
|
||||
Just as in the summary, use the imperative, present tense: "fix" not "fixed" nor "fixes".
|
||||
|
||||
Explain the motivation for the change in the commit message body. This commit message should explain _why_ you are making the change.
|
||||
You can include a comparison of the previous behavior with the new behavior in order to illustrate the impact of the change.
|
||||
|
||||
#### Examples
|
||||
|
||||
```
|
||||
feat(server): add swarm monitoring endpoint
|
||||
|
||||
GET /api/swarm returns sorted drone list for the TUI dashboard.
|
||||
Persistent total GB saved to swarm_total.json, survives restarts.
|
||||
```
|
||||
|
||||
```
|
||||
fix(app): remove dead _isThrottled field from session timer
|
||||
|
||||
Field was written but never read — throttle handled by port-swap now.
|
||||
Also removed unreachable 404 branch in _syncWithHivemind.
|
||||
```
|
||||
|
||||
```
|
||||
docs: update README with correct quota and Reality protocol details
|
||||
```
|
||||
@@ -1,21 +1,690 @@
|
||||
MIT License
|
||||
ReVoltVPN — Copyright (C) 2026 esef
|
||||
|
||||
Copyright (c) 2026 esef
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -1,21 +1,49 @@
|
||||
Privacy Policy
|
||||
Last updated: July 2025
|
||||
# Privacy Policy
|
||||
|
||||
**Last updated:** September 2026
|
||||
|
||||
ReVoltVPN is a free VPN service built and operated by ReVolt Team.
|
||||
What we collect
|
||||
|
||||
## In-app disclosure
|
||||
|
||||
When you first open the app, we show a brief summary of this policy before you connect. You can review this full policy at any time from the sidebar menu.
|
||||
|
||||
## What we collect
|
||||
|
||||
We collect the minimum required to operate the service:
|
||||
|
||||
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. All session data is stored in memory and deleted permanently when your session ends.
|
||||
- A randomly generated device ID created on your phone. This is not linked to your identity in any way.
|
||||
- Your connection duration and data usage for the current session, linked to your device ID. This is used solely to enforce the per-session quota (see below).
|
||||
|
||||
What we do not collect
|
||||
## What our server sees
|
||||
|
||||
We do not collect your name, email, or any personal information.
|
||||
We do not log your internet traffic or browsing history.
|
||||
We do not sell or share any data with third parties.
|
||||
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.
|
||||
|
||||
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.
|
||||
Your traffic
|
||||
Your internet traffic is routed through our server located in Finland. We do not inspect, log, or store your traffic.
|
||||
Contact
|
||||
If you have any questions, open an issue on the GitHub repository.
|
||||
## 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
|
||||
|
||||
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
|
||||
|
||||
- We do not collect your name, email, or any personal information.
|
||||
- We do not log your internet traffic, browsing history, DNS queries, or destination IPs.
|
||||
- We do not inspect or store the content of your traffic.
|
||||
- We do not sell or share any data with third parties.
|
||||
|
||||
## Ads & Consent
|
||||
|
||||
ReVoltVPN uses Google AdMob to display rewarded video ads. Where required — for users in the European Economic Area (EEA) and United Kingdom — a consent dialog provided by Google's User Messaging Platform is shown before the first ad is requested, letting you choose whether to allow personalized ads. This choice is stored on your device and can be reviewed at any time from the "Ad Consent" entry in the sidebar menu. Google may collect data as part of ad delivery. Please refer to Google's Privacy Policy for details.
|
||||
|
||||
## Your traffic
|
||||
|
||||
Your internet traffic is routed through our server located in Finland. We do not inspect, log, or store your traffic. We only track total bytes transferred per session for quota enforcement — no packet contents, no destination IPs, no DNS queries.
|
||||
|
||||
## Contact
|
||||
|
||||
If you have any questions, open an issue on the GitHub repository or join the Discord server.
|
||||
@@ -1,56 +1,60 @@
|
||||
---
|
||||
|
||||
<p align="center">
|
||||
<img src="screenshots/feature_graphic.png" alt="ReVoltVPN banner" width="100%"/>
|
||||
</p>
|
||||
|
||||
# ReVoltVPN
|
||||
A free VPN app built from scratch. I handle the Flutter app, Hivemind backend, and AdMob integration — the ReVolt team manages server security and VLESS/Xray infrastructure.
|
||||
|
||||
There are hundreds of free VPN apps on the Play Store. Most of them are fine honestly — some are genuinely good. But a lot of them are vague about how they work, who runs them, and what happens to your traffic. I wanted to build something where the answer to all of those questions is just... public.
|
||||
|
||||
So here it is.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## How it works
|
||||
You watch a short ad. You get 60 minutes and 4 GB of full-speed traffic. That's it. The ad pays for the server (actually not even enough). No accounts, no emails, no subscriptions.
|
||||
|
||||
When your data runs out you get throttled to 1.5 Mbps instead of getting cut off. A second Reality inbound on a different port handles throttled traffic — your client reconnects automatically, no ad required.
|
||||
1. Watch a short rewarded ad
|
||||
2. Server creates a temporary VLESS session (2 hours / 10 GB)
|
||||
3. Your traffic routes through a single server in Finland at full speed
|
||||
4. When time or data runs out, session ends — watch another ad to continue
|
||||
5. No throttling, no slow lane, no mid-session punishment
|
||||
|
||||
No email. No password. No payment. The ad pays for the server.
|
||||
|
||||
---
|
||||
|
||||
## The stack
|
||||
- **App** — Flutter (Android only for now)
|
||||
- **Server** — A single Debian box rented from Hetzner, located in Finland
|
||||
- **VPN protocol** — VLESS + Xray Reality (XTLS-Vision). Spoofs real TLS certificates (e.g. www.microsoft.com) so your tunnel looks like regular HTTPS. Great for bypassing DPI in countries that are aggressive with it.
|
||||
- **Backend** — Hivemind, a Python Flask server I wrote that manages sessions, data quotas, throttling, and live swarm monitoring. Entire server is open source — in this repo.
|
||||
- **Ads** — Google AdMob rewarded ads, verified server-side so fake callbacks don't work
|
||||
## Protocol
|
||||
|
||||
- **Transport** — VLESS over XHTTP (HTTP/2 multiplexed, path-hidden behind `/revolt`)
|
||||
- **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
|
||||
- **API** — Standard HTTPS to a separate domain. Tunnel destination is IP-pinned — domain compromise is DoS only
|
||||
|
||||
---
|
||||
|
||||
## Limitations (being honest)
|
||||
- One server, one location (Finland). That's all I can afford right now (planning to escalate further)
|
||||
- 2 cores and 4GB RAM. It will not handle thousands of concurrent users
|
||||
- iOS is not supported and probably won't be for a while
|
||||
- The app is built by me in my free time — expect rough edges
|
||||
## Stack
|
||||
|
||||
| Layer | Technology |
|
||||
|-------|-----------|
|
||||
| App | Flutter (Android) |
|
||||
| VPN | VLESS + Xray Reality + XHTTP |
|
||||
| Backend | Python Flask ("Hivemind") — session management, quotas, stats |
|
||||
| Ads | Google AdMob rewarded, verified server-side |
|
||||
| Server | Debian, single Hetzner box in Finland |
|
||||
|
||||
---
|
||||
|
||||
## Why I built this
|
||||
Free time project. I wanted to learn how VPNs actually work under the hood. Ended up building the whole thing from scratch — the Flutter app, Hivemind backend, and AdMob integration are made by me, while server security and VLESS/Xray setup are handled by the ReVolt team. It took way longer than expected.
|
||||
## Limitations
|
||||
|
||||
- One server, one location (Finland)
|
||||
- 2 vCPU / 4 GB RAM — not built for thousands of concurrent users
|
||||
- Android only
|
||||
|
||||
---
|
||||
|
||||
## Privacy
|
||||
Your traffic goes through my server in Finland. I don't log it, I don't sell it, I have no reason to. The session manager (Hivemind) only tracks whether your session is active and how much data you've used — nothing else.
|
||||
|
||||
Internet privacy at the cost of watching an ad. Honest business.
|
||||
Your traffic routes through Finland. We don't log it, inspect it, or sell it. Hivemind tracks only session liveness and byte counters for quota enforcement — no packet contents, no destination IPs, no DNS queries.
|
||||
|
||||
You can read the server code yourself, it's in this repo.
|
||||
Full privacy policy: [`PRIVACY_POLICY.md`](PRIVACY_POLICY.md)
|
||||
|
||||
---
|
||||
|
||||
*ReVoltVPN is not affiliated with any VPN company.*
|
||||
|
||||
---
|
||||
@@ -0,0 +1,10 @@
|
||||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
analyzer:
|
||||
exclude:
|
||||
- local_packages/**
|
||||
- whatsthis/**
|
||||
|
||||
linter:
|
||||
rules:
|
||||
avoid_print: true
|
||||
@@ -1,4 +1,5 @@
|
||||
import java.util.Properties
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
|
||||
plugins {
|
||||
@@ -6,8 +7,130 @@ plugins {
|
||||
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 {
|
||||
namespace = "com.revoltvpn.app"
|
||||
namespace = "com.paladinvpn.app"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
ndkVersion = flutter.ndkVersion
|
||||
|
||||
@@ -34,7 +157,7 @@ android {
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.revoltvpn.app"
|
||||
applicationId = "com.paladinvpn.app"
|
||||
minSdk = flutter.minSdkVersion
|
||||
targetSdk = flutter.targetSdkVersion
|
||||
versionCode = flutter.versionCode
|
||||
|
||||
@@ -1,26 +1,39 @@
|
||||
<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.ACCESS_NETWORK_STATE"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<!-- VpnService provides its own system notification; SPECIAL_USE is not needed -->
|
||||
<!-- Required by url_launcher on Android 11+ to open external browser -->
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW"/>
|
||||
<data android:scheme="https"/>
|
||||
</intent>
|
||||
</queries>
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"/>
|
||||
<uses-permission android:name="android.permission.VIBRATE"/>
|
||||
<!-- Doze/App Standby stop background services of non-exempt apps. A VPN
|
||||
cannot stay up without this; Play allows it for VPN functionality. -->
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
|
||||
<!-- OS-level session-expiry alarm. Auto-granted on 31-32; on 33+ the daemon
|
||||
falls back to setAndAllowWhileIdle if exact alarms aren't granted. -->
|
||||
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
|
||||
|
||||
<application
|
||||
android:label="REVOLT VPN"
|
||||
<!-- 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:name="${applicationName}"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:usesCleartextTraffic="false"
|
||||
android:allowBackup="false">
|
||||
android:allowBackup="false"
|
||||
android:extractNativeLibs="true">
|
||||
|
||||
<!-- AdMob App ID — injected at build time from android/admob.properties -->
|
||||
<meta-data
|
||||
android:name="com.google.android.gms.ads.APPLICATION_ID"
|
||||
android:value="${ADMOB_APP_ID}"/>
|
||||
@@ -34,17 +47,16 @@
|
||||
android:hardwareAccelerated="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<meta-data
|
||||
android:name="io.flutter.embedding.android.NormalTheme"
|
||||
android:resource="@style/NormalTheme"
|
||||
/>
|
||||
android:name="io.flutter.embedding.android.NormalTheme"
|
||||
android:resource="@style/NormalTheme"/>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<meta-data
|
||||
android:name="flutterEmbedding"
|
||||
android:value="2" />
|
||||
android:value="2"/>
|
||||
</application>
|
||||
</manifest>
|
||||
|
||||
@@ -0,0 +1,479 @@
|
||||
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.engine.FlutterEngine
|
||||
import io.flutter.plugin.common.EventChannel
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
|
||||
class MainActivity : FlutterActivity() {
|
||||
private val installerChannel = "com.revoltvpn.app/installer"
|
||||
private val notificationChannel = "com.revoltvpn.app/notification"
|
||||
private val hapticsChannel = "com.revoltvpn.app/haptics"
|
||||
private val networkChannel = "com.revoltvpn.app/network"
|
||||
private val powerChannel = "com.revoltvpn.app/power"
|
||||
|
||||
private var notificationChannelReady = false
|
||||
private var networkCallback: ConnectivityManager.NetworkCallback? = null
|
||||
private var networkEvents: EventChannel.EventSink? = null
|
||||
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, installerChannel)
|
||||
.setMethodCallHandler { call, result ->
|
||||
if (call.method == "getInstallerPackage") {
|
||||
result.success(installerPackage())
|
||||
} else {
|
||||
result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, powerChannel)
|
||||
.setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
// 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 +0,0 @@
|
||||
package com.revoltvpn.app
|
||||
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
|
||||
class MainActivity : FlutterActivity()
|
||||
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 64 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 114 KiB |
|
Before Width: | Height: | Size: 172 KiB After Width: | Height: | Size: 174 KiB |
@@ -1,5 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle">
|
||||
<solid android:color="#0d1017" />
|
||||
<solid android:color="@color/splash_bg" />
|
||||
</shape>
|
||||
|
After Width: | Height: | Size: 144 KiB |
@@ -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"?>
|
||||
<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">
|
||||
<!-- 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:windowDrawsSystemBarBackgrounds">true</item>
|
||||
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||
</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">
|
||||
<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>
|
||||
</resources>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowSplashScreenBackground">@color/splash_bg</item>
|
||||
<item name="android:windowBackground">@color/splash_bg</item>
|
||||
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
|
||||
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||
</style>
|
||||
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
|
||||
<item name="android:windowBackground">@color/splash_bg</item>
|
||||
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
|
||||
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -1,4 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="splash_bg">#0d1017</color>
|
||||
<color name="splash_bg">#0D1117</color>
|
||||
</resources>
|
||||
@@ -1,18 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<!-- Theme applied to the Android Window while the process is starting -->
|
||||
<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:windowDrawsSystemBarBackgrounds">true</item>
|
||||
<item name="android:statusBarColor">@color/splash_bg</item>
|
||||
<item name="android:navigationBarColor">@color/splash_bg</item>
|
||||
</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">
|
||||
<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,8 +1,7 @@
|
||||
org.gradle.jvmargs=-Xmx1536M
|
||||
android.enableR8=true
|
||||
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8
|
||||
org.gradle.workers.max=2
|
||||
android.useAndroidX=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
|
||||
# This newDsl flag was added automatically by Flutter migrator
|
||||
android.newDsl=false
|
||||
@@ -3,3 +3,6 @@ distributionPath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip
|
||||
distributionSha256Sum=efe9a3d147d948d7528a9887fa35abcf24ca1a43ad06439996490f77569b02d1
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
@@ -1,115 +0,0 @@
|
||||
// =============================================================================
|
||||
// clock_display.dart — EDUCATIONAL REFERENCE (not used in production)
|
||||
// =============================================================================
|
||||
//
|
||||
// This widget was the original combined timer + speed + syncing display.
|
||||
// It was replaced by the separate TimerBox and SpeedBox widgets in the
|
||||
// Reality-era UI refactor.
|
||||
//
|
||||
// What's worth studying here:
|
||||
//
|
||||
// 1. TEXT GLOW EFFECT — the yellow glow around the countdown timer:
|
||||
// ```
|
||||
// shadows: [Shadow(color: AppColors.accent50, blurRadius: 16)]
|
||||
// ```
|
||||
// This exact effect was ported to timer_box.dart and is what gives
|
||||
// the countdown its signature pulsing-yellow look.
|
||||
//
|
||||
// 2. SYNCING PLACEHOLDER — conditional spinner + label when the first
|
||||
// server poll hasn't returned yet. Shows "Syncing…" with a small
|
||||
// CircularProgressIndicator instead of flashing 00:00:00.
|
||||
//
|
||||
// 3. COMBINED DISPLAY — clock + speed stacked in a Column inside a
|
||||
// fixed 200×200 SizedBox. The modern UI split these into separate
|
||||
// boxes for the stacked layout, but the stacking approach here is
|
||||
// a good reference for compact combined displays.
|
||||
//
|
||||
// Kept in the repo for reference. Safe to delete if you're pruning.
|
||||
// =============================================================================
|
||||
|
||||
// import 'package:flutter/material.dart';
|
||||
// import 'package:provider/provider.dart';
|
||||
// import 'package:revoltvpn/logic/app_colors.dart';
|
||||
// import 'package:revoltvpn/logic/session_timer.dart';
|
||||
|
||||
// class ClockDisplay extends StatelessWidget {
|
||||
// const ClockDisplay({super.key});
|
||||
|
||||
// @override
|
||||
// Widget build(BuildContext context) {
|
||||
// return Consumer<SessionTimer>(
|
||||
// builder: (context, timer, _) {
|
||||
// final bool showSyncing = !timer.hasSyncedOnce;
|
||||
|
||||
// return SizedBox(
|
||||
// width: 200,
|
||||
// height: 200,
|
||||
// child: Stack(
|
||||
// alignment: Alignment.center,
|
||||
// children: [
|
||||
// Column(
|
||||
// mainAxisSize: MainAxisSize.min,
|
||||
// children: [
|
||||
// if (showSyncing) ...[
|
||||
// const SizedBox(
|
||||
// width: 32,
|
||||
// height: 32,
|
||||
// child: CircularProgressIndicator(
|
||||
// strokeWidth: 2,
|
||||
// color: AppColors.accent50,
|
||||
// ),
|
||||
// ),
|
||||
// const SizedBox(height: 10),
|
||||
// const Text(
|
||||
// 'Syncing…',
|
||||
// style: TextStyle(
|
||||
// fontSize: 16,
|
||||
// fontWeight: FontWeight.w600,
|
||||
// color: AppColors.accent60,
|
||||
// letterSpacing: 1.5,
|
||||
// ),
|
||||
// ),
|
||||
// ] else ...[
|
||||
// Text(
|
||||
// timer.formatted,
|
||||
// style: const TextStyle(
|
||||
// fontSize: 40,
|
||||
// fontWeight: FontWeight.w800,
|
||||
// color: AppColors.textWhite,
|
||||
// letterSpacing: 2,
|
||||
// shadows: [
|
||||
// Shadow(
|
||||
// color: AppColors.accent50,
|
||||
// blurRadius: 16,
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// ),
|
||||
// const SizedBox(height: 6),
|
||||
// Row(
|
||||
// mainAxisSize: MainAxisSize.min,
|
||||
// children: [
|
||||
// const Icon(Icons.speed, color: AppColors.textDim, size: 14),
|
||||
// const SizedBox(width: 4),
|
||||
// Text(
|
||||
// timer.currentSpeedKBps > 0.5
|
||||
// ? '${timer.currentSpeedKBps.toStringAsFixed(1)} KB/s'
|
||||
// : 'Idle',
|
||||
// style: const TextStyle(
|
||||
// fontSize: 12,
|
||||
// color: AppColors.textDim,
|
||||
// fontWeight: FontWeight.w500,
|
||||
// ),
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// ],
|
||||
// ],
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// );
|
||||
// },
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
@@ -1,10 +1,10 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
import 'package:revoltvpn/logic/vpn_connection.dart';
|
||||
import 'package:revoltvpn/logic/session_timer.dart';
|
||||
import 'package:revoltvpn/logic/ad_manager.dart';
|
||||
import 'package:revoltvpn/logic/haptic_settings.dart';
|
||||
|
||||
class ConnectButton extends StatefulWidget {
|
||||
const ConnectButton({super.key});
|
||||
@@ -14,9 +14,9 @@ class ConnectButton extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _ConnectButtonState extends State<ConnectButton>
|
||||
with SingleTickerProviderStateMixin {
|
||||
with SingleTickerProviderStateMixin, WidgetsBindingObserver {
|
||||
bool _busy = false;
|
||||
DateTime _lastTap = DateTime.now();
|
||||
DateTime _lastTap = DateTime.fromMillisecondsSinceEpoch(0);
|
||||
AnimationController? _pulse;
|
||||
Animation<double>? _pulseAnim;
|
||||
|
||||
@@ -25,16 +25,23 @@ class _ConnectButtonState extends State<ConnectButton>
|
||||
@override
|
||||
void 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;
|
||||
_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((_) {
|
||||
context.read<VpnConnection>().addListener(_onVpnChanged);
|
||||
if (mounted) context.read<VpnConnection>().addListener(_onVpnChanged);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
context.read<VpnConnection>().removeListener(_onVpnChanged);
|
||||
_pulse?.dispose();
|
||||
super.dispose();
|
||||
@@ -50,41 +57,48 @@ 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();
|
||||
if (now.difference(_lastTap).inMilliseconds < 1000) return;
|
||||
_lastTap = now;
|
||||
|
||||
HapticFeedback.lightImpact();
|
||||
|
||||
final vpn = context.read<VpnConnection>();
|
||||
final timer = context.read<SessionTimer>();
|
||||
final ad = context.read<AdManager>();
|
||||
|
||||
|
||||
if (vpn.status == VpnStatus.connected || vpn.status == VpnStatus.connecting) {
|
||||
_busy = false;
|
||||
timer.stop(); // MUST stop timer BEFORE disconnect — prevents auto-reconnect
|
||||
await vpn.disconnect();
|
||||
await timer.disconnect();
|
||||
HapticSettings.success();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (vpn.status == VpnStatus.disconnecting) return;
|
||||
|
||||
|
||||
if (_busy) return;
|
||||
if (vpn.status == VpnStatus.disconnecting || _busy) return;
|
||||
|
||||
setState(() => _busy = true);
|
||||
try {
|
||||
final adWatched = await ad.showAd('main');
|
||||
if (!adWatched && AdManager.adsEnabled) {
|
||||
setState(() => _busy = false);
|
||||
return;
|
||||
}
|
||||
if (!adWatched && AdManager.adsEnabled) return;
|
||||
|
||||
final ok = await vpn.connect();
|
||||
if (ok) timer.start();
|
||||
if (ok) {
|
||||
await timer.start();
|
||||
HapticSettings.success();
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
@@ -103,20 +117,41 @@ class _ConnectButtonState extends State<ConnectButton>
|
||||
child: _pulseAnim != null
|
||||
? AnimatedBuilder(
|
||||
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 glowRadius = isConnected ? 18.0 + (pulse * 14) : 0.0;
|
||||
|
||||
return Container(
|
||||
width: 260, // <-- CHANGE ME: circle size
|
||||
width: 260,
|
||||
height: 260,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
@@ -126,21 +161,17 @@ class _ConnectButtonState extends State<ConnectButton>
|
||||
width: isConnected ? 2.5 : 1.5,
|
||||
),
|
||||
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,
|
||||
child: spinning
|
||||
? const Center(
|
||||
child: SizedBox(
|
||||
width: 36, height: 36,
|
||||
child: CircularProgressIndicator(strokeWidth: 2.5, color: AppColors.accent70),
|
||||
),
|
||||
)
|
||||
: Padding(
|
||||
padding: const EdgeInsets.all(14), // <-- CHANGE ME: brand.png padding from edge
|
||||
child: Image.asset('assets/brand.png', fit: BoxFit.contain),
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// lib/components/data_disclosure_dialog.dart
|
||||
// First-launch data disclosure dialog — Google Play Data safety section requirement.
|
||||
// Shows once per install; preference persisted in SharedPreferences.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
|
||||
class DataDisclosureDialog {
|
||||
DataDisclosureDialog._();
|
||||
|
||||
static const _key = 'data_disclosure_accepted';
|
||||
|
||||
/// Shows the disclosure dialog if the user hasn't accepted it yet.
|
||||
/// Call once after the main screen is mounted (post-frame callback).
|
||||
static Future<void> showIfFirstLaunch(BuildContext context) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (prefs.getBool(_key) == true) return; // Already accepted.
|
||||
|
||||
if (!context.mounted) return;
|
||||
|
||||
await showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false, // Must tap Continue — no tap-outside dismiss.
|
||||
builder: (_) => _DisclosureDialog(
|
||||
onContinue: () {
|
||||
prefs.setBool(_key, true);
|
||||
Navigator.of(context).pop(); // Dismiss the dialog.
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DisclosureDialog extends StatelessWidget {
|
||||
final VoidCallback onContinue;
|
||||
|
||||
const _DisclosureDialog({required this.onContinue});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Dialog(
|
||||
backgroundColor: AppColors.bgCard,
|
||||
insetPadding: const EdgeInsets.symmetric(horizontal: 28, vertical: 40),
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(24, 28, 24, 20),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Title
|
||||
const Text(
|
||||
'Before you connect',
|
||||
style: TextStyle(
|
||||
color: AppColors.textWhite,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Body
|
||||
const Text(
|
||||
'Revolt VPN creates a secure VPN tunnel to protect your '
|
||||
'traffic. To enforce your data/time quota, we log your '
|
||||
'connection duration and data usage, linked to a randomly '
|
||||
'generated device ID — not to your identity. We do not log '
|
||||
'or monitor the content of your traffic. We do not share '
|
||||
'your data with third parties. The full policy is in the '
|
||||
'sidebar menu under "Privacy Policy".',
|
||||
style: TextStyle(
|
||||
color: AppColors.textMuted,
|
||||
fontSize: 14,
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Continue button — full-width, accent
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: ElevatedButton(
|
||||
onPressed: onContinue,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.accent,
|
||||
foregroundColor: AppColors.bgDeep,
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
textStyle: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
child: const Text('Continue'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
import 'package:revoltvpn/screens/settings/in_settings/lightning.dart';
|
||||
|
||||
/// 2D lightning bolt — a jagged yellow line from top to bottom with glow.
|
||||
|
||||
class LightningEffect extends StatefulWidget {
|
||||
|
||||
final int minIntervalSec;
|
||||
|
||||
final int maxIntervalSec;
|
||||
|
||||
final double doubleChance;
|
||||
|
||||
const LightningEffect({
|
||||
super.key,
|
||||
this.minIntervalSec = 2,
|
||||
this.maxIntervalSec = 10,
|
||||
this.doubleChance = 0.2,
|
||||
});
|
||||
|
||||
@override
|
||||
State<LightningEffect> createState() => _LightningEffectState();
|
||||
}
|
||||
|
||||
class _LightningEffectState extends State<LightningEffect>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _ctrl;
|
||||
Timer? _timer;
|
||||
final _random = Random();
|
||||
|
||||
LightningBolt? _bolt;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_ctrl = AnimationController(vsync: this, duration: const Duration(milliseconds: 400));
|
||||
lightningEnabled.addListener(_onEnabledChanged);
|
||||
if (lightningEnabled.value) _scheduleNext();
|
||||
}
|
||||
|
||||
void _onEnabledChanged() {
|
||||
if (lightningEnabled.value) {
|
||||
_scheduleNext();
|
||||
} else {
|
||||
_timer?.cancel();
|
||||
_ctrl.stop();
|
||||
_bolt = null;
|
||||
}
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
lightningEnabled.removeListener(_onEnabledChanged);
|
||||
_timer?.cancel();
|
||||
_ctrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _scheduleNext() {
|
||||
final secs = widget.minIntervalSec +
|
||||
_random.nextInt(widget.maxIntervalSec - widget.minIntervalSec + 1);
|
||||
_timer = Timer(Duration(seconds: secs), _strike);
|
||||
}
|
||||
|
||||
void _strike() {
|
||||
if (!mounted || !lightningEnabled.value) return;
|
||||
_bolt = LightningBolt.random(_random);
|
||||
_ctrl.forward(from: 0.0);
|
||||
|
||||
if (_random.nextDouble() < widget.doubleChance) {
|
||||
Future.delayed(const Duration(milliseconds: 120), () {
|
||||
if (mounted && lightningEnabled.value) {
|
||||
_bolt = LightningBolt.random(_random);
|
||||
_ctrl.forward(from: 0.0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
_scheduleNext();
|
||||
}
|
||||
|
||||
/// Sharp flash curve: quick on, quick off. No slow fade.
|
||||
double _opacity(double t) {
|
||||
if (t < 0.08) return t / 0.08; // fast ramp
|
||||
return 1.0 - ((t - 0.08) / 0.92); // linear decay
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!lightningEnabled.value) return const SizedBox.shrink();
|
||||
return AnimatedBuilder(
|
||||
animation: _ctrl,
|
||||
builder: (_, child) {
|
||||
final raw = _opacity(_ctrl.value);
|
||||
if (raw <= 0.02 || _bolt == null) return const SizedBox.shrink();
|
||||
|
||||
return IgnorePointer(
|
||||
child: LayoutBuilder(
|
||||
builder: (ctx, constraints) {
|
||||
final sz = Size(constraints.maxWidth, constraints.maxHeight);
|
||||
return CustomPaint(
|
||||
size: sz,
|
||||
painter: _LightningPainter(
|
||||
bolt: _bolt!,
|
||||
opacity: raw,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// A single bolt defined by a list of 2D points (0.0–1.0 in width×height space).
|
||||
class LightningBolt {
|
||||
final List<Offset> mainPath;
|
||||
final List<List<Offset>> branches; // 0–2 forks off the main path
|
||||
|
||||
const LightningBolt({required this.mainPath, this.branches = const []});
|
||||
|
||||
/// Generate a random bolt. The path always starts near the top-center
|
||||
/// and ends near the bottom, zigzagging left/right along the way.
|
||||
factory LightningBolt.random(Random rng) {
|
||||
final points = <Offset>[];
|
||||
|
||||
// Start: top, slight horizontal offset
|
||||
double x = 0.5 + (rng.nextDouble() - 0.5) * 0.15;
|
||||
points.add(Offset(x, 0.0));
|
||||
|
||||
// Zigzag down — 6–10 segments
|
||||
final segments = 6 + rng.nextInt(5);
|
||||
for (int i = 1; i < segments; i++) {
|
||||
final y = i / segments;
|
||||
// Random horizontal offset — each segment adds jitter
|
||||
x += (rng.nextDouble() - 0.5) * 0.25;
|
||||
x = x.clamp(0.05, 0.95); // stay on screen
|
||||
points.add(Offset(x, y));
|
||||
}
|
||||
|
||||
// End: bottom
|
||||
points.add(Offset(x.clamp(0.1, 0.9), 1.0));
|
||||
|
||||
// Branches — 0–2 forks from random points along the main path
|
||||
final branches = <List<Offset>>[];
|
||||
final branchCount = rng.nextInt(3);
|
||||
for (int b = 0; b < branchCount; b++) {
|
||||
final branch = <Offset>[];
|
||||
final startIdx = 1 + rng.nextInt(points.length - 2);
|
||||
final start = points[startIdx];
|
||||
branch.add(start);
|
||||
|
||||
double bx = start.dx;
|
||||
double by = start.dy;
|
||||
final branchLen = 2 + rng.nextInt(3);
|
||||
for (int j = 0; j < branchLen; j++) {
|
||||
by += (0.05 + rng.nextDouble() * 0.12);
|
||||
bx += (rng.nextDouble() - 0.5) * 0.3;
|
||||
bx = bx.clamp(0.02, 0.98);
|
||||
by = by.clamp(0.0, 1.0);
|
||||
branch.add(Offset(bx, by));
|
||||
}
|
||||
branches.add(branch);
|
||||
}
|
||||
|
||||
return LightningBolt(mainPath: points, branches: branches);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class _LightningPainter extends CustomPainter {
|
||||
final LightningBolt bolt;
|
||||
final double opacity;
|
||||
|
||||
_LightningPainter({required this.bolt, required this.opacity});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final toScreen = (Offset p) => Offset(p.dx * size.width, p.dy * size.height);
|
||||
final scaledMain = bolt.mainPath.map(toScreen).toList();
|
||||
final scaledBranches = bolt.branches
|
||||
.map((b) => b.map(toScreen).toList())
|
||||
.toList();
|
||||
|
||||
final baseColor = AppColors.accent.withAlpha((opacity * 255).round());
|
||||
final glowColor = AppColors.accent.withAlpha((opacity * 0.35 * 255).round());
|
||||
|
||||
// Glow
|
||||
final glowPaint = Paint()
|
||||
..color = glowColor
|
||||
..strokeWidth = 18
|
||||
..strokeCap = StrokeCap.round
|
||||
..strokeJoin = StrokeJoin.round
|
||||
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 8)
|
||||
..style = PaintingStyle.stroke;
|
||||
|
||||
_drawPath(canvas, scaledMain, scaledBranches, glowPaint);
|
||||
|
||||
// Core
|
||||
final corePaint = Paint()
|
||||
..color = baseColor
|
||||
..strokeWidth = 5
|
||||
..strokeCap = StrokeCap.round
|
||||
..strokeJoin = StrokeJoin.round
|
||||
..style = PaintingStyle.stroke;
|
||||
|
||||
_drawPath(canvas, scaledMain, scaledBranches, corePaint);
|
||||
|
||||
// Hot center
|
||||
if (opacity > 0.6) {
|
||||
final hotPaint = Paint()
|
||||
..color = Colors.white.withAlpha((opacity * 180).round())
|
||||
..strokeWidth = 2
|
||||
..strokeCap = StrokeCap.round
|
||||
..strokeJoin = StrokeJoin.round
|
||||
..style = PaintingStyle.stroke;
|
||||
|
||||
_drawPath(canvas, scaledMain, scaledBranches, hotPaint);
|
||||
}
|
||||
}
|
||||
|
||||
void _drawPath(Canvas canvas, List<Offset> main,
|
||||
List<List<Offset>> branches, Paint paint) {
|
||||
final mainPath = Path()..moveTo(main.first.dx, main.first.dy);
|
||||
for (int i = 1; i < main.length; i++) {
|
||||
mainPath.lineTo(main[i].dx, main[i].dy);
|
||||
}
|
||||
canvas.drawPath(mainPath, paint);
|
||||
|
||||
for (final branch in branches) {
|
||||
final bPath = Path()..moveTo(branch.first.dx, branch.first.dy);
|
||||
for (int i = 1; i < branch.length; i++) {
|
||||
bPath.lineTo(branch[i].dx, branch[i].dy);
|
||||
}
|
||||
canvas.drawPath(bPath, paint);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _LightningPainter old) =>
|
||||
bolt != old.bolt || opacity != old.opacity;
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
|
||||
class VpnNotificationManager {
|
||||
static final FlutterLocalNotificationsPlugin _plugin =
|
||||
FlutterLocalNotificationsPlugin();
|
||||
static bool _initialized = false;
|
||||
|
||||
static Future<void> init() async {
|
||||
if (_initialized) return;
|
||||
|
||||
const androidSettings =
|
||||
AndroidInitializationSettings('@drawable/notification_icon');
|
||||
const initSettings = InitializationSettings(android: androidSettings);
|
||||
|
||||
await _plugin.initialize(initSettings);
|
||||
|
||||
// Request POST_NOTIFICATIONS permission on Android 13+
|
||||
if (Platform.isAndroid) {
|
||||
final androidPlugin = _plugin
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin>();
|
||||
await androidPlugin?.requestNotificationsPermission();
|
||||
}
|
||||
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
static String? _lastTimeLeft;
|
||||
static String? _lastSpeedKbps;
|
||||
|
||||
static Future<void> showOrUpdateStatus({
|
||||
required String timeLeft,
|
||||
required String speedKbps,
|
||||
}) async {
|
||||
// Skip update if nothing changed — prevents notification flicker
|
||||
// on Android skins that animate every notification update.
|
||||
if (timeLeft == _lastTimeLeft && speedKbps == _lastSpeedKbps) return;
|
||||
_lastTimeLeft = timeLeft;
|
||||
_lastSpeedKbps = speedKbps;
|
||||
|
||||
if (!_initialized) await init();
|
||||
|
||||
// NOTE: The channel ID includes 'v2' to force Android to create a fresh
|
||||
// notification channel. Android channels are immutable once created — if
|
||||
// the old channel was created without 'ongoing: true', users would be
|
||||
// stuck with a swipeable notification forever.
|
||||
const androidDetails = AndroidNotificationDetails(
|
||||
'revolt_vpn_status_v2',
|
||||
'VPN Status',
|
||||
channelDescription: 'Shown while VPN is active — non-dismissable',
|
||||
importance: Importance.low,
|
||||
priority: Priority.low,
|
||||
// Non-dismissable while VPN is running
|
||||
ongoing: true,
|
||||
autoCancel: false,
|
||||
// Silent updates — no sound or vibration each time stats refresh
|
||||
playSound: false,
|
||||
enableVibration: false,
|
||||
onlyAlertOnce: true,
|
||||
// Hide the auto-generated timestamp
|
||||
showWhen: false,
|
||||
// Show on lock screen
|
||||
visibility: NotificationVisibility.public,
|
||||
// Extra insurance against swipe-to-dismiss on aggressive Android skins
|
||||
usesChronometer: false,
|
||||
category: AndroidNotificationCategory.service,
|
||||
);
|
||||
|
||||
const notificationDetails = NotificationDetails(android: androidDetails);
|
||||
|
||||
try {
|
||||
await _plugin.show(
|
||||
888, // Fixed ID — always updates the same notification
|
||||
'REVOLT VPN Active',
|
||||
'Time: $timeLeft • $speedKbps',
|
||||
notificationDetails,
|
||||
);
|
||||
} catch (e) {
|
||||
// If showing fails (e.g. permission revoked), try to recover by
|
||||
// re-initializing and retrying once.
|
||||
_initialized = false;
|
||||
try {
|
||||
await init();
|
||||
await _plugin.show(
|
||||
888,
|
||||
'REVOLT VPN Active',
|
||||
'Time: $timeLeft • $speedKbps',
|
||||
notificationDetails,
|
||||
);
|
||||
} catch (_) {
|
||||
// Give up — the VPN still works, just without the notification.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> cancel() async {
|
||||
if (!_initialized) return;
|
||||
await _plugin.cancel(888);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import 'dart:math';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
import 'package:revoltvpn/screens/settings/in_settings/rain.dart';
|
||||
|
||||
/// Subtle animated rain effect — sits behind all UI as a full-screen overlay.
|
||||
///
|
||||
/// Usage (in a Stack, as the first child so it renders behind everything):
|
||||
|
||||
class RainEffect extends StatefulWidget {
|
||||
final int dropCount;
|
||||
|
||||
final Color color;
|
||||
|
||||
final double minLength;
|
||||
|
||||
final double maxLength;
|
||||
|
||||
final double windDrift;
|
||||
|
||||
const RainEffect({
|
||||
super.key,
|
||||
this.dropCount = 150,
|
||||
this.color = const Color(0xFFE8EAF6),
|
||||
this.minLength = 12,
|
||||
this.maxLength = 44,
|
||||
this.windDrift = 4.0,
|
||||
});
|
||||
|
||||
@override
|
||||
State<RainEffect> createState() => _RainEffectState();
|
||||
}
|
||||
|
||||
class _RainEffectState extends State<RainEffect>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final Ticker _ticker;
|
||||
final _drops = <_Drop>[];
|
||||
final _random = Random();
|
||||
final _repaint = ValueNotifier<int>(0);
|
||||
Duration _last = Duration.zero;
|
||||
|
||||
// Lifecycle
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
for (int i = 0; i < widget.dropCount; i++) {
|
||||
_drops.add(
|
||||
_Drop.spawn(_random, widget.minLength, widget.maxLength, widget.color));
|
||||
}
|
||||
_ticker = createTicker(_onTick);
|
||||
rainEnabled.addListener(_onEnabledChanged);
|
||||
if (rainEnabled.value) _ticker.start();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
rainEnabled.removeListener(_onEnabledChanged);
|
||||
_ticker.dispose();
|
||||
_repaint.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onEnabledChanged() {
|
||||
if (rainEnabled.value) {
|
||||
// Ticker elapsed restarts at zero; a stale _last makes the first dt negative.
|
||||
_last = Duration.zero;
|
||||
_ticker.start();
|
||||
} else {
|
||||
_ticker.stop();
|
||||
}
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
// Tick
|
||||
|
||||
void _onTick(Duration now) {
|
||||
double dt = 0.016; // ~60 fps fallback on first tick
|
||||
if (_last != Duration.zero) {
|
||||
dt = (now - _last).inMicroseconds / 1000000.0;
|
||||
dt = dt.clamp(0.0, 0.1);
|
||||
}
|
||||
_last = now;
|
||||
|
||||
for (final d in _drops) {
|
||||
d.y += d.speed * dt;
|
||||
if (d.y > 1.08) {
|
||||
d.spawn(_random, widget.minLength, widget.maxLength, widget.color);
|
||||
d.y = -0.06 - _random.nextDouble() * 0.08;
|
||||
}
|
||||
}
|
||||
_repaint.value++;
|
||||
}
|
||||
|
||||
// Build
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!rainEnabled.value) return const SizedBox.shrink();
|
||||
return CustomPaint(
|
||||
painter: _RainPainter(
|
||||
drops: _drops,
|
||||
windDrift: widget.windDrift,
|
||||
repaint: _repaint,
|
||||
),
|
||||
size: Size.infinite,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Drop model
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class _Drop {
|
||||
double x;
|
||||
double y;
|
||||
double speed;
|
||||
double length;
|
||||
Color color;
|
||||
|
||||
_Drop({
|
||||
required this.x,
|
||||
required this.y,
|
||||
required this.speed,
|
||||
required this.length,
|
||||
required this.color,
|
||||
});
|
||||
|
||||
/// Create a drop at a random position anywhere on screen.
|
||||
factory _Drop.spawn(Random r, double minLen, double maxLen, Color base) {
|
||||
return _Drop(
|
||||
x: r.nextDouble(),
|
||||
y: r.nextDouble(),
|
||||
speed: 0.30 + r.nextDouble() * 0.55,
|
||||
length: minLen + r.nextDouble() * (maxLen - minLen),
|
||||
color: base.withAlpha(((0.05 + r.nextDouble() * 0.12) * 255).round()),
|
||||
);
|
||||
}
|
||||
|
||||
/// Re-randomise all properties (call when recycling a drop to the top).
|
||||
void spawn(Random r, double minLen, double maxLen, Color base) {
|
||||
x = r.nextDouble();
|
||||
speed = 0.30 + r.nextDouble() * 0.55;
|
||||
length = minLen + r.nextDouble() * (maxLen - minLen);
|
||||
color = base.withAlpha(((0.05 + r.nextDouble() * 0.12) * 255).round());
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Painter
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class _RainPainter extends CustomPainter {
|
||||
final List<_Drop> drops;
|
||||
final double windDrift;
|
||||
|
||||
_RainPainter({
|
||||
required this.drops,
|
||||
required this.windDrift,
|
||||
required Listenable repaint,
|
||||
}) : super(repaint: repaint);
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final paint = Paint()
|
||||
..strokeCap = StrokeCap.round
|
||||
..strokeWidth = 1.5;
|
||||
|
||||
for (final d in drops) {
|
||||
final sx = d.x * size.width;
|
||||
final sy = d.y * size.height;
|
||||
final ex = sx - windDrift; // slight leftward slant
|
||||
final ey = sy + d.length;
|
||||
|
||||
paint.color = d.color;
|
||||
canvas.drawLine(Offset(sx, sy), Offset(ex, ey), paint);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_RainPainter old) => false; // repaint listenable drives frames
|
||||
}
|
||||
@@ -6,7 +6,7 @@ class DiscordLinkButton extends StatelessWidget {
|
||||
const DiscordLinkButton({super.key});
|
||||
|
||||
static Future<void> launchDiscord() async {
|
||||
final Uri url = Uri.parse('https://discord.gg/revoltvpn');
|
||||
final Uri url = Uri.parse('https://discord.gg/y7SXpjr2ff');
|
||||
if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
|
||||
debugPrint('Could not launch $url');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
import 'package:revoltvpn/screens/settings/settings_screen.dart';
|
||||
|
||||
// ── lib/components/sidebar_contents/settings.dart ────────────────────────────
|
||||
// Thin sidebar row — taps navigate to the full SettingsScreen.
|
||||
// The actual settings UI lives in lib/screens/settings/ (separate folder,
|
||||
// one file per feature).
|
||||
|
||||
class SettingsButton extends StatelessWidget {
|
||||
const SettingsButton({super.key});
|
||||
|
||||
// Opens the settings page sliding in from the right — matches the
|
||||
// sidebar end-drawer animation so it feels like one continuous motion.
|
||||
static PageRoute<void> _route() => PageRouteBuilder<void>(
|
||||
transitionDuration: const Duration(milliseconds: 300),
|
||||
reverseTransitionDuration: const Duration(milliseconds: 250),
|
||||
pageBuilder: (_, __, ___) => const SettingsScreen(),
|
||||
transitionsBuilder: (_, animation, __, child) {
|
||||
return SlideTransition(
|
||||
position: Tween<Offset>(
|
||||
begin: const Offset(1.0, 0.0),
|
||||
end: Offset.zero,
|
||||
).animate(
|
||||
CurvedAnimation(parent: animation, curve: Curves.easeOut),
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
static void openWithNavigator(NavigatorState navigator) {
|
||||
if (!navigator.mounted) return;
|
||||
navigator.push(_route());
|
||||
}
|
||||
|
||||
static void open(BuildContext context) {
|
||||
openWithNavigator(Navigator.of(context, rootNavigator: true));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return IconButton(
|
||||
icon: const Icon(Icons.settings, color: AppColors.textWhite, size: 28),
|
||||
onPressed: () => open(context),
|
||||
tooltip: 'Settings',
|
||||
splashRadius: 24,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
|
||||
class WebsiteButton extends StatelessWidget {
|
||||
const WebsiteButton({super.key});
|
||||
|
||||
static Future<void> launchWebsite() async {
|
||||
final Uri url = Uri.parse('https://userevolt.app');
|
||||
if (!await launchUrl(url, mode: LaunchMode.externalApplication)) {
|
||||
debugPrint('Could not launch $url');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return IconButton(
|
||||
icon: const Icon(Icons.language, color: AppColors.textWhite, size: 28),
|
||||
onPressed: launchWebsite,
|
||||
tooltip: 'Website',
|
||||
splashRadius: 24,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,43 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
import 'package:revoltvpn/components/sidebar_contents/gdpr_button.dart';
|
||||
import 'package:revoltvpn/components/sidebar_contents/privacy_policy_button.dart';
|
||||
import 'package:revoltvpn/components/sidebar_contents/info_button.dart';
|
||||
import 'package:revoltvpn/components/sidebar_contents/discord_link_button.dart';
|
||||
import 'package:revoltvpn/components/sidebar_contents/website_button.dart';
|
||||
import 'package:revoltvpn/components/sidebar_contents/settings.dart';
|
||||
import 'package:revoltvpn/logic/updater.dart';
|
||||
|
||||
class SidebarDrawer extends StatelessWidget {
|
||||
class SidebarDrawer extends StatefulWidget {
|
||||
const SidebarDrawer({super.key});
|
||||
|
||||
@override
|
||||
State<SidebarDrawer> createState() => _SidebarDrawerState();
|
||||
}
|
||||
|
||||
class _SidebarDrawerState extends State<SidebarDrawer> {
|
||||
String _version = '';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadVersion();
|
||||
}
|
||||
|
||||
Future<void> _loadVersion() async {
|
||||
try {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
debugPrint('[Sidebar] PackageInfo version: ${info.version} '
|
||||
'(build: ${info.buildNumber})');
|
||||
if (mounted) setState(() => _version = info.version);
|
||||
} catch (e) {
|
||||
debugPrint('[Sidebar] PackageInfo failed: $e');
|
||||
if (mounted) setState(() => _version = '?.?.?');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Drawer(
|
||||
@@ -84,12 +114,47 @@ class SidebarDrawer extends StatelessWidget {
|
||||
},
|
||||
),
|
||||
|
||||
_Row(
|
||||
icon: Icons.language,
|
||||
label: 'Website',
|
||||
onTap: () {
|
||||
Navigator.of(context).pop();
|
||||
WebsiteButton.launchWebsite();
|
||||
},
|
||||
),
|
||||
|
||||
_Row(
|
||||
icon: Icons.settings,
|
||||
label: 'Settings',
|
||||
onTap: () {
|
||||
final navigator = Navigator.of(context, rootNavigator: true);
|
||||
Navigator.of(context).pop();
|
||||
SettingsButton.openWithNavigator(navigator);
|
||||
},
|
||||
),
|
||||
|
||||
_Row(
|
||||
icon: Icons.system_update_alt,
|
||||
label: 'Check for updates',
|
||||
onTap: () {
|
||||
final navigator = Navigator.of(context, rootNavigator: true);
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
Navigator.of(context).pop();
|
||||
unawaited(
|
||||
Updater.checkWithHandles(
|
||||
navigator: navigator,
|
||||
messenger: messenger,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
const Spacer(),
|
||||
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(20),
|
||||
child: Text('ReVoltVPN · v1.0.6', textAlign: TextAlign.center,
|
||||
style: TextStyle(color: AppColors.slate, fontSize: 11, letterSpacing: 1),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Text('ReVoltVPN · v$_version', textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: AppColors.slate, fontSize: 11, letterSpacing: 1),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -8,10 +8,11 @@ class SpeedBox extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Consumer<SessionTimer>(
|
||||
builder: (context, timer, _) {
|
||||
final speed = timer.currentSpeedKBps > 0.5
|
||||
? '${timer.currentSpeedKBps.toStringAsFixed(1)} KB/s'
|
||||
return Selector<SessionTimer, double>(
|
||||
selector: (_, timer) => timer.currentSpeedKBps,
|
||||
builder: (context, speedKBps, _) {
|
||||
final speed = speedKBps > 0.5
|
||||
? '${speedKBps.toStringAsFixed(1)} KB/s'
|
||||
: 'Idle';
|
||||
|
||||
return Container(
|
||||
|
||||
@@ -3,7 +3,9 @@ import 'package:provider/provider.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
import 'package:revoltvpn/logic/vpn_connection.dart';
|
||||
import 'package:revoltvpn/logic/session_timer.dart';
|
||||
import 'package:revoltvpn/logic/server_list.dart';
|
||||
import 'package:revoltvpn/components/online_dot.dart';
|
||||
import 'package:revoltvpn/screens/server_selector/selection_screen.dart';
|
||||
|
||||
class StatusBar extends StatelessWidget {
|
||||
const StatusBar({super.key});
|
||||
@@ -14,50 +16,114 @@ class StatusBar extends StatelessWidget {
|
||||
builder: (context, vpn, timer, _) {
|
||||
final isConnected = vpn.status == VpnStatus.connected;
|
||||
final isConnecting = vpn.status == VpnStatus.connecting;
|
||||
final serverHealthy = vpn.serverReachable || (isConnected && timer.hasSyncedOnce);
|
||||
final serverHealthy =
|
||||
vpn.serverReachable || (isConnected && timer.hasSyncedOnce);
|
||||
final sessionOrTunnelHealthy = timer.hasSyncedOnce || vpn.serverReachable;
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 24),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.bgCard,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: AppColors.slate15),
|
||||
),
|
||||
child: Row(
|
||||
final statusLabel = isConnected
|
||||
? (sessionOrTunnelHealthy ? 'Online' : 'Syncing…')
|
||||
: (isConnecting
|
||||
? 'Connecting…'
|
||||
: (vpn.serverReachable ? 'Ready' : 'Offline'));
|
||||
|
||||
final server = context.watch<ServerList>().selected;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// ── Connection status (left) ─────────────────────────────
|
||||
if (isConnected) ...[
|
||||
Image.asset('assets/finland_flag_256.png', width: 20, height: 20),
|
||||
const SizedBox(width: 8),
|
||||
const Text('Helsinki, Finland', style: TextStyle(
|
||||
color: AppColors.accent, fontWeight: FontWeight.w600,
|
||||
fontSize: 13, letterSpacing: 0.5,
|
||||
)),
|
||||
] else ...[
|
||||
Icon(
|
||||
isConnecting ? Icons.sync : Icons.shield_outlined,
|
||||
size: 18,
|
||||
color: isConnecting ? AppColors.accent : AppColors.slate70,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
vpn.statusMessage.toUpperCase(),
|
||||
style: TextStyle(
|
||||
color: isConnecting ? AppColors.accent : AppColors.slate70,
|
||||
fontWeight: FontWeight.w600, fontSize: 13, letterSpacing: 1,
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
Navigator.of(context).push(
|
||||
PageRouteBuilder(
|
||||
transitionDuration: const Duration(milliseconds: 300),
|
||||
pageBuilder: (_, __, ___) => const SelectionScreen(),
|
||||
transitionsBuilder: (_, animation, __, child) {
|
||||
return SlideTransition(
|
||||
position: Tween<Offset>(
|
||||
begin: const Offset(1.0, 0.0),
|
||||
end: Offset.zero,
|
||||
).animate(
|
||||
CurvedAnimation(
|
||||
parent: animation,
|
||||
curve: Curves.easeOut,
|
||||
),
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Container(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.bgCard,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: AppColors.slate15),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Image.asset(server.flagAsset, width: 20, height: 20),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
server.name,
|
||||
style: const TextStyle(
|
||||
color: AppColors.accent,
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 13,
|
||||
letterSpacing: 0.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
const Icon(
|
||||
Icons.chevron_right,
|
||||
color: AppColors.textDim,
|
||||
size: 20,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
const Spacer(),
|
||||
|
||||
// ── Server health dot (right) ────────────────────────────
|
||||
OnlineDot(
|
||||
isOnline: serverHealthy,
|
||||
label: isConnected
|
||||
? (timer.hasSyncedOnce ? 'Online' : 'Syncing…')
|
||||
: (vpn.serverReachable ? 'Ready' : 'Offline'),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.bgCard,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: AppColors.slate15),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
OnlineDot(
|
||||
isOnline: serverHealthy,
|
||||
label: statusLabel,
|
||||
),
|
||||
const Spacer(),
|
||||
if (vpn.networkTransport != 'unknown' &&
|
||||
vpn.networkTransport != 'none')
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: Text(
|
||||
vpn.networkTransport,
|
||||
style: const TextStyle(
|
||||
color: AppColors.textDim,
|
||||
fontSize: 11,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (isConnected)
|
||||
const Icon(
|
||||
Icons.lock,
|
||||
color: AppColors.green50,
|
||||
size: 14,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -20,13 +20,22 @@ class _SupportButtonState extends State<SupportButton> {
|
||||
final ad = context.read<AdManager>();
|
||||
final timer = context.read<SessionTimer>();
|
||||
|
||||
// Only available when there's an active session.
|
||||
if (!timer.isRunning && !timer.hasSyncedOnce) return;
|
||||
// Only available when there's an active session, once the persisted
|
||||
// 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);
|
||||
|
||||
try {
|
||||
await ad.showAd('support');
|
||||
final rewarded = await ad.showAd('support');
|
||||
if (rewarded) {
|
||||
await timer.markSupportRewardClaimed();
|
||||
await timer.syncNow();
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
@@ -40,41 +49,56 @@ class _SupportButtonState extends State<SupportButton> {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final stateLoaded = timer.supportRewardStateLoaded;
|
||||
final claimed = timer.supportRewardClaimed;
|
||||
final disabled = !stateLoaded || claimed;
|
||||
|
||||
return GestureDetector(
|
||||
onTap: _handleTap,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.glassBg,
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
border: Border.all(
|
||||
color: AppColors.accent.withAlpha(100),
|
||||
width: 1,
|
||||
onTap: disabled ? null : _handleTap,
|
||||
child: Opacity(
|
||||
opacity: disabled ? 0.55 : 1.0,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.glassBg,
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
border: Border.all(
|
||||
color: AppColors.accent.withAlpha(100),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.favorite_border, color: AppColors.accent, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
_busy
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: AppColors.accent,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
claimed ? Icons.check_circle_outline : Icons.favorite_border,
|
||||
color: AppColors.accent,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
_busy
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
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,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -19,17 +19,21 @@ class TimerBox extends StatelessWidget {
|
||||
),
|
||||
child: Text(
|
||||
timer.hasSyncedOnce ? timer.formatted : '00:00:00',
|
||||
style: const TextStyle(
|
||||
style: TextStyle(
|
||||
fontSize: 32,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: AppColors.textWhite,
|
||||
color: timer.hasSyncedOnce
|
||||
? AppColors.textWhite
|
||||
: AppColors.slate70,
|
||||
letterSpacing: 2,
|
||||
shadows: [
|
||||
Shadow(
|
||||
color: AppColors.accent50,
|
||||
blurRadius: 16,
|
||||
),
|
||||
],
|
||||
shadows: timer.hasSyncedOnce
|
||||
? const [
|
||||
Shadow(
|
||||
color: AppColors.accent50,
|
||||
blurRadius: 16,
|
||||
),
|
||||
]
|
||||
: [],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -6,13 +6,9 @@ import 'package:google_mobile_ads/google_mobile_ads.dart';
|
||||
import 'package:revoltvpn/logic/crypto_service.dart';
|
||||
import 'package:revoltvpn/logic/hivemind_service.dart';
|
||||
import 'package:revoltvpn/logic/app_config.dart';
|
||||
import 'package:revoltvpn/logic/consent_manager.dart';
|
||||
|
||||
/// AdManager manages the lifecycle of rewarded video ads.
|
||||
///
|
||||
/// When [adsEnabled] is false (pre-launch mode) all ad operations are
|
||||
/// silently skipped — the app connects without any ad requirement.
|
||||
class AdManager extends ChangeNotifier {
|
||||
/// Flip to `true` after Google Play launch when real ads are wired up.
|
||||
static const bool adsEnabled = false;
|
||||
|
||||
RewardedAd? _rewardedAd;
|
||||
@@ -32,15 +28,30 @@ class AdManager extends ChangeNotifier {
|
||||
if (adsEnabled) preloadAd();
|
||||
}
|
||||
|
||||
/// Loads a rewarded ad in the background and returns a Future when ready.
|
||||
/// Safe to call multiple times — re-entrant calls wait on the same load.
|
||||
/// No-op when [adsEnabled] is false.
|
||||
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 {
|
||||
if (!adsEnabled) return true;
|
||||
// If already loaded, return instantly
|
||||
await ensureSdkInitialized();
|
||||
if (_isAdLoaded) return true;
|
||||
|
||||
// If we're already loading one right now, wait for that same request to finish
|
||||
if (_isAdLoading) return _loadCompleter?.future ?? Future.value(false);
|
||||
|
||||
_isAdLoading = true;
|
||||
@@ -84,12 +95,36 @@ class AdManager extends ChangeNotifier {
|
||||
return _loadCompleter!.future;
|
||||
}
|
||||
|
||||
/// Displays the rewarded video ad to the user.
|
||||
/// Returns false immediately when [adsEnabled] is false.
|
||||
// ── Show ad (or debug bypass) ─────────────────────────────────────
|
||||
|
||||
Future<bool> showAd(String adType) async {
|
||||
// Debug bypass: fire fake AdMob callback so support ads work in dev.
|
||||
// The server's ADMOB_BYPASS must be True for this to succeed.
|
||||
if (!adsEnabled && kDebugMode) {
|
||||
final deviceId = await CryptoService.getDeviceId();
|
||||
final nonce = '${Random().nextInt(0x7FFFFFFF)}-${DateTime.now().millisecondsSinceEpoch}';
|
||||
HivemindService.setExpectedNonce(nonce);
|
||||
try {
|
||||
final customData = jsonEncode({
|
||||
'device_id': deviceId,
|
||||
'ad_type': adType,
|
||||
'nonce': nonce,
|
||||
});
|
||||
final fakeUrl = Uri.parse(
|
||||
'${AppConfig.hivemindApiPublic}/admob/callback'
|
||||
'?signature=test&key_id=test'
|
||||
'&custom_data=${Uri.encodeComponent(customData)}');
|
||||
await HivemindService.directGet(fakeUrl, timeout: const Duration(seconds: 8));
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!adsEnabled) return false;
|
||||
|
||||
// 1. Ensure the ad is fully loaded before trying to show it
|
||||
await ensureSdkInitialized();
|
||||
|
||||
if (!_isAdLoaded || _rewardedAd == null) {
|
||||
final loaded = await preloadAd();
|
||||
if (!loaded || _rewardedAd == null) {
|
||||
@@ -98,16 +133,12 @@ class AdManager extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Fetch device ID for Server-Side Verification (SSV)
|
||||
final deviceId = await CryptoService.getDeviceId();
|
||||
|
||||
// 3. Generate a connect nonce so the subsequent poll can verify
|
||||
// it's talking to the session created by *this* ad.
|
||||
final nonce = '${Random().nextInt(0x7FFFFFFF)}-${DateTime.now().millisecondsSinceEpoch}';
|
||||
HivemindService.setExpectedNonce(nonce);
|
||||
debugPrint('[AdManager] Ad nonce: $nonce');
|
||||
|
||||
// 4. Build SSV options to send to our Hivemind server via Google's callback
|
||||
final ssvOptions = ServerSideVerificationOptions(
|
||||
customData: jsonEncode({
|
||||
'device_id': deviceId,
|
||||
@@ -118,7 +149,6 @@ class AdManager extends ChangeNotifier {
|
||||
|
||||
Completer<bool> rewardCompleter = Completer<bool>();
|
||||
|
||||
// 4. Setup full screen callbacks to handle dismissal and errors
|
||||
_rewardedAd!.fullScreenContentCallback = FullScreenContentCallback(
|
||||
onAdShowedFullScreenContent: (ad) => debugPrint('[AdManager] Ad showing.'),
|
||||
onAdDismissedFullScreenContent: (ad) {
|
||||
@@ -126,10 +156,9 @@ class AdManager extends ChangeNotifier {
|
||||
ad.dispose();
|
||||
_isAdLoaded = false;
|
||||
_rewardedAd = null;
|
||||
// Start loading the next ad immediately
|
||||
preloadAd();
|
||||
if (!rewardCompleter.isCompleted) {
|
||||
rewardCompleter.complete(false); // User closed before earning reward
|
||||
rewardCompleter.complete(false);
|
||||
}
|
||||
},
|
||||
onAdFailedToShowFullScreenContent: (ad, error) {
|
||||
@@ -143,13 +172,10 @@ class AdManager extends ChangeNotifier {
|
||||
},
|
||||
);
|
||||
|
||||
// 5. Show the ad with SSV options
|
||||
_rewardedAd!.setServerSideOptions(ssvOptions);
|
||||
await _rewardedAd!.show(
|
||||
onUserEarnedReward: (AdWithoutView ad, RewardItem reward) {
|
||||
debugPrint('[AdManager] Reward earned: ${reward.amount} ${reward.type}');
|
||||
// The SSV callback will hit our server independently. We just need to signal the UI
|
||||
// that the ad was successfully completed.
|
||||
if (!rewardCompleter.isCompleted) {
|
||||
rewardCompleter.complete(true);
|
||||
}
|
||||
|
||||
@@ -1,31 +1,39 @@
|
||||
// =============================================================================
|
||||
// app_config.example.dart — TEMPLATE FOR SERVER SETTINGS
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Rename this file to `app_config.dart` and fill in your real values.
|
||||
// Do not commit your real `app_config.dart` to GitHub!
|
||||
//
|
||||
// Most Reality tunnel fields (vless_ip, vless_port, reality_pbk, reality_sid,
|
||||
// reality_sni, reality_fp) come from the server's /session/status response.
|
||||
// The constants below are fallbacks — the server is the source of truth.
|
||||
// =============================================================================
|
||||
|
||||
abstract final class AppConfig {
|
||||
AppConfig._();
|
||||
AppConfig._(); // static members only
|
||||
|
||||
// ── Server (API) ──────────────────────────────────────────────────────
|
||||
static const String serverDomain = 'yourdomain.com'; // ◄── REPLACE
|
||||
|
||||
static String get hivemindApiBase => 'https://$serverDomain/api';
|
||||
// ── Server ───────────────────────────────────────────────────────────
|
||||
/// Your server's public IP. The VPN tunnel is pinned to this.
|
||||
static const String serverIp = '0.0.0.0'; // ◄── REPLACE
|
||||
static const String hivemindApiPublic = 'https://YOUR_DOMAIN/api'; // ◄── REPLACE
|
||||
|
||||
// ── Reality (VPN tunnel) ──────────────────────────────────────────────
|
||||
// These are fallbacks — normally overridden by /session/status response.
|
||||
static const String realitySni = 'www.microsoft.com';
|
||||
static const String realityFp = 'chrome';
|
||||
// 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 client does NOT hardcode one — server is always the source of truth.
|
||||
|
||||
// These are authoritative — never sent by the server.
|
||||
/// TLS fingerprint: chrome | firefox | safari | random
|
||||
static const String realityFp = 'chrome';
|
||||
|
||||
// These are normally overridden by /session/status response fields.
|
||||
static const String vlessSecurity = 'reality';
|
||||
static const String vlessType = 'tcp';
|
||||
static const String vlessFlow = 'xtls-rprx-vision';
|
||||
static const String vlessType = 'xhttp';
|
||||
|
||||
/// XHTTP path — must match xray_config_reality.json xhttpSettings.path.
|
||||
static const String vlessPath = '/revolt';
|
||||
|
||||
// ── Updates ────────────────────────────────────────────────────────────
|
||||
/// Used by the updater.
|
||||
static const String applicationId = 'com.paladinvpn.app'; // ◄── REPLACE
|
||||
static const String githubOwner = 'YOUR_GITHUB_USERNAME'; // ◄── REPLACE (current: 'esefxdz')
|
||||
static const String githubRepo = 'YOUR_REPO_NAME'; // ◄── REPLACE (current: 'ReVoltVPN')
|
||||
|
||||
/// Fallback URL if the GitHub API call fails.
|
||||
static const String githubReleasesUrl = 'https://github.com/$githubOwner/$githubRepo/releases/latest';
|
||||
|
||||
// ── AdMob ──────────────────────────────────────────────────────────────
|
||||
static const String adUnitId = 'ca-app-pub-0000000000000000/0000000000'; // REPLACE
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,17 @@ import 'package:uuid/uuid.dart';
|
||||
class CryptoService {
|
||||
static const String _deviceIdPref = 'device_uuid';
|
||||
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.
|
||||
/// Corrupted or tampered storage values are replaced instead of being sent
|
||||
/// to the public API as arbitrary query data.
|
||||
static Future<String> getDeviceId() async {
|
||||
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();
|
||||
await _storage.write(key: _deviceIdPref, value: newId);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:revoltvpn/logic/app_config.dart';
|
||||
@@ -10,85 +11,61 @@ class HivemindService {
|
||||
static String? _expectedNonce;
|
||||
static int _currentCallId = 0;
|
||||
|
||||
/// Call this from disconnect to abort any in-progress polling.
|
||||
static void cancel() {
|
||||
_currentCallId++; // bump — any running loop sees a stale ID and exits
|
||||
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';
|
||||
static const _pollBackoff = <Duration>[
|
||||
Duration(seconds: 1),
|
||||
Duration(seconds: 2),
|
||||
Duration(seconds: 3),
|
||||
Duration(seconds: 5),
|
||||
];
|
||||
|
||||
static Future<http.Response> directGet(
|
||||
Uri uri, {
|
||||
Duration timeout = const Duration(seconds: 5),
|
||||
}) {
|
||||
return http.get(uri, headers: {'User-Agent': _ua}).timeout(timeout);
|
||||
}
|
||||
|
||||
static void cancel() => _currentCallId++;
|
||||
|
||||
static void setExpectedNonce(String nonce) {
|
||||
_expectedNonce = nonce;
|
||||
}
|
||||
|
||||
/// Tries to fetch the VLESS config from the server.
|
||||
/// Only polls a few times — by the time the ad finishes, the SSV callback
|
||||
/// has usually already fired.
|
||||
static Future<String> fetchConfigWithPolling({
|
||||
static Future<String> fetchConfigDirectly({
|
||||
void Function(int attempt, int total)? onAttempt,
|
||||
bool skipAdBypass = false,
|
||||
bool quickReconnect = false,
|
||||
}) async {
|
||||
final deviceId = await CryptoService.getDeviceId();
|
||||
|
||||
final callId = ++_currentCallId;
|
||||
final nonce = '${Random().nextInt(0x7FFFFFFF)}-${DateTime.now().millisecondsSinceEpoch}';
|
||||
final nonce = _newNonce();
|
||||
_expectedNonce = nonce;
|
||||
debugPrint('[HivemindService] Call #$callId — nonce: $nonce');
|
||||
|
||||
final url = Uri.parse('${AppConfig.hivemindApiBase}/session/status?device_id=$deviceId');
|
||||
|
||||
// ── AD BYPASS (debug only) ────────────────────────────────────────
|
||||
if (kDebugMode && !skipAdBypass) {
|
||||
try {
|
||||
final customData = jsonEncode({'device_id': deviceId, 'nonce': nonce});
|
||||
final fakeUrl = Uri.parse(
|
||||
'${AppConfig.hivemindApiBase}/admob/callback?signature=test&key_id=test&custom_data=${Uri.encodeComponent(customData)}');
|
||||
await http.get(fakeUrl).timeout(const Duration(seconds: 8));
|
||||
} catch (_) {}
|
||||
if (!skipAdBypass) {
|
||||
await _runConfiguredBypass(deviceId, nonce);
|
||||
}
|
||||
|
||||
final maxAttempts = quickReconnect ? 1 : 5;
|
||||
for (int i = 1; i <= maxAttempts; i++) {
|
||||
if (_currentCallId != callId) throw Exception('Cancelled');
|
||||
const maxAttempts = 5;
|
||||
for (var attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
_throwIfCancelled(callId);
|
||||
onAttempt?.call(attempt, maxAttempts);
|
||||
|
||||
onAttempt?.call(i, maxAttempts);
|
||||
try {
|
||||
final response = await http.get(url).timeout(const Duration(seconds: 5));
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body);
|
||||
|
||||
final serverNonce = data['nonce'] as String?;
|
||||
if (_expectedNonce != null && serverNonce != null && serverNonce != _expectedNonce) {
|
||||
debugPrint('[HivemindService] Nonce mismatch — retrying…');
|
||||
} else if (data['active'] == true && data['vless_uuid'] != null) {
|
||||
final vlessUuid = data['vless_uuid'];
|
||||
|
||||
// Reality tunnel fields — server is source of truth, AppConfig is fallback.
|
||||
final vlessIp = data['vless_ip'] ?? AppConfig.serverDomain;
|
||||
final vlessPort = data['vless_port'] ?? 8443;
|
||||
final pbk = data['reality_pbk'] ?? '';
|
||||
final sid = data['reality_sid'] ?? '';
|
||||
final sni = data['reality_sni'] ?? AppConfig.realitySni;
|
||||
final fp = data['reality_fp'] ?? AppConfig.realityFp;
|
||||
|
||||
final vlessUrl = 'vless://$vlessUuid@$vlessIp:$vlessPort'
|
||||
'?security=${AppConfig.vlessSecurity}'
|
||||
'&type=${AppConfig.vlessType}'
|
||||
'&flow=${AppConfig.vlessFlow}'
|
||||
'&pbk=${Uri.encodeComponent(pbk)}'
|
||||
'&sni=${Uri.encodeComponent(sni)}'
|
||||
'&sid=${Uri.encodeComponent(sid)}'
|
||||
'&fp=${Uri.encodeComponent(fp)}'
|
||||
'#ReVoltVPN';
|
||||
_expectedNonce = null;
|
||||
return vlessUrl;
|
||||
}
|
||||
final session = await _fetchActiveSession(deviceId, nonce);
|
||||
if (session != null) {
|
||||
_expectedNonce = null;
|
||||
return session.toVlessUrl();
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.toString().contains('Cancelled')) rethrow;
|
||||
debugPrint('[HivemindService] Attempt $i failed: $e');
|
||||
if (_isCancelledError(e)) rethrow;
|
||||
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.');
|
||||
@@ -96,36 +73,139 @@ class HivemindService {
|
||||
|
||||
static Future<bool> checkHealth() async {
|
||||
try {
|
||||
final url = Uri.parse('${AppConfig.hivemindApiBase}/health');
|
||||
final response = await http.get(url).timeout(const Duration(seconds: 3));
|
||||
final response = await directGet(
|
||||
_publicUrl('/health'),
|
||||
timeout: const Duration(seconds: 3),
|
||||
);
|
||||
return response.statusCode == 200;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<bool> verifySession() async {
|
||||
try {
|
||||
final deviceId = await CryptoService.getDeviceId();
|
||||
final url = Uri.parse('${AppConfig.hivemindApiBase}/session/status?device_id=$deviceId');
|
||||
final response = await http.get(url).timeout(const Duration(seconds: 5));
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body);
|
||||
return data['active'] == true;
|
||||
}
|
||||
} catch (_) {}
|
||||
return false;
|
||||
static String _newNonce() {
|
||||
final random = Random.secure();
|
||||
final high = random.nextInt(0x7FFFFFFF);
|
||||
final low = random.nextInt(0x7FFFFFFF);
|
||||
return '$high-$low-${DateTime.now().microsecondsSinceEpoch}';
|
||||
}
|
||||
|
||||
static Future<void> disconnectAndCleanup() async {
|
||||
final deviceId = await CryptoService.getDeviceId();
|
||||
final url = Uri.parse('${AppConfig.hivemindApiBase}/session/stop');
|
||||
static Future<void> _runConfiguredBypass(String deviceId, String nonce) async {
|
||||
try {
|
||||
await http.post(
|
||||
url,
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({'device_id': deviceId}),
|
||||
).timeout(const Duration(seconds: 3));
|
||||
} catch (_) {}
|
||||
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.
|
||||
}
|
||||
}
|
||||
|
||||
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) =>
|
||||
Uri.parse('${AppConfig.hivemindApiPublic}$path');
|
||||
}
|
||||
|
||||
class _HivemindSessionConfig {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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>),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
// ── lib/logic/server_list.dart ──────────────────────────────────────────────
|
||||
// Server data model and ChangeNotifier — shared by StatusBar (shows current
|
||||
// server name/flag) and SelectionScreen (lets user pick a server).
|
||||
//
|
||||
// Each server is defined by its tunnel IP/port. Reality credentials (public
|
||||
// key, shortId) come from /session/status per session; only the transport
|
||||
// parameters live in AppConfig.
|
||||
//
|
||||
// When multi-server ships:
|
||||
// - _all becomes a fetched list (from /api/servers or bundled config)
|
||||
// - SelectionScreen shows multiple rows
|
||||
// - select() triggers a disconnect/reconnect cycle if the tunnel is active
|
||||
|
||||
class ServerInfo {
|
||||
final String id;
|
||||
final String name;
|
||||
final String flagAsset;
|
||||
final String ip;
|
||||
final int port;
|
||||
|
||||
const ServerInfo({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.flagAsset,
|
||||
required this.ip,
|
||||
required this.port,
|
||||
});
|
||||
}
|
||||
|
||||
class ServerList extends ChangeNotifier {
|
||||
static const _all = [
|
||||
ServerInfo(
|
||||
id: 'finland',
|
||||
name: 'Helsinki, Finland',
|
||||
flagAsset: 'assets/finland_flag_256.png',
|
||||
ip: '204.168.246.88',
|
||||
port: 443,
|
||||
),
|
||||
];
|
||||
|
||||
int _selectedIndex = 0;
|
||||
|
||||
List<ServerInfo> get all => _all;
|
||||
int get selectedIndex => _selectedIndex;
|
||||
ServerInfo get selected => _all[_selectedIndex];
|
||||
|
||||
// Loads persisted selection from SharedPreferences.
|
||||
// Fire-and-forget — UI starts with default, updates when prefs load.
|
||||
Future<void> init() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final saved = prefs.getInt('selected_server_index') ?? 0;
|
||||
if (saved >= 0 && saved < _all.length && saved != _selectedIndex) {
|
||||
_selectedIndex = saved;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
// Switches to a different server. Persists the choice.
|
||||
Future<void> select(int index) async {
|
||||
if (index == _selectedIndex || index < 0 || index >= _all.length) return;
|
||||
_selectedIndex = index;
|
||||
notifyListeners();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setInt('selected_server_index', index);
|
||||
}
|
||||
}
|
||||
@@ -1,53 +1,73 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:revoltvpn/logic/app_config.dart';
|
||||
import 'package:revoltvpn/logic/vpn_connection.dart';
|
||||
import 'package:revoltvpn/logic/crypto_service.dart';
|
||||
import 'package:revoltvpn/components/notification.dart';
|
||||
|
||||
class SessionTimer extends ChangeNotifier {
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:revoltvpn/logic/app_config.dart';
|
||||
import 'package:revoltvpn/logic/crypto_service.dart';
|
||||
import 'package:revoltvpn/logic/hivemind_service.dart';
|
||||
import 'package:revoltvpn/logic/notification_service.dart';
|
||||
import 'package:revoltvpn/logic/power_settings.dart';
|
||||
import 'package:revoltvpn/logic/vpn_connection.dart';
|
||||
|
||||
class SessionTimer extends ChangeNotifier with WidgetsBindingObserver {
|
||||
Timer? _timer;
|
||||
int _tickCount = 0;
|
||||
int _lastPushedExpiryAtMs = 0;
|
||||
bool _appBackgrounded = false;
|
||||
|
||||
final VpnConnection vpnConnection;
|
||||
|
||||
int _remainingSeconds = 0;
|
||||
int _usedBytes = 0;
|
||||
int _remainingAtLastSync = 0;
|
||||
int _usedBytes = 0;
|
||||
|
||||
bool _hasSyncedOnce = false;
|
||||
int _consecutiveFailures = 0;
|
||||
bool _isDisconnecting = false;
|
||||
bool _userInitiatedStop = false;
|
||||
bool _hasSyncedOnce = false;
|
||||
int _consecutiveFailures = 0;
|
||||
bool _isDisconnecting = false;
|
||||
bool _syncInProgress = false;
|
||||
bool _supportRewardClaimed = false;
|
||||
bool _supportRewardStateLoaded = false;
|
||||
int _supportStateEpoch = 0;
|
||||
|
||||
|
||||
int? _currentPort;
|
||||
bool _portSwitchInProgress = false;
|
||||
static const String _supportRewardClaimKey =
|
||||
'support_reward_claimed_active_session';
|
||||
static const FlutterSecureStorage _supportStorage = FlutterSecureStorage();
|
||||
|
||||
static const int _maxConsecutiveFailures = 3;
|
||||
|
||||
static const int _maxOfflineSeconds = 120;
|
||||
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;
|
||||
double _currentSpeedKBps = 0.0;
|
||||
|
||||
String _lastNotifTime = '';
|
||||
String _lastNotifSpeed = '';
|
||||
int _lastUsedBytes = 0;
|
||||
DateTime? _lastSuccessfulSyncAt;
|
||||
double _currentSpeedKBps = 0.0;
|
||||
|
||||
SessionTimer({required this.vpnConnection}) {
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
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;
|
||||
bool get isRunning => _timer != null && _timer!.isActive;
|
||||
bool get isExpired => _remainingSeconds <= 0 && !isRunning;
|
||||
bool get hasSyncedOnce => _hasSyncedOnce;
|
||||
int get remaining => _remainingSeconds;
|
||||
bool get isRunning => _timer != null && _timer!.isActive;
|
||||
bool get isExpired => _remainingSeconds <= 0 && !isRunning;
|
||||
bool get hasSyncedOnce => _hasSyncedOnce;
|
||||
bool get supportRewardClaimed => _supportRewardClaimed;
|
||||
bool get supportRewardStateLoaded => _supportRewardStateLoaded;
|
||||
|
||||
int get usedBytes => _usedBytes;
|
||||
int get usedBytes => _usedBytes;
|
||||
double get currentSpeedKBps => _currentSpeedKBps;
|
||||
|
||||
String get formatted {
|
||||
@@ -57,243 +77,328 @@ class SessionTimer extends ChangeNotifier {
|
||||
return '$h:$m:$s';
|
||||
}
|
||||
|
||||
// Lifecycle
|
||||
|
||||
/// Fires whenever VpnConnection state changes.
|
||||
void _onVpnConnectionChanged() {
|
||||
|
||||
if (vpnConnection.status == VpnStatus.connected &&
|
||||
!isRunning &&
|
||||
vpnConnection.isStartupRestoration) {
|
||||
_resumeTicking();
|
||||
return;
|
||||
Future<void> _loadSupportRewardState() async {
|
||||
final epoch = _supportStateEpoch;
|
||||
var claimed = false;
|
||||
try {
|
||||
claimed =
|
||||
(await _supportStorage.read(key: _supportRewardClaimKey)) == '1';
|
||||
} catch (e) {
|
||||
debugPrint('[Timer] Failed to load support reward state: $e');
|
||||
}
|
||||
|
||||
if (epoch != _supportStateEpoch) return;
|
||||
_supportRewardClaimed = claimed;
|
||||
_supportRewardStateLoaded = true;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
// The underlying VLESS tunnel may briefly flap. If we weren't
|
||||
// explicitly stopped by the user, resume where we left off.
|
||||
if (vpnConnection.status == VpnStatus.connected &&
|
||||
!isRunning &&
|
||||
!_userInitiatedStop &&
|
||||
_hasSyncedOnce) {
|
||||
debugPrint('[Timer] VPN reconnected after blip — resuming.');
|
||||
_resumeTicking();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (vpnConnection.status == VpnStatus.disconnected && isRunning) {
|
||||
_stopInternal();
|
||||
Future<void> _persistSupportRewardState(bool value) async {
|
||||
try {
|
||||
await _supportStorage.write(
|
||||
key: _supportRewardClaimKey,
|
||||
value: value ? '1' : '0',
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[Timer] Failed to persist support reward state: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> start() async {
|
||||
_remainingSeconds = 0;
|
||||
_usedBytes = 0;
|
||||
_lastUsedBytes = 0;
|
||||
_currentSpeedKBps = 0.0;
|
||||
_tickCount = 0;
|
||||
_hasSyncedOnce = false;
|
||||
Future<void> markSupportRewardClaimed() async {
|
||||
if (_supportRewardClaimed) return;
|
||||
_supportRewardClaimed = true;
|
||||
_supportRewardStateLoaded = true;
|
||||
notifyListeners();
|
||||
await _persistSupportRewardState(true);
|
||||
}
|
||||
|
||||
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;
|
||||
_offlineSeconds = 0;
|
||||
_isDisconnecting = false;
|
||||
_userInitiatedStop = false;
|
||||
_currentPort = null;
|
||||
_portSwitchInProgress = false;
|
||||
_offlineSeconds = 0;
|
||||
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 = Timer.periodic(const Duration(seconds: 1), _tick);
|
||||
|
||||
notifyListeners();
|
||||
|
||||
// Kick off the first sync — the UI will show real data as soon as it lands.
|
||||
_syncWithHivemind();
|
||||
unawaited(_syncWithHivemind());
|
||||
}
|
||||
|
||||
void _tick(Timer t) {
|
||||
if (_isDisconnecting) return;
|
||||
|
||||
// Decrement the local clock as long as we're not in a network blackout.
|
||||
if (_hasSyncedOnce && _consecutiveFailures < _maxConsecutiveFailures) {
|
||||
if (_remainingSeconds > 0) {
|
||||
_remainingSeconds--;
|
||||
}
|
||||
_reconcileElapsedTime();
|
||||
}
|
||||
|
||||
|
||||
// If the server has been unreachable for too long, kill the VPN.
|
||||
// Don't let an orphaned tunnel keep running forever.
|
||||
if (_consecutiveFailures >= _maxConsecutiveFailures) {
|
||||
_offlineSeconds++;
|
||||
if (_offlineSeconds >= _maxOfflineSeconds) {
|
||||
debugPrint('[Timer] Offline for $_maxOfflineSeconds s — forcing disconnect.');
|
||||
_forceDisconnect('Session lost — server unreachable');
|
||||
unawaited(_doDisconnect('Server unreachable'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// When our clock hits zero, disconnect immediately. Don't wait for the
|
||||
// next server poll — the session is over and the user expects the VPN
|
||||
// to drop right now.
|
||||
if (_hasSyncedOnce && _remainingSeconds <= 0) {
|
||||
debugPrint('[Timer] Local countdown expired — disconnecting.');
|
||||
_forceDisconnect('Session expired');
|
||||
unawaited(_doDisconnect('Session expired'));
|
||||
return;
|
||||
}
|
||||
|
||||
_tickCount++;
|
||||
if (_tickCount % _pollIntervalSeconds == 0) {
|
||||
_syncWithHivemind();
|
||||
}
|
||||
|
||||
|
||||
// Uses the locally-decremented time so the notification stays in sync
|
||||
// with the in-app display, not gated behind the 5 s server poll.
|
||||
if (_hasSyncedOnce) {
|
||||
final speedText = _currentSpeedKBps > 0.5
|
||||
? '${_currentSpeedKBps.toStringAsFixed(1)} KB/s'
|
||||
: 'Idle';
|
||||
if (formatted != _lastNotifTime || speedText != _lastNotifSpeed) {
|
||||
_lastNotifTime = formatted;
|
||||
_lastNotifSpeed = speedText;
|
||||
VpnNotificationManager.showOrUpdateStatus(
|
||||
timeLeft: formatted,
|
||||
speedKbps: speedText,
|
||||
);
|
||||
}
|
||||
final pollInterval = _appBackgrounded
|
||||
? _backgroundPollIntervalSeconds
|
||||
: _pollIntervalSeconds;
|
||||
if (_tickCount % pollInterval == 0) {
|
||||
unawaited(_syncWithHivemind());
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
|
||||
if (_hasSyncedOnce && vpnConnection.status == VpnStatus.connected) {
|
||||
NotificationService.updateTimer(formatted);
|
||||
}
|
||||
}
|
||||
|
||||
void _forceDisconnect(String reason) {
|
||||
if (_isDisconnecting) return; // Already tearing down
|
||||
debugPrint('[Timer] $reason — forcing disconnect.');
|
||||
/// 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 {
|
||||
await _doDisconnect(reason);
|
||||
}
|
||||
|
||||
Future<void> _doDisconnect(String reason) async {
|
||||
if (_isDisconnecting) return;
|
||||
_isDisconnecting = true;
|
||||
debugPrint('[Timer] Disconnecting: $reason');
|
||||
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
_currentSpeedKBps = 0.0;
|
||||
_isDisconnecting = true;
|
||||
VpnNotificationManager.cancel();
|
||||
_remainingSeconds = 0;
|
||||
_remainingAtLastSync = 0;
|
||||
_hasSyncedOnce = false;
|
||||
_lastSuccessfulSyncAt = null;
|
||||
NotificationService.reset();
|
||||
notifyListeners();
|
||||
|
||||
await vpnConnection.disconnect();
|
||||
|
||||
if (!_isDisconnecting) return;
|
||||
_isDisconnecting = false;
|
||||
notifyListeners();
|
||||
// Await the disconnect so the tunnel is confirmed down before we
|
||||
// consider the session fully cleaned up.
|
||||
vpnConnection.disconnect();
|
||||
}
|
||||
|
||||
|
||||
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 {
|
||||
// Never sync while the user is explicitly disconnecting.
|
||||
if (_isDisconnecting) return;
|
||||
|
||||
if (_isDisconnecting || _syncInProgress) return;
|
||||
_syncInProgress = true;
|
||||
try {
|
||||
final deviceId = await CryptoService.getDeviceId();
|
||||
final url = Uri.parse(
|
||||
'${AppConfig.hivemindApiBase}/session/status?device_id=$deviceId');
|
||||
final response = await http.get(url).timeout(const Duration(seconds: 5));
|
||||
final base = Uri.parse('${AppConfig.hivemindApiPublic}/session/status');
|
||||
final url = base.replace(queryParameters: {'device_id': deviceId});
|
||||
final response = await HivemindService.directGet(url);
|
||||
if (_isDisconnecting) return;
|
||||
|
||||
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;
|
||||
if (!active) {
|
||||
// Server killed the session — tear down and wait for it.
|
||||
stop();
|
||||
await vpnConnection.disconnect();
|
||||
final activeValue = data['active'];
|
||||
if (activeValue is! bool) {
|
||||
debugPrint('[Timer] Session payload missing boolean active state.');
|
||||
_markSyncFailure();
|
||||
return;
|
||||
}
|
||||
if (!activeValue) {
|
||||
await _doDisconnect('Server ended session');
|
||||
return;
|
||||
}
|
||||
|
||||
_remainingSeconds = data['expires_in_seconds'] ?? _remainingSeconds;
|
||||
_usedBytes = data['used_bytes'] ?? _usedBytes;
|
||||
final expiresValue = data['expires_in_seconds'];
|
||||
if (expiresValue is! num ||
|
||||
!expiresValue.isFinite ||
|
||||
expiresValue < 0) {
|
||||
debugPrint('[Timer] Session payload has invalid expiry.');
|
||||
_markSyncFailure();
|
||||
return;
|
||||
}
|
||||
|
||||
_remainingAtLastSync = expiresValue.toInt();
|
||||
_remainingSeconds = _remainingAtLastSync;
|
||||
// Push the absolute deadline to the VPN service so it can tear the
|
||||
// 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 int deltaBytes = _usedBytes - _lastUsedBytes;
|
||||
if (_hasSyncedOnce && deltaBytes > 0) {
|
||||
_currentSpeedKBps = (deltaBytes / _pollIntervalSeconds) / 1000;
|
||||
} else if (!_hasSyncedOnce) {
|
||||
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;
|
||||
}
|
||||
_lastUsedBytes = _usedBytes;
|
||||
_lastSuccessfulSyncAt = now;
|
||||
|
||||
|
||||
// ── Detect port change (throttle engage / disengage) ──────
|
||||
final serverPort = data['vless_port'];
|
||||
if (serverPort != null &&
|
||||
_currentPort != null &&
|
||||
serverPort != _currentPort &&
|
||||
!_portSwitchInProgress) {
|
||||
debugPrint('[Timer] Port changed $_currentPort → $serverPort — reconnecting…');
|
||||
_currentPort = serverPort;
|
||||
_portSwitchInProgress = true;
|
||||
|
||||
_timer?.cancel();
|
||||
_isDisconnecting = true;
|
||||
await vpnConnection.disconnect(skipCleanup: true);
|
||||
await vpnConnection.connect(skipAdBypass: true, quickReconnect: true);
|
||||
|
||||
_resumeTicking();
|
||||
_portSwitchInProgress = false;
|
||||
if (data['cap_exhausted'] == true) {
|
||||
await _doDisconnect('Data cap reached');
|
||||
return;
|
||||
}
|
||||
_currentPort = serverPort;
|
||||
|
||||
_consecutiveFailures = 0;
|
||||
_offlineSeconds = 0;
|
||||
_hasSyncedOnce = true;
|
||||
|
||||
notifyListeners();
|
||||
} else {
|
||||
_markSyncFailure();
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('Hivemind sync error: $e');
|
||||
_markSyncFailure();
|
||||
if (!_isDisconnecting) {
|
||||
debugPrint('Hivemind sync error: $e');
|
||||
_markSyncFailure();
|
||||
}
|
||||
} finally {
|
||||
_syncInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
void _markSyncFailure() {
|
||||
_consecutiveFailures++;
|
||||
if (_consecutiveFailures >= _maxConsecutiveFailures) {
|
||||
notifyListeners(); // let the UI show "Reconnecting…"
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
void stop() {
|
||||
_userInitiatedStop = true;
|
||||
_isDisconnecting = true;
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
_currentSpeedKBps = 0.0;
|
||||
_hasSyncedOnce = false;
|
||||
_remainingSeconds = 0;
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.paused ||
|
||||
state == AppLifecycleState.detached ||
|
||||
state == AppLifecycleState.inactive ||
|
||||
state == AppLifecycleState.hidden) {
|
||||
_appBackgrounded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (state != AppLifecycleState.resumed || _isDisconnecting) return;
|
||||
_appBackgrounded = false;
|
||||
if (vpnConnection.status != VpnStatus.connected) return;
|
||||
|
||||
_reconcileElapsedTime();
|
||||
if (!isRunning) {
|
||||
_resumeTicking();
|
||||
return;
|
||||
}
|
||||
|
||||
unawaited(_syncWithHivemind());
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _resumeTicking() {
|
||||
_reconcileElapsedTime();
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(const Duration(seconds: 1), _tick);
|
||||
_isDisconnecting = false;
|
||||
_syncWithHivemind();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _stopInternal() {
|
||||
_isDisconnecting = true;
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
_currentSpeedKBps = 0.0;
|
||||
_hasSyncedOnce = false;
|
||||
VpnNotificationManager.cancel();
|
||||
unawaited(_syncWithHivemind());
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
vpnConnection.removeListener(_onVpnConnectionChanged);
|
||||
_timer?.cancel();
|
||||
VpnNotificationManager.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:revoltvpn/logic/app_config.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
|
||||
enum UpdateStatus { upToDate, updateAvailable, checkFailed }
|
||||
|
||||
enum InstallSource { playStore, sideload }
|
||||
|
||||
Uri? _trustedHttpsUri(String raw, Set<String> allowedHosts) {
|
||||
final uri = Uri.tryParse(raw);
|
||||
if (uri == null || uri.scheme != 'https' || !allowedHosts.contains(uri.host)) {
|
||||
return null;
|
||||
}
|
||||
return uri;
|
||||
}
|
||||
|
||||
class _ParsedVersion {
|
||||
final List<int> core;
|
||||
final List<String> preRelease;
|
||||
|
||||
const _ParsedVersion(this.core, this.preRelease);
|
||||
|
||||
static _ParsedVersion? tryParse(String input) {
|
||||
var value = input.trim();
|
||||
if (value.startsWith('v') || value.startsWith('V')) {
|
||||
value = value.substring(1);
|
||||
}
|
||||
value = value.split('+').first;
|
||||
final dash = value.indexOf('-');
|
||||
final corePart = dash < 0 ? value : value.substring(0, dash);
|
||||
final prePart = dash < 0 ? '' : value.substring(dash + 1);
|
||||
final rawCore = corePart.split('.');
|
||||
if (rawCore.isEmpty || rawCore.any((p) => int.tryParse(p) == null)) {
|
||||
return null;
|
||||
}
|
||||
final core = rawCore.map(int.parse).toList(growable: false);
|
||||
while (core.length < 3) {
|
||||
core.add(0);
|
||||
}
|
||||
final pre = prePart.isEmpty
|
||||
? const <String>[]
|
||||
: prePart.split('.').where((e) => e.isNotEmpty).toList(growable: false);
|
||||
return _ParsedVersion(core, pre);
|
||||
}
|
||||
|
||||
int compareTo(_ParsedVersion other) {
|
||||
final length = core.length > other.core.length ? core.length : other.core.length;
|
||||
for (var i = 0; i < length; i++) {
|
||||
final left = i < core.length ? core[i] : 0;
|
||||
final right = i < other.core.length ? other.core[i] : 0;
|
||||
if (left != right) return left.compareTo(right);
|
||||
}
|
||||
|
||||
if (preRelease.isEmpty && other.preRelease.isEmpty) return 0;
|
||||
if (preRelease.isEmpty) return 1;
|
||||
if (other.preRelease.isEmpty) return -1;
|
||||
|
||||
final preLength = preRelease.length > other.preRelease.length
|
||||
? preRelease.length
|
||||
: other.preRelease.length;
|
||||
for (var i = 0; i < preLength; i++) {
|
||||
if (i >= preRelease.length) return -1;
|
||||
if (i >= other.preRelease.length) return 1;
|
||||
final left = preRelease[i];
|
||||
final right = other.preRelease[i];
|
||||
final leftNum = int.tryParse(left);
|
||||
final rightNum = int.tryParse(right);
|
||||
if (leftNum != null && rightNum != null) {
|
||||
if (leftNum != rightNum) return leftNum.compareTo(rightNum);
|
||||
continue;
|
||||
}
|
||||
if (leftNum != null) return -1;
|
||||
if (rightNum != null) return 1;
|
||||
final lexical = left.compareTo(right);
|
||||
if (lexical != 0) return lexical;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
class PlayStoreUpdater {
|
||||
PlayStoreUpdater._();
|
||||
|
||||
static String get _url =>
|
||||
'https://play.google.com/store/apps/details?id=${AppConfig.applicationId}';
|
||||
|
||||
static Future<bool> open() async {
|
||||
final uri = _trustedHttpsUri(_url, const {'play.google.com'});
|
||||
if (uri == null) {
|
||||
debugPrint('[Updater] Refusing invalid Play Store URL.');
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
} catch (e) {
|
||||
debugPrint('[Updater] Failed to open Play Store: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class GitHubUpdater {
|
||||
GitHubUpdater._();
|
||||
|
||||
static String? _cachedDownloadUrl;
|
||||
|
||||
static Future<String?> fetchLatestVersion() async {
|
||||
final apiUri = Uri.https(
|
||||
'api.github.com',
|
||||
'/repos/${AppConfig.githubOwner}/${AppConfig.githubRepo}/releases/latest',
|
||||
);
|
||||
|
||||
try {
|
||||
final response = await http
|
||||
.get(apiUri, headers: {'Accept': 'application/vnd.github+json'})
|
||||
.timeout(const Duration(seconds: 8));
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
debugPrint('[Updater] GitHub API returned ${response.statusCode}');
|
||||
return null;
|
||||
}
|
||||
|
||||
final decoded = jsonDecode(response.body);
|
||||
if (decoded is! Map<String, dynamic>) {
|
||||
debugPrint('[Updater] Invalid GitHub release payload.');
|
||||
return null;
|
||||
}
|
||||
|
||||
final htmlUrl = decoded['html_url'];
|
||||
if (htmlUrl is String &&
|
||||
_trustedHttpsUri(htmlUrl, const {'github.com'}) != null) {
|
||||
_cachedDownloadUrl = htmlUrl;
|
||||
} else {
|
||||
_cachedDownloadUrl = null;
|
||||
}
|
||||
|
||||
final rawTag = decoded['tag_name'];
|
||||
if (rawTag is! String || rawTag.isEmpty || rawTag.length > 64) {
|
||||
debugPrint('[Updater] Invalid release tag.');
|
||||
return null;
|
||||
}
|
||||
|
||||
final normalized = rawTag.startsWith('v') ? rawTag.substring(1) : rawTag;
|
||||
if (_ParsedVersion.tryParse(normalized) == null) {
|
||||
debugPrint('[Updater] Release tag is not a supported version: $rawTag');
|
||||
return null;
|
||||
}
|
||||
return normalized;
|
||||
} catch (e) {
|
||||
debugPrint('[Updater] GitHub API error: $e');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static Future<bool> open() async {
|
||||
final raw = _cachedDownloadUrl ?? AppConfig.githubReleasesUrl;
|
||||
final uri = _trustedHttpsUri(raw, const {'github.com'});
|
||||
if (uri == null) {
|
||||
debugPrint('[Updater] Refusing untrusted GitHub update URL.');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
} catch (e) {
|
||||
debugPrint('[Updater] Failed to open GitHub: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Updater {
|
||||
Updater._();
|
||||
|
||||
static InstallSource? _cachedSource;
|
||||
|
||||
static Future<InstallSource> get installSource async {
|
||||
if (_cachedSource != null) return _cachedSource!;
|
||||
if (kIsWeb || !Platform.isAndroid) {
|
||||
_cachedSource = InstallSource.sideload;
|
||||
return _cachedSource!;
|
||||
}
|
||||
|
||||
try {
|
||||
final result = await MethodChannel('com.revoltvpn.app/installer')
|
||||
.invokeMethod<String>('getInstallerPackage');
|
||||
_cachedSource = (result == 'com.android.vending')
|
||||
? InstallSource.playStore
|
||||
: InstallSource.sideload;
|
||||
} catch (e) {
|
||||
debugPrint('[Updater] Installer check failed: $e');
|
||||
_cachedSource = InstallSource.sideload;
|
||||
}
|
||||
|
||||
return _cachedSource!;
|
||||
}
|
||||
|
||||
static int _compareVersions(String a, String b) {
|
||||
final left = _ParsedVersion.tryParse(a);
|
||||
final right = _ParsedVersion.tryParse(b);
|
||||
if (left == null || right == null) {
|
||||
// Invalid local metadata should not invent an ordering.
|
||||
return 0;
|
||||
}
|
||||
return left.compareTo(right);
|
||||
}
|
||||
|
||||
static String _versionLabel(String v, bool isLocal) {
|
||||
final prefix = v.startsWith('v') ? '' : 'v';
|
||||
return '$prefix$v${isLocal ? ' (installed)' : ''}';
|
||||
}
|
||||
|
||||
static Future<void> check(BuildContext context) {
|
||||
final navigator = Navigator.of(context, rootNavigator: true);
|
||||
final messenger = ScaffoldMessenger.of(context);
|
||||
return checkWithHandles(
|
||||
navigator: navigator,
|
||||
messenger: messenger,
|
||||
);
|
||||
}
|
||||
|
||||
static Future<void> checkWithHandles({
|
||||
required NavigatorState navigator,
|
||||
required ScaffoldMessengerState messenger,
|
||||
}) async {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
final localVersion = info.version;
|
||||
if (localVersion.isEmpty || _ParsedVersion.tryParse(localVersion) == null) {
|
||||
_showSnackBar(
|
||||
messenger,
|
||||
'Could not determine app version',
|
||||
isError: true,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final latestVersion = await GitHubUpdater.fetchLatestVersion();
|
||||
if (latestVersion == null) {
|
||||
_showSnackBar(messenger, 'Could not reach GitHub', isError: true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (_compareVersions(localVersion, latestVersion) >= 0) {
|
||||
_showSnackBar(messenger, 'Up to date');
|
||||
return;
|
||||
}
|
||||
|
||||
final source = await installSource;
|
||||
final storeName =
|
||||
source == InstallSource.playStore ? 'Play Store' : 'GitHub';
|
||||
if (!navigator.mounted) return;
|
||||
|
||||
showDialog(
|
||||
context: navigator.context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
backgroundColor: AppColors.bgCard,
|
||||
title: const Text(
|
||||
'Update available',
|
||||
style: TextStyle(color: AppColors.textWhite),
|
||||
),
|
||||
content: Text(
|
||||
'${_versionLabel(latestVersion, false)} is available on $storeName.\n'
|
||||
'You have ${_versionLabel(localVersion, true)}.',
|
||||
style: const TextStyle(color: AppColors.slate70),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
child: const Text(
|
||||
'Later',
|
||||
style: TextStyle(color: AppColors.slate70),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(ctx);
|
||||
source == InstallSource.playStore
|
||||
? PlayStoreUpdater.open()
|
||||
: GitHubUpdater.open();
|
||||
},
|
||||
child: Text(
|
||||
'Open $storeName',
|
||||
style: const TextStyle(color: AppColors.accent),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
static void _showSnackBar(
|
||||
ScaffoldMessengerState messenger,
|
||||
String message, {
|
||||
bool isError = false,
|
||||
}) {
|
||||
if (!messenger.mounted) return;
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(
|
||||
isError ? Icons.error_outline : Icons.check_circle,
|
||||
color: isError ? AppColors.red : AppColors.green,
|
||||
size: 18,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(message),
|
||||
],
|
||||
),
|
||||
backgroundColor: AppColors.bgCard,
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.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/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 {
|
||||
disconnected,
|
||||
@@ -22,78 +28,174 @@ class VpnConnection extends ChangeNotifier {
|
||||
String? _errorMessage;
|
||||
String? get errorMessage => _errorMessage;
|
||||
|
||||
// True when the app was killed and reopened while the VPN was running.
|
||||
bool _isStartupRestoration = false;
|
||||
bool get isStartupRestoration => _isStartupRestoration;
|
||||
/// True when the UI attached to a tunnel that was already running, rather
|
||||
/// than starting one itself. The session timer uses this to resume ticking.
|
||||
bool _adoptedRunningRuntime = false;
|
||||
bool get adoptedRunningRuntime => _adoptedRunningRuntime;
|
||||
|
||||
bool _serverReachable = false;
|
||||
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;
|
||||
StreamSubscription<NetworkSnapshot>? _networkSubscription;
|
||||
|
||||
SecureSocksSession? _lastSecureSocks;
|
||||
bool _userDisconnecting = false;
|
||||
|
||||
late final FlutterVless _vless;
|
||||
bool _initialized = false;
|
||||
final Completer<void> _readyCompleter = Completer<void>();
|
||||
Future<void> get ready => _readyCompleter.future;
|
||||
|
||||
VpnConnection() {
|
||||
_activeMode = ConnectionSettings.mode;
|
||||
_init();
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
await ConnectionSettings.initialize();
|
||||
_activeMode = ConnectionSettings.mode;
|
||||
|
||||
_vless = FlutterVless(
|
||||
onStatusChanged: (status) {
|
||||
debugPrint('[VPN] Status: state=${status.state} '
|
||||
'connection=${status.connectionState.name}');
|
||||
debugPrint(
|
||||
'[VPN] Status: state=${status.state} '
|
||||
'connection=${status.connectionState.name}',
|
||||
);
|
||||
_mapStatus(status);
|
||||
},
|
||||
);
|
||||
|
||||
try {
|
||||
await _vless.initializeVless(
|
||||
providerBundleIdentifier: 'com.revoltvpn.app',
|
||||
providerBundleIdentifier: 'com.paladinvpn.app',
|
||||
notificationIconResourceType: 'drawable',
|
||||
notificationIconResourceName: 'notification_status_icon',
|
||||
);
|
||||
_initialized = true;
|
||||
} catch (e) {
|
||||
debugPrint('[VPN] VLESS init error (expected on emulator): $e');
|
||||
}
|
||||
|
||||
// Periodic server health check
|
||||
_checkHealth();
|
||||
_healthTimer = Timer.periodic(const Duration(seconds: 30), (_) => _checkHealth());
|
||||
_networkSubscription = NetworkMonitor.changes.listen(
|
||||
(snapshot) {
|
||||
// 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());
|
||||
});
|
||||
|
||||
// Check if VPN was already running (app killed and reopened)
|
||||
try {
|
||||
final coreVersion = await _vless.getCoreVersion();
|
||||
debugPrint('[VPN] Xray core version: $coreVersion');
|
||||
|
||||
final delay = await _vless.getConnectedServerDelay();
|
||||
if (delay > 0) {
|
||||
_isStartupRestoration = true;
|
||||
_setStatus(VpnStatus.connected, 'Secured');
|
||||
}
|
||||
} 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) {
|
||||
switch (status.connectionState) {
|
||||
case VlessConnectionState.connected:
|
||||
_setStatus(VpnStatus.connected, 'Secured');
|
||||
_setStatus(VpnStatus.connected, _connectedLabel);
|
||||
break;
|
||||
|
||||
case VlessConnectionState.disconnected:
|
||||
_isStartupRestoration = false;
|
||||
_clearRuntimeSnapshot();
|
||||
_setStatus(VpnStatus.disconnected, 'Tap to connect');
|
||||
break;
|
||||
|
||||
case VlessConnectionState.connecting:
|
||||
_setStatus(VpnStatus.connecting, 'Establishing tunnel…');
|
||||
break;
|
||||
|
||||
case VlessConnectionState.disconnecting:
|
||||
_isStartupRestoration = false;
|
||||
_setStatus(VpnStatus.disconnecting, 'Tearing down…');
|
||||
break;
|
||||
|
||||
case VlessConnectionState.unknown:
|
||||
// Native backend emitted an unrecognized state — treat as error
|
||||
// only if we aren't already in a terminal state.
|
||||
if (_status != VpnStatus.connected &&
|
||||
_status != VpnStatus.disconnected) {
|
||||
_setStatus(VpnStatus.error, 'Connection failed');
|
||||
@@ -102,11 +204,16 @@ class VpnConnection extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> connect({bool skipAdBypass = false, bool quickReconnect = false}) async {
|
||||
Future<bool> connect({bool skipAdBypass = false}) async {
|
||||
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_cancelled = false;
|
||||
_userDisconnecting = false;
|
||||
|
||||
await ConnectionSettings.initialize();
|
||||
_activeMode = ConnectionSettings.mode;
|
||||
|
||||
if (!kIsWeb && !_initialized) {
|
||||
_errorMessage = 'VPN service unavailable.';
|
||||
@@ -114,7 +221,22 @@ class VpnConnection extends ChangeNotifier {
|
||||
return false;
|
||||
}
|
||||
|
||||
_setStatus(VpnStatus.connecting, 'Fetching config…');
|
||||
// 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();
|
||||
if (!ok) {
|
||||
_errorMessage = 'VPN permission denied.';
|
||||
_setStatus(VpnStatus.error, 'Permission required');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
final startingMessage = switch (_activeMode) {
|
||||
ConnectionMode.tun => 'Establishing secure channel…',
|
||||
ConnectionMode.proxy => 'Starting local SOCKS5 proxy…',
|
||||
};
|
||||
_setStatus(VpnStatus.connecting, startingMessage);
|
||||
_errorMessage = null;
|
||||
|
||||
if (kIsWeb) {
|
||||
@@ -123,33 +245,30 @@ class VpnConnection extends ChangeNotifier {
|
||||
return true;
|
||||
}
|
||||
|
||||
String vlessUrl;
|
||||
_setStatus(VpnStatus.connecting, 'Fetching config…');
|
||||
|
||||
String realUrl;
|
||||
try {
|
||||
vlessUrl = await HivemindService.fetchConfigWithPolling(
|
||||
realUrl = await HivemindService.fetchConfigDirectly(
|
||||
skipAdBypass: skipAdBypass,
|
||||
quickReconnect: quickReconnect,
|
||||
onAttempt: (attempt, total) {
|
||||
if (!quickReconnect) {
|
||||
_setStatus(VpnStatus.connecting, 'Contacting server ($attempt/$total)…');
|
||||
}
|
||||
_setStatus(
|
||||
VpnStatus.connecting,
|
||||
'Contacting server ($attempt/$total)…',
|
||||
);
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[VPN] Hivemind config error: $e');
|
||||
debugPrint('[VPN] Config fetch error: $e');
|
||||
final raw = e.toString().replaceAll('Exception: ', '');
|
||||
if (raw.contains('Cancelled')) {
|
||||
// User tapped disconnect — silently abort
|
||||
return false;
|
||||
} else if (raw.contains('timed out') || raw.contains('Session not activated')) {
|
||||
_errorMessage = 'The server did not respond in time.\nCheck your connection and try again.';
|
||||
if (raw.contains('Cancelled')) return false;
|
||||
if (raw.contains('timed out') || raw.contains('Session not activated')) {
|
||||
_errorMessage =
|
||||
'The server did not respond in time.\nCheck your connection and try again.';
|
||||
_setStatus(VpnStatus.error, 'Server unreachable');
|
||||
} else if (raw.contains('SocketException') || raw.contains('Failed host lookup')) {
|
||||
_errorMessage = 'Cannot reach the server.\nMake sure you have internet access.';
|
||||
_setStatus(VpnStatus.error, 'No internet');
|
||||
} else {
|
||||
_errorMessage = raw;
|
||||
final short = raw.length > 35 ? '${raw.substring(0, 35)}…' : raw;
|
||||
_setStatus(VpnStatus.error, short);
|
||||
_setStatus(VpnStatus.error, 'Config fetch error');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -159,57 +278,115 @@ class VpnConnection extends ChangeNotifier {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
final parsed = FlutterVless.parse(vlessUrl);
|
||||
final config = parsed.getFullConfiguration();
|
||||
_setStatus(VpnStatus.connecting, 'Starting secure route…');
|
||||
|
||||
await _vless.startVless(
|
||||
remark: parsed.remark.isNotEmpty ? parsed.remark : 'ReVoltVPN',
|
||||
config: config,
|
||||
try {
|
||||
final parsed = FlutterVless.parse(realUrl);
|
||||
final baseConfig = parsed.getFullConfiguration();
|
||||
final remark = parsed.remark.isNotEmpty ? parsed.remark : 'Revolt VPN';
|
||||
final secureSocks = await SecureSocksSession.create(baseConfig);
|
||||
final verifyLocalSocks = _activeMode == ConnectionMode.proxy;
|
||||
|
||||
await _startRuntime(
|
||||
config: secureSocks.configJson,
|
||||
remark: remark,
|
||||
proxyOnly: verifyLocalSocks,
|
||||
);
|
||||
|
||||
if (quickReconnect) {
|
||||
_setStatus(VpnStatus.connected, 'Secured');
|
||||
} else {
|
||||
// Give the tunnel a moment to stabilise
|
||||
_setStatus(VpnStatus.connecting, 'Verifying session…');
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
|
||||
bool sessionOk = false;
|
||||
for (int attempt = 0; attempt < 2; attempt++) {
|
||||
sessionOk = await HivemindService.verifySession();
|
||||
if (sessionOk) break;
|
||||
if (attempt == 0) {
|
||||
debugPrint('[VPN] verifySession attempt 1 failed, retrying…');
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
}
|
||||
}
|
||||
|
||||
if (!sessionOk) {
|
||||
debugPrint('[VPN] Tunnel started but no server session — tearing down.');
|
||||
try {
|
||||
await _vless.stopVless();
|
||||
} catch (_) {}
|
||||
_errorMessage = 'Session not confirmed by server.\nPlease try again.';
|
||||
_setStatus(VpnStatus.error, 'Session rejected');
|
||||
return false;
|
||||
}
|
||||
|
||||
_setStatus(VpnStatus.connected, 'Secured');
|
||||
_setStatus(
|
||||
VpnStatus.connecting,
|
||||
verifyLocalSocks ? 'Waiting for local SOCKS5…' : 'Waiting for VPN interface…',
|
||||
);
|
||||
if (!await _waitForNativeConnected()) {
|
||||
throw StateError('VPN runtime did not report CONNECTED');
|
||||
}
|
||||
return true;
|
||||
|
||||
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) {
|
||||
debugPrint('[VPN] VLESS tunnel error: $e');
|
||||
_errorMessage = 'Tunnel failed to start.\nTry reconnecting.';
|
||||
debugPrint('[VPN] Tunnel start error: $e');
|
||||
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');
|
||||
return false;
|
||||
}
|
||||
|
||||
_setStatus(VpnStatus.connected, _connectedLabel);
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> disconnect({bool skipCleanup = false}) async {
|
||||
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 {
|
||||
_cancelled = true;
|
||||
HivemindService.cancel(); // abort any in-progress polling
|
||||
if (_status == VpnStatus.disconnected || _status == VpnStatus.disconnecting) {
|
||||
_userDisconnecting = true;
|
||||
HivemindService.cancel();
|
||||
|
||||
if (_status == VpnStatus.disconnected ||
|
||||
_status == VpnStatus.disconnecting) {
|
||||
_clearRuntimeSnapshot();
|
||||
_userDisconnecting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -217,32 +394,57 @@ class VpnConnection extends ChangeNotifier {
|
||||
|
||||
if (kIsWeb) {
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
_clearRuntimeSnapshot();
|
||||
_setStatus(VpnStatus.disconnected, 'Tap to connect');
|
||||
_userDisconnecting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
bool timedOut = false;
|
||||
try {
|
||||
await _vless.stopVless().timeout(
|
||||
const Duration(seconds: 5),
|
||||
onTimeout: () => debugPrint('[VPN] stopVless() timed out.'),
|
||||
);
|
||||
const Duration(seconds: 5),
|
||||
onTimeout: () => timedOut = true,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[VPN] VLESS stop error: $e');
|
||||
_errorMessage = 'VPN shutdown error.\nPlease restart the app.';
|
||||
_clearRuntimeSnapshot();
|
||||
_setStatus(VpnStatus.error, 'Shutdown failed');
|
||||
_userDisconnecting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!skipCleanup) {
|
||||
HivemindService.disconnectAndCleanup();
|
||||
if (timedOut) {
|
||||
debugPrint('[VPN] stopVless() timed out after 5 s.');
|
||||
_errorMessage = 'VPN did not shut down cleanly.\nPlease restart the app.';
|
||||
_clearRuntimeSnapshot();
|
||||
_setStatus(VpnStatus.error, 'Shutdown failed');
|
||||
_userDisconnecting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
_errorMessage = null;
|
||||
_clearRuntimeSnapshot();
|
||||
_setStatus(VpnStatus.disconnected, 'Tap to connect');
|
||||
_userDisconnecting = false;
|
||||
}
|
||||
|
||||
void _setStatus(VpnStatus s, String msg) {
|
||||
_status = s;
|
||||
_statusMessage = msg;
|
||||
void _clearRuntimeSnapshot() {
|
||||
_lastSecureSocks = null;
|
||||
_adoptedRunningRuntime = false;
|
||||
}
|
||||
|
||||
void _setStatus(VpnStatus status, String message) {
|
||||
_status = status;
|
||||
_statusMessage = message;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
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();
|
||||
notifyListeners();
|
||||
}
|
||||
@@ -250,13 +452,9 @@ class VpnConnection extends ChangeNotifier {
|
||||
@override
|
||||
void dispose() {
|
||||
_healthTimer?.cancel();
|
||||
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) {
|
||||
try {
|
||||
_vless.stopVless();
|
||||
} catch (_) {
|
||||
// Best-effort — widget is being destroyed anyway
|
||||
}
|
||||
}
|
||||
_networkSubscription?.cancel();
|
||||
// Provider/UI disposal is not a user disconnect command. Keeping teardown
|
||||
// in disconnect() prevents lifecycle churn from silently dropping the VPN.
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,23 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:google_mobile_ads/google_mobile_ads.dart';
|
||||
|
||||
import 'package:revoltvpn/logic/vpn_connection.dart';
|
||||
import 'package:revoltvpn/logic/session_timer.dart';
|
||||
import 'package:revoltvpn/logic/ad_manager.dart';
|
||||
import 'package:revoltvpn/logic/consent_manager.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';
|
||||
|
||||
void main() async {
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
|
||||
await HapticSettings.initialize();
|
||||
await ConnectionSettings.initialize();
|
||||
await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
|
||||
|
||||
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
|
||||
statusBarColor: Colors.transparent,
|
||||
@@ -32,9 +35,6 @@ void main() async {
|
||||
return true;
|
||||
};
|
||||
|
||||
await ConsentManager.requestConsentIfNeeded();
|
||||
await MobileAds.instance.initialize();
|
||||
|
||||
runApp(const ReVoltApp());
|
||||
}
|
||||
|
||||
@@ -45,12 +45,21 @@ class ReVoltApp extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider(create: (_) => VpnConnection()),
|
||||
ChangeNotifierProvider(create: (_) => VpnConnection(), lazy: false),
|
||||
ChangeNotifierProxyProvider<VpnConnection, SessionTimer>(
|
||||
create: (ctx) => SessionTimer(vpnConnection: ctx.read<VpnConnection>()),
|
||||
update: (_, vpn, prev) => prev ?? SessionTimer(vpnConnection: vpn),
|
||||
// Eager, like VpnConnection: the timer has to be listening before the
|
||||
// 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: (_) => ServerList()..init(),
|
||||
lazy: false,
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
title: 'ReVolt VPN',
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.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/settings/in_settings/rain.dart';
|
||||
import 'package:revoltvpn/screens/settings/in_settings/lightning.dart';
|
||||
|
||||
class IntroScreen extends StatefulWidget {
|
||||
const IntroScreen({super.key});
|
||||
@@ -11,11 +16,18 @@ class IntroScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
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
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_scheduleNavigation();
|
||||
_boot();
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -26,28 +38,56 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
_navigateToMain();
|
||||
if (state == AppLifecycleState.resumed) _navigateIfReady();
|
||||
}
|
||||
|
||||
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() {
|
||||
// Brief natural pause — just long enough to perceive the logo.
|
||||
Timer(const Duration(milliseconds: 1200), () {
|
||||
if (!mounted) return;
|
||||
if (WidgetsBinding.instance.lifecycleState == AppLifecycleState.paused) {
|
||||
// App is backgrounded — defer navigation until resumed.
|
||||
return;
|
||||
}
|
||||
_navigateToMain();
|
||||
});
|
||||
}
|
||||
try {
|
||||
await settingsPrefs;
|
||||
} catch (e) {
|
||||
debugPrint('[Boot] Settings prefs load failed, using defaults: $e');
|
||||
}
|
||||
|
||||
void _navigateToMain() {
|
||||
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(
|
||||
PageRouteBuilder(
|
||||
transitionDuration: const Duration(milliseconds: 600),
|
||||
transitionDuration: const Duration(milliseconds: 400),
|
||||
pageBuilder: (_, __, ___) => const MainScreen(),
|
||||
transitionsBuilder: (_, animation, __, child) {
|
||||
return FadeTransition(opacity: animation, child: child);
|
||||
@@ -63,7 +103,6 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
|
||||
body: Column(
|
||||
children: [
|
||||
const Spacer(flex: 7),
|
||||
// Image slightly below center
|
||||
Center(
|
||||
child: Image.asset(
|
||||
'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(
|
||||
width: 40,
|
||||
@@ -90,7 +128,7 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
const Text(
|
||||
'REVOLT VPN',
|
||||
'Revolt VPN',
|
||||
style: TextStyle(
|
||||
color: AppColors.textWhite,
|
||||
fontSize: 28,
|
||||
@@ -98,6 +136,19 @@ class _IntroScreenState extends State<IntroScreen> with WidgetsBindingObserver {
|
||||
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 SizedBox(height: 12),
|
||||
],
|
||||
|
||||
@@ -1,15 +1,32 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
import 'package:revoltvpn/components/connect_button.dart';
|
||||
import 'package:revoltvpn/components/data_disclosure_dialog.dart';
|
||||
import 'package:revoltvpn/components/sidebar_drawer.dart';
|
||||
import 'package:revoltvpn/components/timer_box.dart';
|
||||
import 'package:revoltvpn/components/speed_box.dart';
|
||||
import 'package:revoltvpn/components/status_bar.dart';
|
||||
import 'package:revoltvpn/components/support_button.dart';
|
||||
import 'package:revoltvpn/components/rain.dart';
|
||||
import 'package:revoltvpn/components/lightning.dart';
|
||||
|
||||
class MainScreen extends StatelessWidget {
|
||||
class MainScreen extends StatefulWidget {
|
||||
const MainScreen({super.key});
|
||||
|
||||
@override
|
||||
State<MainScreen> createState() => _MainScreenState();
|
||||
}
|
||||
|
||||
class _MainScreenState extends State<MainScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Show data disclosure on first launch — Google Play Data safety requirement.
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
DataDisclosureDialog.showIfFirstLaunch(context);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
@@ -27,55 +44,70 @@ class MainScreen extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: Stack(
|
||||
children: [
|
||||
Positioned(
|
||||
top: 0,
|
||||
right: 4,
|
||||
child: Builder(
|
||||
builder: (ctx) => IconButton(
|
||||
icon: const Icon(Icons.menu, color: AppColors.textWhite, size: 28),
|
||||
onPressed: () => Scaffold.of(ctx).openEndDrawer(),
|
||||
tooltip: 'Menu', splashRadius: 24,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
// Proportional positioning — fractions of available height.
|
||||
// On the reference device (~700 dp) this produces the exact
|
||||
// original pixel positions (100, 175, 250, 520) and scales
|
||||
// proportionally on taller/shorter screens.
|
||||
final h = constraints.maxHeight;
|
||||
return Stack(
|
||||
children: [
|
||||
// Lightning — behind rain
|
||||
const Positioned.fill(child: LightningEffect()),
|
||||
|
||||
// Rain — behind all UI
|
||||
const Positioned.fill(child: RainEffect()),
|
||||
|
||||
Positioned(
|
||||
top: 0,
|
||||
right: 4,
|
||||
child: Builder(
|
||||
builder: (ctx) => IconButton(
|
||||
icon: const Icon(Icons.menu, color: AppColors.textWhite, size: 28),
|
||||
onPressed: () => Scaffold.of(ctx).openEndDrawer(),
|
||||
tooltip: 'Menu', splashRadius: 24,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
Positioned(
|
||||
top: 100, // <-- CHANGE ME: timer distance from top
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: const Center(child: TimerBox()),
|
||||
),
|
||||
Positioned(
|
||||
top: h * 0.143,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: const Center(child: TimerBox()),
|
||||
),
|
||||
|
||||
Positioned(
|
||||
top: 175, // <-- CHANGE ME: support button from top
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: const Center(child: SupportButton()),
|
||||
),
|
||||
Positioned(
|
||||
top: h * 0.250,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: const Center(child: SupportButton()),
|
||||
),
|
||||
|
||||
Positioned(
|
||||
top: 250, // <-- CHANGE ME: connect button from top
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: const Center(child: ConnectButton()),
|
||||
),
|
||||
Positioned(
|
||||
top: h * 0.357,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: const Center(child: ConnectButton()),
|
||||
),
|
||||
|
||||
Positioned(
|
||||
top: 520, // <-- CHANGE ME: speed box from top
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: const Center(child: SpeedBox()),
|
||||
),
|
||||
Positioned(
|
||||
top: h * 0.743,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: const Center(child: SpeedBox()),
|
||||
),
|
||||
|
||||
Positioned(
|
||||
bottom: 16, // <-- CHANGE ME: status bar from bottom
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: const StatusBar(),
|
||||
),
|
||||
],
|
||||
const Positioned(
|
||||
bottom: 16,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: StatusBar(),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
import 'package:revoltvpn/logic/server_list.dart';
|
||||
|
||||
// ── lib/screens/server_selector/selection_screen.dart ──────────────────────
|
||||
// Server picker — reads the server list from the ServerList provider.
|
||||
// Each row shows a flag + city name. Tapping a row persists the choice
|
||||
// and pops back. No latency measurement — the app runs inside a Reality
|
||||
// tunnel and must not emit separate probe traffic.
|
||||
|
||||
class SelectionScreen extends StatelessWidget {
|
||||
const SelectionScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final serverList = context.watch<ServerList>();
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.bgDeep,
|
||||
appBar: AppBar(
|
||||
backgroundColor: AppColors.bgSurface,
|
||||
elevation: 0,
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back, color: AppColors.textWhite),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
),
|
||||
title: const Text(
|
||||
'Select Server',
|
||||
style: TextStyle(
|
||||
color: AppColors.textWhite,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
body: ListView.builder(
|
||||
itemCount: serverList.all.length,
|
||||
itemBuilder: (context, index) {
|
||||
final server = serverList.all[index];
|
||||
final isSelected = index == serverList.selectedIndex;
|
||||
|
||||
return ListTile(
|
||||
leading: Image.asset(server.flagAsset, width: 28, height: 28),
|
||||
title: Text(server.name,
|
||||
style: TextStyle(
|
||||
color: isSelected ? AppColors.accent : AppColors.textWhite,
|
||||
fontWeight: FontWeight.w600,
|
||||
)),
|
||||
trailing: isSelected
|
||||
? const Icon(Icons.check, color: AppColors.accent)
|
||||
: null,
|
||||
onTap: () {
|
||||
serverList.select(index);
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
contentPadding:
|
||||
const EdgeInsets.symmetric(horizontal: 20, vertical: 8),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
import 'package:revoltvpn/logic/haptic_settings.dart';
|
||||
|
||||
class HapticFeedbackTile extends StatefulWidget {
|
||||
const HapticFeedbackTile({super.key});
|
||||
|
||||
@override
|
||||
State<HapticFeedbackTile> createState() => _HapticFeedbackTileState();
|
||||
}
|
||||
|
||||
class _HapticFeedbackTileState extends State<HapticFeedbackTile> {
|
||||
bool _on = HapticSettings.enabled;
|
||||
bool _saving = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
await HapticSettings.initialize();
|
||||
if (mounted) setState(() => _on = HapticSettings.enabled);
|
||||
}
|
||||
|
||||
Future<void> _toggle(bool value) async {
|
||||
if (_saving) return;
|
||||
setState(() {
|
||||
_saving = true;
|
||||
_on = value;
|
||||
});
|
||||
|
||||
try {
|
||||
await HapticSettings.setEnabled(value);
|
||||
} catch (_) {
|
||||
if (mounted) setState(() => _on = HapticSettings.enabled);
|
||||
} finally {
|
||||
if (mounted) setState(() => _saving = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SwitchListTile(
|
||||
title: const Text(
|
||||
'Haptic feedback',
|
||||
style: TextStyle(color: AppColors.textWhite, fontSize: 15),
|
||||
),
|
||||
value: _on,
|
||||
onChanged: _saving ? null : _toggle,
|
||||
activeTrackColor: AppColors.accent.withAlpha(80),
|
||||
activeThumbColor: AppColors.accent,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
|
||||
// ── lib/screens/settings/in_settings/lightning.dart ─────────────────────────
|
||||
// Toggle for the lightning strike overlay on the main screen.
|
||||
|
||||
final ValueNotifier<bool> lightningEnabled = ValueNotifier(true);
|
||||
|
||||
Future<void> loadLightningPref() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
lightningEnabled.value = prefs.getBool('lightning_effect_enabled') ?? true;
|
||||
}
|
||||
|
||||
class LightningToggleTile extends StatefulWidget {
|
||||
const LightningToggleTile({super.key});
|
||||
|
||||
@override
|
||||
State<LightningToggleTile> createState() => _LightningToggleTileState();
|
||||
}
|
||||
|
||||
class _LightningToggleTileState extends State<LightningToggleTile> {
|
||||
bool _on = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
await loadLightningPref();
|
||||
if (mounted) setState(() => _on = lightningEnabled.value);
|
||||
}
|
||||
|
||||
Future<void> _toggle(bool value) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool('lightning_effect_enabled', value);
|
||||
lightningEnabled.value = value;
|
||||
setState(() => _on = value);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SwitchListTile(
|
||||
title: const Text(
|
||||
'Lightning effect',
|
||||
style: TextStyle(color: AppColors.textWhite, fontSize: 15),
|
||||
),
|
||||
value: _on,
|
||||
onChanged: _toggle,
|
||||
activeTrackColor: AppColors.accent.withAlpha(80),
|
||||
activeThumbColor: AppColors.accent,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
|
||||
// ── lib/screens/settings/in_settings/rain.dart ──────────────────────────────
|
||||
// Toggle for the animated rain overlay on the main screen.
|
||||
|
||||
final ValueNotifier<bool> rainEnabled = ValueNotifier(true);
|
||||
|
||||
Future<void> loadRainPref() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
rainEnabled.value = prefs.getBool('rain_effect_enabled') ?? true;
|
||||
}
|
||||
|
||||
class RainToggleTile extends StatefulWidget {
|
||||
const RainToggleTile({super.key});
|
||||
|
||||
@override
|
||||
State<RainToggleTile> createState() => _RainToggleTileState();
|
||||
}
|
||||
|
||||
class _RainToggleTileState extends State<RainToggleTile> {
|
||||
bool _on = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
await loadRainPref();
|
||||
if (mounted) setState(() => _on = rainEnabled.value);
|
||||
}
|
||||
|
||||
Future<void> _toggle(bool value) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool('rain_effect_enabled', value);
|
||||
rainEnabled.value = value;
|
||||
setState(() => _on = value);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SwitchListTile(
|
||||
title: const Text(
|
||||
'Rain effect',
|
||||
style: TextStyle(color: AppColors.textWhite, fontSize: 15),
|
||||
),
|
||||
value: _on,
|
||||
onChanged: _toggle,
|
||||
activeTrackColor: AppColors.accent.withAlpha(80),
|
||||
activeThumbColor: AppColors.accent,
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:revoltvpn/logic/app_colors.dart';
|
||||
import 'package:revoltvpn/screens/settings/in_settings/background_reliability.dart';
|
||||
import 'package:revoltvpn/screens/settings/in_settings/connection_mode.dart';
|
||||
import 'package:revoltvpn/screens/settings/in_settings/haptic.dart';
|
||||
import 'package:revoltvpn/screens/settings/in_settings/lightning.dart';
|
||||
import 'package:revoltvpn/screens/settings/in_settings/rain.dart';
|
||||
|
||||
class SettingsScreen extends StatelessWidget {
|
||||
const SettingsScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.bgDeep,
|
||||
appBar: AppBar(
|
||||
backgroundColor: AppColors.bgSurface,
|
||||
elevation: 0,
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back, color: AppColors.textWhite),
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
),
|
||||
title: const Text(
|
||||
'Settings',
|
||||
style: TextStyle(
|
||||
color: AppColors.textWhite,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
children: const [
|
||||
ConnectionModeTile(),
|
||||
BackgroundReliabilityTile(),
|
||||
HapticFeedbackTile(),
|
||||
RainToggleTile(),
|
||||
LightningToggleTile(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -73,14 +73,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.9"
|
||||
dbus:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: dbus
|
||||
sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.12"
|
||||
fake_async:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -97,14 +89,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.0"
|
||||
ffi_leak_tracker:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: ffi_leak_tracker
|
||||
sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.1.2"
|
||||
file:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -134,30 +118,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
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:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -202,10 +162,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_secure_storage_windows
|
||||
sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1"
|
||||
sha256: "3b7c8e068875dfd46719ff57c90d8c459c87f2302ed6b00ff006b3c9fcad1613"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.2.2"
|
||||
version: "4.1.0"
|
||||
flutter_test:
|
||||
dependency: "direct dev"
|
||||
description: flutter
|
||||
@@ -215,26 +175,26 @@ packages:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: flutter_vless
|
||||
sha256: aa66ea904e7593cc9b2f8f12c291a3a1f404377125d5cd9faa6399d444f511ab
|
||||
sha256: db242f7fe007d35b4d51c5bd5b895d816f141e4d4afc7038c3b6228c1c66dfb5
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.4"
|
||||
version: "1.1.5"
|
||||
flutter_vless_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_vless_android
|
||||
sha256: f2f2c81a410a7341ea05dfe3643b213530be44d6574bc91fa29c0bd417d97ac2
|
||||
sha256: "5e6fe73d3606ed8c73e87fac15efa7631e12ce18d39a4bd4e13b6c097c6d52b9"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.4"
|
||||
version: "1.1.5"
|
||||
flutter_vless_macos:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: flutter_vless_macos
|
||||
sha256: "096c21bd9728ee2856325c85f60bc7075dda44f99205dd0baa82e5a1223a62a2"
|
||||
sha256: "2651eda1ae75aff8d0acd74f3d38980c71e7629075eee7aa57e52897479f973f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.4"
|
||||
version: "1.1.5"
|
||||
flutter_vless_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -400,6 +360,22 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.0"
|
||||
package_info_plus:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: package_info_plus
|
||||
sha256: cb44f49b6e690fa766f023d5b22cac6b9affe741dd792b6ac7ad4fabe0d7b097
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.0.0"
|
||||
package_info_plus_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: package_info_plus_platform_interface
|
||||
sha256: "9bc8ba46813a4cc42c66ab781470711781940780fd8beddd0c3da62506d3a6c6"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.1"
|
||||
path:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -456,14 +432,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.0"
|
||||
petitparser:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: petitparser
|
||||
sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.0.2"
|
||||
platform:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -613,14 +581,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.11"
|
||||
timezone:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: timezone
|
||||
sha256: "2236ec079a174ce07434e89fcd3fcda430025eb7692244139a9cf54fdcf1fc7d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.9.4"
|
||||
typed_data:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -721,10 +681,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: web
|
||||
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
|
||||
sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
version: "0.5.1"
|
||||
webview_flutter:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -761,10 +721,10 @@ packages:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: win32
|
||||
sha256: ba6f4bba816c8d7e3c1580e170f3786d216951cc6b94babc3b814c08d2cb2738
|
||||
sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.3.0"
|
||||
version: "5.15.0"
|
||||
xdg_directories:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -773,14 +733,6 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
xml:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: xml
|
||||
sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "6.6.1"
|
||||
yaml:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -15,7 +15,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
|
||||
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
|
||||
# Read more about iOS versioning at
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
version: 1.0.6+10
|
||||
version: 3.3.4+30
|
||||
|
||||
environment:
|
||||
sdk: ">=3.0.0 <4.0.0"
|
||||
@@ -30,14 +30,14 @@ dependencies:
|
||||
google_fonts: ^6.1.0
|
||||
provider: ^6.1.1
|
||||
google_mobile_ads: ^4.0.0
|
||||
flutter_vless: 1.1.4
|
||||
flutter_vless: 1.1.5
|
||||
http: ^1.6.0
|
||||
shared_preferences: ^2.5.5
|
||||
url_launcher: ^6.3.2
|
||||
flutter_secure_storage: ^10.3.1
|
||||
uuid: ^4.5.3
|
||||
flutter_local_notifications: ^17.0.0
|
||||
path_provider: ^2.1.5
|
||||
package_info_plus: ^6.0.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -1,737 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Hivemind VPN Session Manager
|
||||
Manages VLESS Reality sessions via ad rewards — 60 min, throttle at 4 GB.
|
||||
Designed for Android-only clients.
|
||||
|
||||
=== TABLE OF CONTENTS ===========================================================
|
||||
Configuration — ad rewards, Reality constants, Xray paths
|
||||
State & Cache — sessions dict, stats failure counter
|
||||
Flask Routes — /admob/callback, /session/status, /session/stop
|
||||
Session Logic — _start_or_extend_session, _extend_session
|
||||
AdMob SSV Verification — Google ECDSA signature checks
|
||||
Management Loop — expiry + throttle watchdog (60 s tick)
|
||||
Low-Level Plumbing — add/remove users, Xray stats
|
||||
Entry Point — daemon thread + gunicorn bootstrap
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import time
|
||||
import subprocess
|
||||
import threading
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import requests
|
||||
import shlex
|
||||
import urllib.parse
|
||||
import uuid
|
||||
import base64
|
||||
from flask import Flask, request, jsonify
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.serialization import load_pem_public_key
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
|
||||
# ── Log buffer for TUI / remote monitoring ────────────────────────────────
|
||||
# Captures every print() into a ring buffer so the TUI dashboard can pull
|
||||
# recent log lines without SSH. /api/log returns the last 200 lines.
|
||||
import sys
|
||||
from collections import deque
|
||||
|
||||
_log_buffer = deque(maxlen=200)
|
||||
|
||||
class _TeeStdout:
|
||||
def __init__(self, original):
|
||||
self.original = original
|
||||
def write(self, s):
|
||||
self.original.write(s)
|
||||
self.original.flush()
|
||||
for line in s.splitlines():
|
||||
stripped = line.rstrip()
|
||||
if stripped:
|
||||
_log_buffer.append(stripped)
|
||||
def flush(self):
|
||||
self.original.flush()
|
||||
|
||||
sys.stdout = _TeeStdout(sys.stdout)
|
||||
|
||||
|
||||
def _is_valid_device_id(device_id):
|
||||
"""Validate that device_id is a well-formed UUID (Flutter uuid.v4() format).
|
||||
|
||||
Rejects empty strings, non-UUID garbage, and oversized payloads
|
||||
before they reach the session dict or Xray config.
|
||||
"""
|
||||
if not isinstance(device_id, str):
|
||||
return False
|
||||
if len(device_id) > 64:
|
||||
return False
|
||||
try:
|
||||
uuid.UUID(device_id)
|
||||
return True
|
||||
except (ValueError, AttributeError):
|
||||
return False
|
||||
|
||||
|
||||
def _atomic_write_json(path, data):
|
||||
"""Write JSON to path atomically (temp file + rename).
|
||||
|
||||
Prevents Xray from reading a half-written config file during hot-reload.
|
||||
"""
|
||||
tmpfd, tmppath = tempfile.mkstemp(dir=os.path.dirname(path), suffix='.tmp')
|
||||
try:
|
||||
with os.fdopen(tmpfd, 'w') as f:
|
||||
json.dump(data, f, indent=2)
|
||||
os.replace(tmppath, path)
|
||||
except Exception:
|
||||
try:
|
||||
os.unlink(tmppath)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
# ==============================================================================
|
||||
# CONFIGURATION
|
||||
# ==============================================================================
|
||||
CHECK_INTERVAL_SECONDS = 60 # Checking every 1 minute is extremely safe and uses 0% CPU.
|
||||
|
||||
# Main Ad Rewards
|
||||
MAIN_AD_MINUTES = 60
|
||||
|
||||
# Support Ad Rewards (top-up)
|
||||
SUPPORT_AD_MINUTES = 30
|
||||
|
||||
# ── Reality — returned to app in /session/status ────────────────────────
|
||||
REALITY_SNI = "www.microsoft.com"
|
||||
VLESS_SERVER_IP = "204.168.246.88"
|
||||
VLESS_REALITY_PORT = 8443
|
||||
REALITY_PUBLIC_KEY = "GENERATE_ME_WITH_xray_x25519"
|
||||
REALITY_SHORT_ID = "abc123"
|
||||
|
||||
# ── Persistent swarm total (survives restarts) ──────────────────────────
|
||||
SWARM_TOTAL_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
"swarm_total.json")
|
||||
_persistent_total_gb = 0.0
|
||||
REALITY_FINGERPRINT = "chrome"
|
||||
|
||||
# ── Xray paths ───────────────────────────────────────────────────────────
|
||||
XRAY_CONFIG = "/usr/local/etc/xray/config.json"
|
||||
XRAY_API = "http://127.0.0.1:10085"
|
||||
VLESS_REALITY_TAG = "vless-reality"
|
||||
VLESS_REALITY_THROTTLED_TAG = "vless-reality-throttled"
|
||||
|
||||
THROTTLE_BYTES = 4 * 1024 * 1024 * 1024 # 4 GB
|
||||
|
||||
# AdMob SSV verification toggle
|
||||
# True = dev mode, accept any callback (no signature check)
|
||||
# False = prod mode, enforce Google ECDSA signature verification
|
||||
#
|
||||
# ⚠️ Set to False AFTER Google Play verifies your AdMob implementation is
|
||||
# working correctly with real rewarded ads. Until then, keep True so
|
||||
# the debug fake-callback path in the Flutter app still functions.
|
||||
ADMOB_BYPASS = True
|
||||
|
||||
def _load_persistent_total():
|
||||
"""Read the running total GB from disk. Returns 0.0 if file missing/corrupt."""
|
||||
try:
|
||||
with open(SWARM_TOTAL_FILE, 'r') as f:
|
||||
data = json.load(f)
|
||||
return float(data.get("total_gb", 0.0))
|
||||
except Exception:
|
||||
return 0.0
|
||||
|
||||
|
||||
def _save_persistent_total():
|
||||
"""Write the running total GB to disk atomically."""
|
||||
_atomic_write_json(SWARM_TOTAL_FILE, {"total_gb": _persistent_total_gb})
|
||||
|
||||
|
||||
# Load at module init — survives Hivemind restarts.
|
||||
_persistent_total_gb = _load_persistent_total()
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# STATE & CACHE
|
||||
# ==============================================================================
|
||||
sessions_lock = threading.Lock()
|
||||
|
||||
# Consecutive Xray stats API failures — reset to 0 on first success.
|
||||
# Used to rate-limit log spam when the stats endpoint is unreachable.
|
||||
_xray_stats_failures = 0
|
||||
|
||||
active_sessions = {}
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# FLASK ROUTES (API surface — what the outside world sees)
|
||||
# ==============================================================================
|
||||
|
||||
@app.route('/api/admob/callback', methods=['GET'])
|
||||
def admob_callback():
|
||||
"""
|
||||
Google AdMob SSV callback — called server-to-server when a rewarded ad completes.
|
||||
The Android client never touches this endpoint; Google calls it directly.
|
||||
|
||||
custom_data (JSON, set by the app before showing the ad):
|
||||
{ "device_id": "...", "nonce": "..." }
|
||||
"""
|
||||
try:
|
||||
if ADMOB_BYPASS:
|
||||
# ── DEV: accept any callback without signature verification ──
|
||||
custom_data_str = request.args.get('custom_data')
|
||||
if not custom_data_str:
|
||||
return "OK", 200
|
||||
else:
|
||||
# ── PROD: enforce Google ECDSA signature verification ────────
|
||||
signature = request.args.get('signature')
|
||||
key_id = request.args.get('key_id')
|
||||
custom_data_str = request.args.get('custom_data')
|
||||
|
||||
# Google sends a verification ping with signature+key_id but no custom_data
|
||||
if not custom_data_str:
|
||||
return "OK", 200
|
||||
|
||||
if not all([signature, key_id]):
|
||||
return "Missing parameters", 400
|
||||
|
||||
raw_qs = request.query_string.decode("utf-8")
|
||||
if not _verify_admob_signature(raw_qs, signature, key_id):
|
||||
print("[ADMOB] Rejected callback — invalid signature.")
|
||||
return "Forbidden", 403
|
||||
|
||||
try:
|
||||
custom_data = json.loads(custom_data_str)
|
||||
except (json.JSONDecodeError, TypeError) as e:
|
||||
print(f"[ADMOB] Malformed custom_data JSON: {e}")
|
||||
return "Invalid JSON in custom_data", 400
|
||||
|
||||
device_id = custom_data.get('device_id')
|
||||
|
||||
if not device_id:
|
||||
return "Invalid custom_data payload", 400
|
||||
if not _is_valid_device_id(device_id):
|
||||
print(f"[ADMOB] Rejected — invalid device_id: {str(device_id)[:32]}...")
|
||||
return "Invalid device_id", 400
|
||||
|
||||
nonce = custom_data.get('nonce', None)
|
||||
ad_type = custom_data.get('ad_type', 'main')
|
||||
|
||||
if ad_type == 'support':
|
||||
success, msg = _extend_session(device_id, nonce)
|
||||
else:
|
||||
success, msg = _start_or_extend_session(device_id, nonce)
|
||||
return ("OK", 200) if success else (msg, 500)
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ADMOB] SSV Error: {e}")
|
||||
return "Internal Error", 500
|
||||
|
||||
|
||||
@app.route('/api/health')
|
||||
def health():
|
||||
return jsonify({"ok": True})
|
||||
|
||||
|
||||
@app.route('/api/swarm')
|
||||
def swarm_status():
|
||||
"""Returns sorted drone list — consumed by TUI dashboards and CLI tools."""
|
||||
return jsonify(get_swarm_status())
|
||||
|
||||
|
||||
@app.route('/api/log')
|
||||
def log_tail():
|
||||
"""Returns recent log lines — consumed by TUI dashboards."""
|
||||
return jsonify(list(_log_buffer))
|
||||
|
||||
|
||||
@app.route('/api/session/status', methods=['GET'])
|
||||
def session_status():
|
||||
"""
|
||||
Query: ?device_id=esf-xxx
|
||||
Returns current VLESS session state so the app can connect.
|
||||
"""
|
||||
device_id = request.args.get('device_id')
|
||||
if not device_id:
|
||||
return jsonify({"error": "Missing query parameter: device_id"}), 400
|
||||
if not _is_valid_device_id(device_id):
|
||||
return jsonify({"error": "Invalid device_id — expected UUID"}), 400
|
||||
|
||||
with sessions_lock:
|
||||
session = active_sessions.get(device_id)
|
||||
|
||||
if not session:
|
||||
return jsonify({"active": False, "message": "No session found."}), 200
|
||||
|
||||
stats = get_xray_stats()
|
||||
used_bytes = stats.get(device_id, {}).get("total_bytes", 0)
|
||||
remaining_secs = max(0, session["expires_at"] - time.time())
|
||||
|
||||
return jsonify({
|
||||
"active": remaining_secs > 0,
|
||||
"vless_uuid": session["vless_uuid"],
|
||||
"vless_ip": VLESS_SERVER_IP,
|
||||
# NOTE: assumes throttled port = normal port + 1. If you change the
|
||||
# throttled port in xray_config_reality.json, update this logic too.
|
||||
"vless_port": VLESS_REALITY_PORT + 1 if session.get("throttled") else VLESS_REALITY_PORT,
|
||||
"reality_pbk": REALITY_PUBLIC_KEY,
|
||||
"reality_sid": REALITY_SHORT_ID,
|
||||
"reality_sni": REALITY_SNI,
|
||||
"reality_fp": REALITY_FINGERPRINT,
|
||||
"expires_in_seconds": int(remaining_secs),
|
||||
"used_bytes": used_bytes,
|
||||
"nonce": session.get("nonce", ""),
|
||||
"is_throttled": session.get("throttled", False),
|
||||
})
|
||||
|
||||
|
||||
@app.route('/api/session/stop', methods=['POST'])
|
||||
def session_stop():
|
||||
"""Allows the app to explicitly tear down its session on disconnect."""
|
||||
data = request.get_json(silent=True)
|
||||
device_id = data.get('device_id') if data else None
|
||||
|
||||
if not device_id:
|
||||
return jsonify({"error": "Missing device_id"}), 400
|
||||
if not _is_valid_device_id(device_id):
|
||||
return jsonify({"error": "Invalid device_id — expected UUID"}), 400
|
||||
|
||||
if device_id:
|
||||
with sessions_lock:
|
||||
session = active_sessions.pop(device_id, None)
|
||||
# Lock released — file I/O and subprocess happen outside.
|
||||
if session:
|
||||
# Add final bytes to persistent odometer.
|
||||
stats = get_xray_stats()
|
||||
used = stats.get(device_id, {}).get("total_bytes", 0)
|
||||
if used > 0:
|
||||
global _persistent_total_gb
|
||||
_persistent_total_gb += used / 1_000_000_000
|
||||
_save_persistent_total()
|
||||
remove_vless_client(device_id)
|
||||
print(f"[API] Explicit stop for {device_id}.")
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# SESSION LOGIC
|
||||
# ==============================================================================
|
||||
|
||||
def _start_or_extend_session(device_id, nonce=None):
|
||||
"""Provision a new VLESS session (or replace an existing one).
|
||||
|
||||
nonce -- client-generated random token; stored in session and echoed
|
||||
back in /session/status so the client can reject stale sessions.
|
||||
"""
|
||||
now = time.time()
|
||||
|
||||
# ── Phase 1: update in-memory state under lock ────────────────────
|
||||
xray_action = None # ("add", uuid) | ("replace", uuid)
|
||||
|
||||
with sessions_lock:
|
||||
existing = active_sessions.get(device_id)
|
||||
vless_uuid = str(uuid.uuid4())
|
||||
|
||||
active_sessions[device_id] = {
|
||||
"vless_uuid": vless_uuid,
|
||||
"expires_at": now + (MAIN_AD_MINUTES * 60),
|
||||
"nonce": nonce,
|
||||
"throttled": False,
|
||||
"_created_at": now,
|
||||
"_prev_bytes": 0,
|
||||
}
|
||||
|
||||
if existing:
|
||||
xray_action = ("replace", vless_uuid)
|
||||
else:
|
||||
xray_action = ("add", vless_uuid)
|
||||
|
||||
print(f"[SESSION] Session started for {device_id} (UUID: {vless_uuid[:8]}...).")
|
||||
|
||||
# ── Phase 2: Xray file I/O + subprocess OUTSIDE the lock ──────────
|
||||
op, arg = xray_action[0], xray_action[1]
|
||||
if op == "replace":
|
||||
remove_vless_client(device_id)
|
||||
add_vless_client(arg, device_id, inbound_tag=VLESS_REALITY_TAG)
|
||||
return True, "Session active."
|
||||
elif op == "add":
|
||||
add_vless_client(arg, device_id, inbound_tag=VLESS_REALITY_TAG)
|
||||
return True, "Session active."
|
||||
else:
|
||||
raise RuntimeError(
|
||||
f"BUG: _start_or_extend_session got unexpected xray_action op={op!r}. "
|
||||
f"Expected one of: replace, add. "
|
||||
f"This is a code bug — add the new op to the if-chain."
|
||||
)
|
||||
|
||||
|
||||
def _extend_session(device_id, nonce=None):
|
||||
"""Top-up an EXISTING session — adds time without replacing the UUID.
|
||||
|
||||
Used by the 'Support us' rewarded ad. Does NOT touch the throttle state
|
||||
or move the user between inbounds.
|
||||
"""
|
||||
with sessions_lock:
|
||||
session = active_sessions.get(device_id)
|
||||
if not session:
|
||||
print(f"[SESSION] Extend failed — no active session for {device_id}.")
|
||||
return False, "No active session to extend"
|
||||
|
||||
session["expires_at"] += SUPPORT_AD_MINUTES * 60
|
||||
session["nonce"] = nonce
|
||||
|
||||
print(f"[SESSION] Extended for {device_id}: +{SUPPORT_AD_MINUTES} min")
|
||||
|
||||
return True, "Session extended"
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# ADMOB SERVER-TO-SERVER (SSV) VERIFICATION
|
||||
# ==============================================================================
|
||||
ADMOB_KEYS_URL = "https://www.gstatic.com/admob/reward/verifier-keys.json"
|
||||
|
||||
# Cache: { key_id_str: EllipticCurvePublicKey }
|
||||
# Refreshed at most once every 24 hours so we don't hammer Google's CDN.
|
||||
_admob_key_cache = {}
|
||||
_admob_keys_fetched_at = 0.0
|
||||
_ADMOB_KEY_TTL = 86400 # seconds
|
||||
|
||||
|
||||
def _get_admob_public_key(key_id: str):
|
||||
"""
|
||||
Returns the Google ECDSA public-key object for the given key_id.
|
||||
Fetches and caches the key list from gstatic; refreshes every 24h.
|
||||
Returns None if the key_id is unknown.
|
||||
"""
|
||||
global _admob_key_cache, _admob_keys_fetched_at
|
||||
|
||||
now = time.time()
|
||||
if now - _admob_keys_fetched_at > _ADMOB_KEY_TTL or not _admob_key_cache:
|
||||
try:
|
||||
resp = requests.get(ADMOB_KEYS_URL, timeout=5)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
|
||||
new_cache = {}
|
||||
for entry in data.get("keys", []):
|
||||
kid = str(entry["keyId"])
|
||||
pem = entry["pem"].encode()
|
||||
new_cache[kid] = load_pem_public_key(pem)
|
||||
|
||||
_admob_key_cache = new_cache
|
||||
_admob_keys_fetched_at = now
|
||||
print(f"[ADMOB] Refreshed {len(new_cache)} public key(s) from Google.")
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ADMOB] WARNING: Could not refresh public keys: {e}")
|
||||
# Fall through with stale cache rather than rejecting all valid callbacks
|
||||
|
||||
return _admob_key_cache.get(key_id)
|
||||
|
||||
|
||||
def _verify_admob_signature(raw_query_string: str, signature_b64url: str, key_id: str) -> bool:
|
||||
"""
|
||||
Verifies an AdMob SSV ECDSA-SHA256 signature.
|
||||
Google signs all query params EXCEPT 'signature' and 'key_id', in original order.
|
||||
"""
|
||||
try:
|
||||
public_key = _get_admob_public_key(key_id)
|
||||
if not public_key:
|
||||
print("[ADMOB] Unknown key_id — rejecting callback.")
|
||||
return False
|
||||
|
||||
# Reconstruct the signed payload by stripping signature + key_id from raw qs
|
||||
parsed = urllib.parse.parse_qs(raw_query_string, keep_blank_values=True)
|
||||
|
||||
# Google signs query params in the exact order they appear in the URL.
|
||||
# Use the raw string to preserve ordering — parse_qs loses it.
|
||||
ordered_pairs = []
|
||||
for pair in raw_query_string.split('&'):
|
||||
if '=' not in pair:
|
||||
continue
|
||||
k, v = pair.split('=', 1)
|
||||
if k in ('signature', 'key_id'):
|
||||
continue
|
||||
ordered_pairs.append(f"{k}={v}")
|
||||
payload = '&'.join(ordered_pairs).encode('utf-8')
|
||||
|
||||
# Google uses URL-safe base64 (no padding) for the signature
|
||||
sig_bytes = base64.urlsafe_b64decode(signature_b64url + '==')
|
||||
|
||||
public_key.verify(
|
||||
sig_bytes,
|
||||
payload,
|
||||
ec.ECDSA(hashes.SHA256())
|
||||
)
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ADMOB] Signature verification failed: {e}")
|
||||
return False
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# MANAGEMENT LOOP (The Hivemind — expiry + throttle watchdog)
|
||||
# ==============================================================================
|
||||
def management_loop():
|
||||
global _persistent_total_gb
|
||||
print(f"[HIVEMIND] Started. Tick every {CHECK_INTERVAL_SECONDS}s.")
|
||||
|
||||
while True:
|
||||
try:
|
||||
stats = get_xray_stats()
|
||||
now = time.time()
|
||||
|
||||
with sessions_lock:
|
||||
to_remove = []
|
||||
to_throttle_add = []
|
||||
to_throttle_cleanup = []
|
||||
|
||||
for device_id, session in list(active_sessions.items()):
|
||||
|
||||
if now > session["expires_at"]:
|
||||
print(f"[HIVEMIND] Session expired for {device_id}.")
|
||||
to_remove.append(device_id)
|
||||
continue
|
||||
|
||||
used_bytes = stats.get(device_id, {}).get("total_bytes", 0)
|
||||
session["_prev_bytes"] = used_bytes
|
||||
|
||||
just_throttled = False
|
||||
if used_bytes > THROTTLE_BYTES and not session.get("throttled", False):
|
||||
print(f"[HIVEMIND] Throttling {device_id} ({used_bytes/1e9:.2f} GB used).")
|
||||
session["throttled"] = True
|
||||
just_throttled = True
|
||||
to_throttle_add.append((device_id, session["vless_uuid"]))
|
||||
|
||||
if (session.get("throttled") and not just_throttled
|
||||
and not session.get("_cleaned_normal")):
|
||||
to_throttle_cleanup.append(device_id)
|
||||
session["_cleaned_normal"] = True
|
||||
|
||||
for device_id in to_remove:
|
||||
# Add final used bytes to the persistent odometer before culling.
|
||||
used = stats.get(device_id, {}).get("total_bytes", 0)
|
||||
if used > 0:
|
||||
_persistent_total_gb += used / 1_000_000_000
|
||||
_save_persistent_total()
|
||||
del active_sessions[device_id]
|
||||
|
||||
for device_id in to_remove:
|
||||
remove_vless_client(device_id)
|
||||
|
||||
for device_id, uuid in to_throttle_add:
|
||||
add_vless_client(uuid, device_id, level=1, inbound_tag=VLESS_REALITY_THROTTLED_TAG)
|
||||
|
||||
for device_id in to_throttle_cleanup:
|
||||
remove_vless_client_from(device_id, VLESS_REALITY_TAG)
|
||||
|
||||
except Exception as e:
|
||||
print(f"[HIVEMIND] Unhandled error: {e}")
|
||||
|
||||
time.sleep(CHECK_INTERVAL_SECONDS)
|
||||
|
||||
|
||||
# ##############################################################################
|
||||
# SWARM INTELLIGENCE (drone status — sorted data for TUI / API consumers)
|
||||
# ##############################################################################
|
||||
# get_swarm_status() returns a list of dicts sorted by GB used (highest first).
|
||||
# Callers (CLI tools, TUI dashboards, /api/swarm endpoint) consume this.
|
||||
# It snapshots active_sessions under lock and reads Xray stats — no side effects.
|
||||
# ##############################################################################
|
||||
|
||||
def get_swarm_status():
|
||||
"""Return sorted drone list + aggregate totals for external monitoring.
|
||||
|
||||
Returns a dict:
|
||||
{
|
||||
"drones": [ {...}, {...}, ... ], # sorted by gb descending
|
||||
"swarm_gb": 7.3, # total GB across all drones
|
||||
"active_count": 3, # sessions still alive
|
||||
}
|
||||
|
||||
Each drone dict:
|
||||
{
|
||||
"id": "a1b2c3d4", # first 8 chars of device_id
|
||||
"uptime_min": 23, # minutes since session created
|
||||
"gb": 2.14, # data used (GB, 2 decimal places)
|
||||
"throttled": false, # over quota?
|
||||
"active": true, # had traffic in the last tick?
|
||||
"remaining_min": 37, # minutes until expiry
|
||||
}
|
||||
"""
|
||||
now = time.time()
|
||||
stats = get_xray_stats()
|
||||
|
||||
with sessions_lock:
|
||||
drones = []
|
||||
for device_id, session in active_sessions.items():
|
||||
used_bytes = stats.get(device_id, {}).get("total_bytes", 0)
|
||||
gb = round(used_bytes / 1_000_000_000, 2)
|
||||
uptime_min = int((now - session.get("_created_at", session.get("expires_at", now) - MAIN_AD_MINUTES * 60)) / 60)
|
||||
remaining_min = max(0, int((session["expires_at"] - now) / 60))
|
||||
prev_bytes = session.get("_prev_bytes", 0)
|
||||
active = used_bytes > prev_bytes
|
||||
|
||||
drones.append({
|
||||
"id": device_id[:8],
|
||||
"uptime_min": max(0, uptime_min),
|
||||
"gb": gb,
|
||||
"throttled": session.get("throttled", False),
|
||||
"active": active,
|
||||
"remaining_min": remaining_min,
|
||||
})
|
||||
|
||||
# Sort: highest data usage first — abusers float to the top.
|
||||
drones.sort(key=lambda d: d["gb"], reverse=True)
|
||||
|
||||
swarm_gb = round(sum(d["gb"] for d in drones), 2)
|
||||
|
||||
return {
|
||||
"drones": drones,
|
||||
"swarm_gb": swarm_gb,
|
||||
"total_gb": round(_persistent_total_gb + swarm_gb, 2),
|
||||
"active_count": len(drones),
|
||||
}
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# LOW-LEVEL PLUMBING (Xray client management + stats)
|
||||
# ==============================================================================
|
||||
|
||||
def run_cmd(cmd, ignore_errors=False):
|
||||
"""Executes a shell command directly on the host."""
|
||||
args = shlex.split(cmd)
|
||||
try:
|
||||
result = subprocess.run(
|
||||
args, shell=False, check=not ignore_errors,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
|
||||
)
|
||||
return result.stdout.strip()
|
||||
except FileNotFoundError:
|
||||
print(f"[CMD FAIL] executable not found: {args[0]}")
|
||||
return None
|
||||
except subprocess.CalledProcessError as e:
|
||||
if not ignore_errors:
|
||||
print(f"[CMD FAIL] {cmd}\n stderr: {e.stderr.strip()}")
|
||||
return None
|
||||
except OSError as e:
|
||||
print(f"[CMD FAIL] {cmd}\n os error: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def add_vless_client(uuid, email, level=0, inbound_tag=VLESS_REALITY_TAG):
|
||||
"""Add a client UUID to the Xray inbound config and hot-reload.
|
||||
|
||||
level -- Xray policy level for bandwidth limits: 0 = default.
|
||||
inbound_tag -- which inbound to add the client to (default: VLESS_REALITY_TAG).
|
||||
"""
|
||||
with open(XRAY_CONFIG, 'r') as f:
|
||||
config = json.load(f)
|
||||
|
||||
for inbound in config["inbounds"]:
|
||||
if inbound.get("tag") == inbound_tag:
|
||||
inbound["settings"]["clients"].append({
|
||||
"id": uuid,
|
||||
"email": email,
|
||||
"level": level
|
||||
})
|
||||
break
|
||||
|
||||
_atomic_write_json(XRAY_CONFIG, config)
|
||||
run_cmd("xray api adi --server=127.0.0.1:10085")
|
||||
print(f"[VLESS] User added to {inbound_tag}: {email[:16]}...")
|
||||
|
||||
|
||||
def remove_vless_client(email):
|
||||
"""Remove a client from ALL VLESS inbounds and hot-reload."""
|
||||
with open(XRAY_CONFIG, 'r') as f:
|
||||
config = json.load(f)
|
||||
|
||||
for inbound in config["inbounds"]:
|
||||
if inbound.get("tag") in (VLESS_REALITY_TAG, VLESS_REALITY_THROTTLED_TAG):
|
||||
clients = inbound["settings"]["clients"]
|
||||
inbound["settings"]["clients"] = [
|
||||
c for c in clients if c.get("email") != email
|
||||
]
|
||||
|
||||
_atomic_write_json(XRAY_CONFIG, config)
|
||||
run_cmd("xray api adi --server=127.0.0.1:10085")
|
||||
print(f"[VLESS] User removed: {email[:16]}...")
|
||||
|
||||
|
||||
def remove_vless_client_from(email, inbound_tag):
|
||||
"""Remove a client from one specific inbound and hot-reload."""
|
||||
with open(XRAY_CONFIG, 'r') as f:
|
||||
config = json.load(f)
|
||||
|
||||
for inbound in config["inbounds"]:
|
||||
if inbound.get("tag") == inbound_tag:
|
||||
clients = inbound["settings"]["clients"]
|
||||
inbound["settings"]["clients"] = [
|
||||
c for c in clients if c.get("email") != email
|
||||
]
|
||||
break
|
||||
|
||||
_atomic_write_json(XRAY_CONFIG, config)
|
||||
run_cmd("xray api adi --server=127.0.0.1:10085")
|
||||
print(f"[VLESS] User removed from {inbound_tag}: {email[:16]}...")
|
||||
|
||||
|
||||
def get_xray_stats():
|
||||
"""Query Xray stats API for per-user upload+download bytes.
|
||||
|
||||
Returns: { "device_id": {"total_bytes": 12345}, ... }
|
||||
"""
|
||||
global _xray_stats_failures
|
||||
|
||||
try:
|
||||
resp = requests.get(
|
||||
f"{XRAY_API}/stats/query",
|
||||
json={"pattern": "", "reset": False},
|
||||
timeout=5
|
||||
)
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
# Rate-limit log spam: warn on first failure, then every 10th.
|
||||
_xray_stats_failures += 1
|
||||
if _xray_stats_failures == 1:
|
||||
print(f"[XRAY_STATS] WARNING: Cannot reach Xray stats API: {e}")
|
||||
elif _xray_stats_failures % 10 == 0:
|
||||
print(f"[XRAY_STATS] ERROR: {_xray_stats_failures} consecutive failures. "
|
||||
f"Quota enforcement is NOT running. Last error: {e}")
|
||||
return {}
|
||||
|
||||
# Success — reset the failure counter.
|
||||
if _xray_stats_failures > 0:
|
||||
print(f"[XRAY_STATS] Recovered after {_xray_stats_failures} failure(s).")
|
||||
_xray_stats_failures = 0
|
||||
|
||||
stats = {}
|
||||
for entry in data.get("stat", []):
|
||||
name = entry.get("name", "")
|
||||
value = int(entry.get("value", 0))
|
||||
|
||||
# Xray stats names look like: "user>>>email>>>traffic>>>uplink"
|
||||
if ">>>traffic>>>" in name:
|
||||
parts = name.split(">>>")
|
||||
email = parts[1] if len(parts) > 1 else None
|
||||
if email and email != "api":
|
||||
if email not in stats:
|
||||
stats[email] = {"total_bytes": 0}
|
||||
stats[email]["total_bytes"] += value
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# ENTRY POINT
|
||||
# ==============================================================================
|
||||
# Start management daemon at module load (gunicorn-safe, runs once per process)
|
||||
_daemon_thread = threading.Thread(target=management_loop, daemon=True)
|
||||
_daemon_thread.start()
|
||||
|
||||
if __name__ == '__main__':
|
||||
# When running directly with Flask, the before_request hook handles it
|
||||
app.run(host='0.0.0.0', port=5000)
|
||||
@@ -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');
|
||||
}
|
||||