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

No files matched your search

+83 -51
View File
@@ -1,37 +1,22 @@
# Miscellaneous
*.class
*.log
*.pyc
# =============================================================================
# ReVoltVPN — .gitignore
# =============================================================================
# ── OS & Editor ────────────────────────────────────────────────────────────
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
.java-version
# 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/
# Python cache & User files
TECHNICAL_DEBT.md
RUNNING.md
# ── Python ─────────────────────────────────────────────────────────────────
__pycache__/
*.pyc
# App Config (Hide real IPs/IDs from GitHub)
lib/logic/app_config.dart
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
# ── Flutter / Dart ─────────────────────────────────────────────────────────
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
@@ -42,8 +27,10 @@ build/
local_packages/*/build/
local_packages/*/.dart_tool/
*.dart_tool/
**/doc/api/
**/ios/Flutter/.last_build_id
# Android related
# ── Android ────────────────────────────────────────────────────────────────
**/android/**/gradle-wrapper.jar
**/android/.gradle
**/android/captures/
@@ -54,37 +41,82 @@ local_packages/*/.dart_tool/
**/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
# Secrets
# ── Secrets & Keystores ───────────────────────────────────────────────────
*.keystore
*.jks
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
# App config (contains real IPs/IDs — use example as template)
lib/logic/app_config.dart
# ── Hivemind server (deployed separately, not part of the Flutter repo) ───
hivemind/
server_hivemind_5_0.py
swarm_watch.py
nginx_hivemind_reality.conf
nginx_hivemind_reality.conf
nginx_hivemind_reality.conf
xray_config_reality.json
swarm_total.json
# ── Internal docs (not for public repo) ────────────────────────────────────
AGENTS.md
FRONTEND_POLISH_REVIEW.md
RUNNING.md
SERVER_DEPLOYMENT.md
SERVER_NOTES.md
SERVER_SETUP.md
REALITY_MIGRATION_PLAN.md
SECURITY_HARDENING.md
VLESS_APP_CONTRACT.md
UI_POSITIONING.md
# ── Technical debt & security audits ───────────────────────────────────────
technical_debt_*.md
technical_debt_*_answer.md
# ── Backups & reference files ──────────────────────────────────────────────
backups/
backup/
hivemind_backup.py
server full picture.txt
server_full_picture_2.txt
00-FULL-REPORT.md
XRAY_CONFIG_REFERENCE.md
# ── Logs & temp ────────────────────────────────────────────────────────────
*.log
*.class
server_picture.sh
# ── AI assistant ───────────────────────────────────────────────────────────
.codewhale/
# ── Dev tool config ────────────────────────────────────────────────────────
devtools_options.yaml
lib/logic/backup/
scraped
scraped.zip
hivemind.zip
XRAY_AUDIT.md
TECHNICAL_DEBT.md
DOCUMENTATION-ARCHITECTURE-V2.md
config.json
RESILIENCE_REVIEW.md
CONFIG_REVIEW.md
SERVER_SELECTION.md
THREAT_MODEL.md
BUSINESS_MODEL.md
DPI_FINGERPRINT_ANALYSIS.md
CODE_FINGERPRINT_AUDIT.md
CONFERENCE_PREP.md
CONVERSION_CHECKLIST.md
HIVEMIND_INTERNALS.md
#why are you even looking at this file? it's a secret. go away.
SERVER_ARCHITECTURE.md
turbovpn_play.html
supervpn_play.html
hetzner*
DEPLOYMENT_REPORT_FINAL.md
+145
View File
@@ -0,0 +1,145 @@
# Changelog
All notable changes to the ReVoltVPN Flutter app.
Versions follow [semver](https://semver.org/): MAJOR.MINOR.PATCH
---
## [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
+83
View File
@@ -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
```
+686 -17
View File
@@ -1,21 +1,690 @@
MIT License
ReVoltVPN — Copyright (C) 2026 esef
Copyright (c) 2026 esef
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Permission is hereby granted, free of charge, to any person obtaining a copy
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>.
+27 -14
View File
@@ -1,21 +1,34 @@
Privacy Policy
Last updated: July 2025
# Privacy Policy
**Last updated:** August 2026
ReVoltVPN is a free VPN service built and operated by ReVolt Team.
What we collect
## 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 active session status and data usage for the current session only. Sessions last up to 1 hour, then expire. Session data is stored in memory and deleted when your session ends.
What we do not collect
## Operational logs
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.
We keep a short in-memory log buffer (last 200 lines) for debugging and server health monitoring. These logs include truncated device IDs (first 8 characters only), session start/stop events, and error messages. Logs never leave the server, are not retained after a server restart, and are only accessible to the server operator via local console. We also maintain an aggregate total of all data ever transferred (in GB) for capacity planning — this counter is not tied to any individual device.
## What we do not collect
- 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.
## Ads & Consent
Ads & Consent
ReVoltVPN uses Google AdMob to display rewarded video ads. On first launch, users in the European Economic Area (EEA) and United Kingdom are shown a consent dialog (provided by Google's User Messaging Platform) that lets them choose whether to allow personalized ads. This consent choice is stored on your device and can be changed at any time by reinstalling the app. Google may collect data as part of ad delivery. Please refer to Google's Privacy Policy for details.
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.
## Your traffic
Your internet traffic is routed through our server located in Finland. We do not inspect, log, or store your traffic. We only track total bytes transferred per session (for quota enforcement and blocking abusers) — no packet contents, no destination IPs, no DNS queries.
## Contact
If you have any questions, open an issue on the GitHub repository or join the Discord server.
+30 -26
View File
@@ -1,56 +1,60 @@
---
<p align="center">
<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 60 minutes 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 `www.github.com` TLS. To any DPI box, your tunnel looks like a browser visiting GitHub
- **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.*
---
+2 -2
View File
@@ -7,7 +7,7 @@ plugins {
}
android {
namespace = "com.revoltvpn.app"
namespace = "com.paladinvpn.app"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
@@ -34,7 +34,7 @@ android {
}
defaultConfig {
applicationId = "com.revoltvpn.app"
applicationId = "com.paladinvpn.app"
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
+3 -2
View File
@@ -14,11 +14,12 @@
</queries>
<application
android:label="REVOLT VPN"
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
@@ -1,4 +1,4 @@
package com.revoltvpn.app
package com.paladinvpn.app
import io.flutter.embedding.android.FlutterActivity
Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 172 KiB

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

+1 -1
View File
@@ -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>
-115
View File
@@ -1,115 +0,0 @@
// =============================================================================
// clock_display.dart — EDUCATIONAL REFERENCE (not used in production)
// =============================================================================
//
// This widget was the original combined timer + speed + syncing display.
// It was replaced by the separate TimerBox and SpeedBox widgets in the
// Reality-era UI refactor.
//
// What's worth studying here:
//
// 1. TEXT GLOW EFFECT — the yellow glow around the countdown timer:
// ```
// shadows: [Shadow(color: AppColors.accent50, blurRadius: 16)]
// ```
// This exact effect was ported to timer_box.dart and is what gives
// the countdown its signature pulsing-yellow look.
//
// 2. SYNCING PLACEHOLDER — conditional spinner + label when the first
// server poll hasn't returned yet. Shows "Syncing…" with a small
// CircularProgressIndicator instead of flashing 00:00:00.
//
// 3. COMBINED DISPLAY — clock + speed stacked in a Column inside a
// fixed 200×200 SizedBox. The modern UI split these into separate
// boxes for the stacked layout, but the stacking approach here is
// a good reference for compact combined displays.
//
// Kept in the repo for reference. Safe to delete if you're pruning.
// =============================================================================
// import 'package:flutter/material.dart';
// import 'package:provider/provider.dart';
// import 'package:revoltvpn/logic/app_colors.dart';
// import 'package:revoltvpn/logic/session_timer.dart';
// class ClockDisplay extends StatelessWidget {
// const ClockDisplay({super.key});
// @override
// Widget build(BuildContext context) {
// return Consumer<SessionTimer>(
// builder: (context, timer, _) {
// final bool showSyncing = !timer.hasSyncedOnce;
// return SizedBox(
// width: 200,
// height: 200,
// child: Stack(
// alignment: Alignment.center,
// children: [
// Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// if (showSyncing) ...[
// const SizedBox(
// width: 32,
// height: 32,
// child: CircularProgressIndicator(
// strokeWidth: 2,
// color: AppColors.accent50,
// ),
// ),
// const SizedBox(height: 10),
// const Text(
// 'Syncing…',
// style: TextStyle(
// fontSize: 16,
// fontWeight: FontWeight.w600,
// color: AppColors.accent60,
// letterSpacing: 1.5,
// ),
// ),
// ] else ...[
// Text(
// timer.formatted,
// style: const TextStyle(
// fontSize: 40,
// fontWeight: FontWeight.w800,
// color: AppColors.textWhite,
// letterSpacing: 2,
// shadows: [
// Shadow(
// color: AppColors.accent50,
// blurRadius: 16,
// ),
// ],
// ),
// ),
// const SizedBox(height: 6),
// Row(
// mainAxisSize: MainAxisSize.min,
// children: [
// const Icon(Icons.speed, color: AppColors.textDim, size: 14),
// const SizedBox(width: 4),
// Text(
// timer.currentSpeedKBps > 0.5
// ? '${timer.currentSpeedKBps.toStringAsFixed(1)} KB/s'
// : 'Idle',
// style: const TextStyle(
// fontSize: 12,
// color: AppColors.textDim,
// fontWeight: FontWeight.w500,
// ),
// ),
// ],
// ),
// ],
// ],
// ),
// ],
// ),
// );
// },
// );
// }
// }
+9 -7
View File
@@ -5,6 +5,7 @@ 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/screens/settings/in_settings/haptic.dart';
class ConnectButton extends StatefulWidget {
const ConnectButton({super.key});
@@ -56,8 +57,6 @@ class _ConnectButtonState extends State<ConnectButton>
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>();
@@ -65,8 +64,8 @@ class _ConnectButtonState extends State<ConnectButton>
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();
if (hapticEnabled) HapticFeedback.lightImpact();
return;
}
@@ -84,7 +83,10 @@ class _ConnectButtonState extends State<ConnectButton>
return;
}
final ok = await vpn.connect();
if (ok) timer.start();
if (ok) {
timer.start();
if (hapticEnabled) HapticFeedback.lightImpact();
}
} finally {
if (mounted) setState(() => _busy = false);
}
@@ -116,7 +118,7 @@ class _ConnectButtonState extends State<ConnectButton>
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,
@@ -138,7 +140,7 @@ class _ConnectButtonState extends State<ConnectButton>
),
)
: Padding(
padding: const EdgeInsets.all(14), // <-- CHANGE ME: brand.png padding from edge
padding: const EdgeInsets.all(14),
child: Image.asset('assets/brand.png', fit: BoxFit.contain),
),
);
+104
View File
@@ -0,0 +1,104 @@
// 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 your '
'account. We do not log or monitor the content of your '
'traffic. We do not share your data with third parties.'
'If you have more questions, visit our website.',
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'),
),
),
],
),
),
);
}
}
+235
View File
@@ -0,0 +1,235 @@
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));
_scheduleNext();
}
@override
void dispose() {
_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) return;
_bolt = LightningBolt.random(_random);
_ctrl.forward(from: 0.0);
if (_random.nextDouble() < widget.doubleChance) {
Future.delayed(const Duration(milliseconds: 120), () {
if (mounted) {
_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) 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;
}
+42 -51
View File
@@ -1,10 +1,18 @@
import 'dart:io';
import 'dart:ui' as ui;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class VpnNotificationManager {
static final FlutterLocalNotificationsPlugin _plugin =
FlutterLocalNotificationsPlugin();
static bool _initialized = false;
static String? _lastTimeLeft;
static String? _lastSpeedKbps;
// Android channels are immutable — bump this if settings change.
static const _channelId = 'revolt_vpn_v4';
static const _channelName = 'Revolt VPN';
static const _notifId = 888;
static Future<void> init() async {
if (_initialized) return;
@@ -15,7 +23,6 @@ class VpnNotificationManager {
await _plugin.initialize(initSettings);
// Request POST_NOTIFICATIONS permission on Android 13+
if (Platform.isAndroid) {
final androidPlugin = _plugin
.resolvePlatformSpecificImplementation<
@@ -26,77 +33,61 @@ class VpnNotificationManager {
_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;
_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,
final bodyText = 'Time: $timeLeft • $speedKbps';
final bigPictureStyle = BigPictureStyleInformation(
const DrawableResourceAndroidBitmap('notification_banner'),
largeIcon: const DrawableResourceAndroidBitmap('notification_icon'),
contentTitle: 'Revolt VPN',
summaryText: bodyText,
htmlFormatContentTitle: false,
htmlFormatSummaryText: false,
);
const notificationDetails = NotificationDetails(android: androidDetails);
final androidDetails = AndroidNotificationDetails(
_channelId,
_channelName,
channelDescription: 'Session timer and speed',
importance: Importance.low,
priority: Priority.low,
ongoing: true,
autoCancel: false,
playSound: false,
enableVibration: false,
showWhen: false,
visibility: NotificationVisibility.public,
usesChronometer: false,
category: AndroidNotificationCategory.service,
colorized: true,
color: const ui.Color(0xFF0D1117),
styleInformation: bigPictureStyle,
);
final details = NotificationDetails(android: androidDetails);
try {
await _plugin.show(
888, // Fixed ID — always updates the same notification
'REVOLT VPN Active',
'Time: $timeLeft • $speedKbps',
notificationDetails,
);
await _plugin.show(_notifId, _channelName, bodyText, details);
} 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.
}
await _plugin.show(_notifId, _channelName, bodyText, details);
} catch (_) {}
}
}
static Future<void> cancel() async {
if (!_initialized) return;
await _plugin.cancel(888);
await _plugin.cancel(_notifId);
}
}
+167
View File
@@ -0,0 +1,167 @@
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();
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));
}
_ticker = createTicker(_onTick)..start();
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
// 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);
d.y = -0.06 - _random.nextDouble() * 0.08;
}
}
setState(() {});
}
// Build
@override
Widget build(BuildContext context) {
if (!rainEnabled) return const SizedBox.shrink();
return CustomPaint(
painter: _RainPainter(
drops: _drops,
color: widget.color,
windDrift: widget.windDrift,
),
size: Size.infinite,
);
}
}
// ═══════════════════════════════════════════════════════════════════════════
// Drop model
// ═══════════════════════════════════════════════════════════════════════════
class _Drop {
double x;
double y;
double speed;
double length;
double opacity;
_Drop({
required this.x,
required this.y,
required this.speed,
required this.length,
required this.opacity,
});
/// Create a drop at a random position anywhere on screen.
factory _Drop.spawn(Random r, double minLen, double maxLen) {
return _Drop(
x: r.nextDouble(),
y: r.nextDouble(),
speed: 0.30 + r.nextDouble() * 0.55,
length: minLen + r.nextDouble() * (maxLen - minLen),
opacity: 0.05 + r.nextDouble() * 0.12,
);
}
/// Re-randomise all properties (call when recycling a drop to the top).
void spawn(Random r, double minLen, double maxLen) {
x = r.nextDouble();
speed = 0.30 + r.nextDouble() * 0.55;
length = minLen + r.nextDouble() * (maxLen - minLen);
opacity = 0.05 + r.nextDouble() * 0.12;
}
}
// ═══════════════════════════════════════════════════════════════════════════
// Painter
// ═══════════════════════════════════════════════════════════════════════════
class _RainPainter extends CustomPainter {
final List<_Drop> drops;
final Color color;
final double windDrift;
_RainPainter({
required this.drops,
required this.color,
required this.windDrift,
});
@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 = color.withAlpha((d.opacity * 255).round());
canvas.drawLine(Offset(sx, sy), Offset(ex, ey), paint);
}
}
@override
bool shouldRepaint(_RainPainter old) => true; // always animating
}
@@ -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,46 @@
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 void open(BuildContext context) {
Navigator.of(context).push(
PageRouteBuilder(
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,
);
},
),
);
}
@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,
);
}
}
+61 -5
View File
@@ -1,13 +1,42 @@
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 +113,39 @@ class SidebarDrawer extends StatelessWidget {
},
),
_Row(
icon: Icons.language,
label: 'Website',
onTap: () {
Navigator.of(context).pop();
WebsiteButton.launchWebsite();
},
),
_Row(
icon: Icons.settings,
label: 'Settings',
onTap: () {
Navigator.of(context).pop();
SettingsButton.open(context);
},
),
_Row(
icon: Icons.system_update_alt,
label: 'Check for updates',
onTap: () {
Navigator.of(context).pop();
Updater.check(context);
},
),
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),
),
),
],
+97 -38
View File
@@ -3,7 +3,19 @@ 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';
// ── lib/components/status_bar.dart ──────────────────────────────────────────
// Two-card layout at the bottom of the main screen.
//
// Top card: server location from ServerList provider (flag + city).
// Tappable → opens server selector. Always visible.
// Bottom card: connection status (health dot + label + lock icon).
//
// Separated into two rows — no more RenderFlex overflow and ready for
// multi-server picker.
class StatusBar extends StatelessWidget {
const StatusBar({super.key});
@@ -14,50 +26,97 @@ 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);
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
? (timer.hasSyncedOnce ? 'Online' : 'Syncing…')
: (isConnecting
? 'Connecting…'
: (vpn.serverReachable ? 'Ready' : 'Offline'));
// Read from the ServerList provider — the source of truth for
// which server is selected and what it looks like.
final server = context.watch<ServerList>().selected;
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,
// ── Server location ──────────────────────────────────────────
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(),
const SizedBox(height: 8),
// ── Server health dot (right) ────────────────────────────
OnlineDot(
isOnline: serverHealthy,
label: isConnected
? (timer.hasSyncedOnce ? 'Online' : 'Syncing…')
: (vpn.serverReachable ? 'Ready' : 'Offline'),
// ── Connection status ────────────────────────────────────────
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 (isConnected)
const Icon(Icons.lock,
color: AppColors.green50, size: 14),
],
),
),
],
),
+12 -8
View File
@@ -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,
),
]
: [],
),
),
);
+26 -24
View File
@@ -7,12 +7,7 @@ import 'package:revoltvpn/logic/crypto_service.dart';
import 'package:revoltvpn/logic/hivemind_service.dart';
import 'package:revoltvpn/logic/app_config.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 +27,9 @@ 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.
Future<bool> preloadAd() async {
if (!adsEnabled) return true;
// If already loaded, return instantly
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 +73,34 @@ 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
if (!_isAdLoaded || _rewardedAd == null) {
final loaded = await preloadAd();
if (!loaded || _rewardedAd == null) {
@@ -98,16 +109,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 +125,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 +132,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 +148,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);
}
+43 -17
View File
@@ -1,31 +1,57 @@
// =============================================================================
// 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
// ── Server ───────────────────────────────────────────────────────────
/// Your server's public IP. The VPN tunnel is pinned to this.
static const String serverIp = '0.0.0.0'; // ◄── REPLACE
static String get hivemindApiBase => 'https://$serverDomain/api';
/// API base — routed through the tunnel to Flask via Xray "api" outbound.
static const String hivemindApiBase = 'http://10.254.254.1:5000/api';
// ── Bootstrap (first-connect config fetch) ────────────────────────────
/// Hardcoded Reality config. App connects with this, fetches the real
/// per-session VLESS URL through the tunnel, then reconnects.
static String get bootstrapVlessUrl =>
'vless://$bootstrapUuid@$serverIp:8443'
'?security=reality&type=xhttp&path=/revolt'
'&pbk=$realityPbk&sni=www.github.com&sid=$realitySid&fp=chrome'
'#ReVoltVPN';
/// Generate with `xray uuid` on the server. Must match xray_config_reality.json.
static const String bootstrapUuid = '00000000-0000-0000-0000-000000000000'; // ◄── REPLACE
/// Server's Reality public key (from `xray x25519`).
static const String realityPbk = 'REPLACE_WITH_YOUR_PUBLIC_KEY';
/// Must be in xray_config_reality.json shortIds[].
static const String realitySid = 'abc123';
// ── Reality (VPN tunnel) ──────────────────────────────────────────────
// These are fallbacks — normally overridden by /session/status response.
static const String realitySni = 'www.microsoft.com';
static const String realityFp = 'chrome';
/// 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_USERNAME'; // ◄── REPLACE
static const String githubRepo = 'revoltvpn'; // ◄── REPLACE
/// 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
+99 -37
View File
@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
@@ -10,22 +11,84 @@ class HivemindService {
static String? _expectedNonce;
static int _currentCallId = 0;
/// Call this from disconnect to abort any in-progress polling.
static const _ua = 'Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36';
static Future<http.Response> directGet(Uri uri, {Duration timeout = const Duration(seconds: 5)}) {
return http.get(uri, headers: {'User-Agent': _ua}).timeout(timeout);
}
static Future<http.Response> directPost(Uri uri, String body, {Duration timeout = const Duration(seconds: 5)}) {
return http.post(uri, headers: {
'Content-Type': 'application/json',
'User-Agent': _ua,
}, body: body).timeout(timeout);
}
static Future<http.Response> proxyGet(Uri uri, {Duration timeout = const Duration(seconds: 5)}) {
return _proxyRequest('GET', uri, timeout: timeout);
}
static Future<http.Response> proxyPost(Uri uri, String body, {Duration timeout = const Duration(seconds: 5)}) {
return _proxyRequest('POST', uri, body: body, timeout: timeout);
}
static Future<http.Response> _proxyRequest(String method, Uri uri,
{String? body, Duration timeout = const Duration(seconds: 5)}) async {
final socket = await Socket.connect('127.0.0.1', 10808, timeout: timeout);
try {
final target = uri.toString();
final headers = <String, String>{
'Host': '${uri.host}:${uri.port}',
'User-Agent': _ua,
'Accept': '*/*',
'Connection': 'close',
};
if (body != null) {
headers['Content-Type'] = 'application/json';
headers['Content-Length'] = body.length.toString();
}
final reqBuf = StringBuffer();
reqBuf.write('$method $target HTTP/1.1\r\n');
headers.forEach((k, v) => reqBuf.write('$k: $v\r\n'));
reqBuf.write('\r\n');
if (body != null) reqBuf.write(body);
socket.write(reqBuf.toString());
await socket.flush();
final response = await socket.fold<String>(
'',
(prev, chunk) => prev + String.fromCharCodes(chunk),
).timeout(timeout);
final parts = response.split('\r\n\r\n');
if (parts.length < 2) throw Exception('Invalid proxy response');
final headerBlock = parts[0];
final respBody = parts.sublist(1).join('\r\n\r\n');
final headerLines = headerBlock.split('\r\n');
final statusParts = headerLines[0].split(' ');
final statusCode = int.parse(statusParts[1]);
return http.Response(respBody, statusCode);
} finally {
socket.destroy();
}
}
static void cancel() {
_currentCallId++; // bump — any running loop sees a stale ID and exits
_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();
@@ -34,25 +97,24 @@ class HivemindService {
_expectedNonce = nonce;
debugPrint('[HivemindService] Call #$callId — nonce: $nonce');
final url = Uri.parse('${AppConfig.hivemindApiBase}/session/status?device_id=$deviceId');
final url = _publicUrl('/session/status?device_id=$deviceId');
// ── AD BYPASS (debug only) ────────────────────────────────────────
if (kDebugMode && !skipAdBypass) {
if (!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));
final fakeUrl = _publicUrl(
'/admob/callback?signature=test&key_id=test&custom_data=${Uri.encodeComponent(customData)}');
await directGet(fakeUrl, timeout: const Duration(seconds: 8));
} catch (_) {}
}
final maxAttempts = quickReconnect ? 1 : 5;
const maxAttempts = 5;
for (int i = 1; i <= maxAttempts; i++) {
if (_currentCallId != callId) throw Exception('Cancelled');
onAttempt?.call(i, maxAttempts);
try {
final response = await http.get(url).timeout(const Duration(seconds: 5));
final response = await directGet(url);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
@@ -61,24 +123,24 @@ class HivemindService {
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 vlessIp = data['vless_ip'] ?? AppConfig.serverIp;
final vlessPort = data['vless_port'] ?? 443;
final pbk = data['reality_pbk'] ?? '';
final sid = data['reality_sid'] ?? '';
final sni = data['reality_sni'] ?? AppConfig.realitySni;
final sni = data['reality_sni'];
if (sni == null) throw Exception('Server did not provide reality_sni');
final fp = data['reality_fp'] ?? AppConfig.realityFp;
final xhttpPath = data['xhttp_path'] ?? AppConfig.vlessPath;
final vlessUrl = 'vless://$vlessUuid@$vlessIp:$vlessPort'
'?security=${AppConfig.vlessSecurity}'
'&type=${AppConfig.vlessType}'
'&flow=${AppConfig.vlessFlow}'
'&path=$xhttpPath'
'&pbk=${Uri.encodeComponent(pbk)}'
'&sni=${Uri.encodeComponent(sni)}'
'&sid=${Uri.encodeComponent(sid)}'
'&fp=${Uri.encodeComponent(fp)}'
'#ReVoltVPN';
'#Revolt VPN';
_expectedNonce = null;
return vlessUrl;
}
@@ -96,8 +158,8 @@ 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 url = Uri.parse('${AppConfig.hivemindApiPublic}/health');
final response = await directGet(url, timeout: const Duration(seconds: 3));
return response.statusCode == 200;
} catch (_) {
return false;
@@ -107,8 +169,8 @@ class HivemindService {
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));
final url = _tunnelUrl('/session/status?device_id=$deviceId');
final response = await proxyGet(url);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
return data['active'] == true;
@@ -117,15 +179,15 @@ class HivemindService {
return false;
}
static Future<void> disconnectAndCleanup() async {
final deviceId = await CryptoService.getDeviceId();
final url = Uri.parse('${AppConfig.hivemindApiBase}/session/stop');
try {
await http.post(
url,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'device_id': deviceId}),
).timeout(const Duration(seconds: 3));
} catch (_) {}
}
// Idle sessions are culled server-side by the management loop
// after 2 minutes of no /status polls (user disconnected).
static void disconnectAndCleanup() {}
// ── URL builders ──────────────────────────────────────────────────
static Uri _publicUrl(String path) =>
Uri.parse('${AppConfig.hivemindApiPublic}$path');
static Uri _tunnelUrl(String path) =>
Uri.parse('${AppConfig.hivemindApiBase}$path');
}
+69
View File
@@ -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 keys (public key,
// shortId, fingerprint) come from AppConfig — all servers share the same
// Reality keypair and bootstrap UUID (same operator, different locations).
//
// 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);
}
}
+38 -121
View File
@@ -1,11 +1,10 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:revoltvpn/logic/hivemind_service.dart';
import 'package:revoltvpn/logic/app_config.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
import 'package:revoltvpn/logic/crypto_service.dart';
import 'package:revoltvpn/components/notification.dart';
class SessionTimer extends ChangeNotifier {
Timer? _timer;
@@ -19,14 +18,9 @@ class SessionTimer extends ChangeNotifier {
bool _hasSyncedOnce = false;
int _consecutiveFailures = 0;
bool _isDisconnecting = false;
bool _userInitiatedStop = false;
int? _currentPort;
bool _portSwitchInProgress = false;
bool _syncInProgress = false;
static const int _maxConsecutiveFailures = 3;
static const int _maxOfflineSeconds = 120;
int _offlineSeconds = 0;
@@ -35,9 +29,6 @@ class SessionTimer extends ChangeNotifier {
int _lastUsedBytes = 0;
double _currentSpeedKBps = 0.0;
String _lastNotifTime = '';
String _lastNotifSpeed = '';
SessionTimer({required this.vpnConnection}) {
vpnConnection.addListener(_onVpnConnectionChanged);
}
@@ -57,11 +48,8 @@ class SessionTimer extends ChangeNotifier {
return '$h:$m:$s';
}
// Lifecycle
/// Fires whenever VpnConnection state changes.
void _onVpnConnectionChanged() {
// Restore timer if VPN was already running at app launch.
if (vpnConnection.status == VpnStatus.connected &&
!isRunning &&
vpnConnection.isStartupRestoration) {
@@ -69,21 +57,18 @@ class SessionTimer extends ChangeNotifier {
return;
}
// The underlying VLESS tunnel may briefly flap. If we weren't
// explicitly stopped by the user, resume where we left off.
// Resume after brief tunnel disconnection.
if (vpnConnection.status == VpnStatus.connected &&
!isRunning &&
!_userInitiatedStop &&
!_isDisconnecting &&
_hasSyncedOnce) {
debugPrint('[Timer] VPN reconnected after blip — resuming.');
_resumeTicking();
return;
}
if (vpnConnection.status == VpnStatus.disconnected && isRunning) {
_stopInternal();
if (vpnConnection.status == VpnStatus.disconnected && !_isDisconnecting) {
_doDisconnect('VPN tunnel dropped');
}
}
@@ -97,47 +82,32 @@ class SessionTimer extends ChangeNotifier {
_consecutiveFailures = 0;
_offlineSeconds = 0;
_isDisconnecting = false;
_userInitiatedStop = false;
_currentPort = null;
_portSwitchInProgress = 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();
}
void _tick(Timer t) {
// Decrement the local clock as long as we're not in a network blackout.
if (_isDisconnecting) return;
if (_hasSyncedOnce && _consecutiveFailures < _maxConsecutiveFailures) {
if (_remainingSeconds > 0) {
_remainingSeconds--;
}
}
// If the server has been unreachable for too long, kill the VPN.
// Don't let an orphaned tunnel keep running forever.
if (_consecutiveFailures >= _maxConsecutiveFailures) {
_offlineSeconds++;
if (_offlineSeconds >= _maxOfflineSeconds) {
debugPrint('[Timer] Offline for $_maxOfflineSeconds s — forcing disconnect.');
_forceDisconnect('Session lost — server unreachable');
_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');
_doDisconnect('Session expired');
return;
}
@@ -146,67 +116,53 @@ class SessionTimer extends ChangeNotifier {
_syncWithHivemind();
}
// Uses the locally-decremented time so the notification stays in sync
// with the in-app display, not gated behind the 5 s server poll.
if (_hasSyncedOnce) {
final speedText = _currentSpeedKBps > 0.5
? '${_currentSpeedKBps.toStringAsFixed(1)} KB/s'
: 'Idle';
if (formatted != _lastNotifTime || speedText != _lastNotifSpeed) {
_lastNotifTime = formatted;
_lastNotifSpeed = speedText;
VpnNotificationManager.showOrUpdateStatus(
timeLeft: formatted,
speedKbps: speedText,
);
}
}
notifyListeners();
}
void _forceDisconnect(String reason) {
if (_isDisconnecting) return; // Already tearing down
debugPrint('[Timer] $reason — forcing disconnect.');
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;
_hasSyncedOnce = false;
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();
}
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));
'${AppConfig.hivemindApiPublic}/session/status?device_id=$deviceId');
final response = await HivemindService.directGet(url);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
final bool active = data['active'] ?? false;
if (!active) {
// Server killed the session — tear down and wait for it.
stop();
await vpnConnection.disconnect();
await _doDisconnect('Server ended session');
return;
}
_remainingSeconds = data['expires_in_seconds'] ?? _remainingSeconds;
_usedBytes = data['used_bytes'] ?? _usedBytes;
final int deltaBytes = _usedBytes - _lastUsedBytes;
if (_hasSyncedOnce && deltaBytes > 0) {
_currentSpeedKBps = (deltaBytes / _pollIntervalSeconds) / 1000;
@@ -215,32 +171,15 @@ class SessionTimer extends ChangeNotifier {
}
_lastUsedBytes = _usedBytes;
// ── 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;
final capExhausted = data['cap_exhausted'] ?? false;
if (capExhausted) {
await _doDisconnect('Data cap reached');
return;
}
_currentPort = serverPort;
_consecutiveFailures = 0;
_offlineSeconds = 0;
_hasSyncedOnce = true;
notifyListeners();
} else {
_markSyncFailure();
@@ -248,29 +187,18 @@ class SessionTimer extends ChangeNotifier {
} catch (e) {
debugPrint('Hivemind sync error: $e');
_markSyncFailure();
} finally {
_syncInProgress = false;
}
}
void _markSyncFailure() {
_consecutiveFailures++;
if (_consecutiveFailures >= _maxConsecutiveFailures) {
notifyListeners(); // let the UI show "Reconnecting…"
notifyListeners();
}
}
void stop() {
_userInitiatedStop = true;
_isDisconnecting = true;
_timer?.cancel();
_timer = null;
_currentSpeedKBps = 0.0;
_hasSyncedOnce = false;
_remainingSeconds = 0;
notifyListeners();
}
void _resumeTicking() {
_timer?.cancel();
_timer = Timer.periodic(const Duration(seconds: 1), _tick);
@@ -279,21 +207,10 @@ class SessionTimer extends ChangeNotifier {
notifyListeners();
}
void _stopInternal() {
_isDisconnecting = true;
_timer?.cancel();
_timer = null;
_currentSpeedKBps = 0.0;
_hasSyncedOnce = false;
VpnNotificationManager.cancel();
notifyListeners();
}
@override
void dispose() {
vpnConnection.removeListener(_onVpnConnectionChanged);
_timer?.cancel();
VpnNotificationManager.cancel();
super.dispose();
}
}
+192
View File
@@ -0,0 +1,192 @@
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 }
class PlayStoreUpdater {
PlayStoreUpdater._();
static String get _url =>
'https://play.google.com/store/apps/details?id=${AppConfig.applicationId}';
static Future<bool> open() async {
try {
return await launchUrl(Uri.parse(_url),
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 url =
'https://api.github.com/repos/${AppConfig.githubOwner}/${AppConfig.githubRepo}/releases/latest';
try {
final response = await http
.get(Uri.parse(url),
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 data = jsonDecode(response.body) as Map<String, dynamic>;
_cachedDownloadUrl = data['html_url'] as String?;
final tag = data['tag_name'] as String? ?? '0.0.0';
return tag.startsWith('v') ? tag.substring(1) : tag;
} catch (e) {
debugPrint('[Updater] GitHub API error: $e');
return null;
}
}
static Future<bool> open() async {
final url = _cachedDownloadUrl ?? AppConfig.githubReleasesUrl;
try {
return await launchUrl(Uri.parse(url),
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 aParts = a.split('.').map((p) => int.tryParse(p) ?? 0).toList();
final bParts = b.split('.').map((p) => int.tryParse(p) ?? 0).toList();
for (int i = 0; i < 3; i++) {
final diff = (aParts.length > i ? aParts[i] : 0) -
(bParts.length > i ? bParts[i] : 0);
if (diff != 0) return diff;
}
return 0;
}
static String _versionLabel(String v, bool isLocal) {
final prefix = v.startsWith('v') ? '' : 'v';
return '$prefix$v${isLocal ? ' (installed)' : ''}';
}
static Future<void> check(BuildContext context) async {
final info = await PackageInfo.fromPlatform();
final localVersion = info.version;
if (localVersion.isEmpty) {
_showSnackBar(context, 'Could not determine app version',
isError: true);
return;
}
final latestVersion = await GitHubUpdater.fetchLatestVersion();
if (latestVersion == null) {
_showSnackBar(context, 'Could not reach GitHub', isError: true);
return;
}
if (_compareVersions(localVersion, latestVersion) >= 0) {
_showSnackBar(context, 'Up to date');
return;
}
final source = await installSource;
final storeName = source == InstallSource.playStore ? 'Play Store' : 'GitHub';
if (!context.mounted) return;
showDialog(
context: 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(BuildContext context, String message,
{bool isError = false}) {
ScaffoldMessenger.of(context).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),
),
);
}
}
+82 -74
View File
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter_vless/flutter_vless.dart';
import 'package:revoltvpn/logic/hivemind_service.dart';
@@ -22,7 +23,6 @@ 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;
@@ -51,18 +51,19 @@ class VpnConnection extends ChangeNotifier {
try {
await _vless.initializeVless(
providerBundleIdentifier: 'com.revoltvpn.app',
providerBundleIdentifier: 'com.paladinvpn.app',
notificationIconResourceType: 'drawable',
notificationIconResourceName: 'notification_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());
_healthTimer =
Timer.periodic(const Duration(seconds: 30), (_) => _checkHealth());
// Check if VPN was already running (app killed and reopened)
try {
final coreVersion = await _vless.getCoreVersion();
debugPrint('[VPN] Xray core version: $coreVersion');
@@ -92,8 +93,6 @@ class VpnConnection extends ChangeNotifier {
_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,7 +101,18 @@ class VpnConnection extends ChangeNotifier {
}
}
Future<bool> connect({bool skipAdBypass = false, bool quickReconnect = false}) async {
// ── Connect ────────────────────────────────────────────────────────
//
// 1. Direct HTTPS to the public API → get per-user VLESS URL
// 2. Start tunnel directly with that URL (no bootstrap, no switch)
//
// The only hardcoded data in the APK is the Reality public key and
// shortId (needed for every Reality handshake — unavoidable).
// The tunnel UUID is per-user, assigned by Hivemind via AdMob SSV.
Future<bool> connect({
bool skipAdBypass = false,
}) async {
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) {
return false;
}
@@ -114,7 +124,16 @@ class VpnConnection extends ChangeNotifier {
return false;
}
_setStatus(VpnStatus.connecting, 'Fetching config…');
if (!kIsWeb) {
final ok = await _vless.requestPermission();
if (!ok) {
_errorMessage = 'VPN permission denied.';
_setStatus(VpnStatus.error, 'Permission required');
return false;
}
}
_setStatus(VpnStatus.connecting, 'Establishing secure channel…');
_errorMessage = null;
if (kIsWeb) {
@@ -123,33 +142,28 @@ 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);
_errorMessage = e.toString().replaceAll('Exception: ', '');
_setStatus(VpnStatus.error, 'Config fetch error');
}
return false;
}
@@ -159,57 +173,43 @@ class VpnConnection extends ChangeNotifier {
return false;
}
_setStatus(VpnStatus.connecting, 'Securing connection…');
try {
final parsed = FlutterVless.parse(vlessUrl);
final config = parsed.getFullConfiguration();
final parsed = FlutterVless.parse(realUrl);
final configJson =
jsonDecode(parsed.getFullConfiguration()) as Map<String, dynamic>;
// Inject HTTP inbound for tunnel-internal API calls.
final inbounds = (configJson['inbounds'] as List?) ?? [];
inbounds.add({
'tag': 'http-proxy',
'port': 10808,
'listen': '127.0.0.1',
'protocol': 'http',
});
configJson['inbounds'] = inbounds;
await _vless.startVless(
remark: parsed.remark.isNotEmpty ? parsed.remark : 'ReVoltVPN',
config: config,
remark: parsed.remark.isNotEmpty ? parsed.remark : 'Revolt VPN',
config: jsonEncode(configJson),
);
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');
}
return true;
} catch (e) {
debugPrint('[VPN] VLESS tunnel error: $e');
debugPrint('[VPN] Tunnel start error: $e');
_errorMessage = 'Tunnel failed to start.\nTry reconnecting.';
_setStatus(VpnStatus.error, 'Connection failed');
return false;
}
_setStatus(VpnStatus.connected, 'Secured');
return true;
}
Future<void> disconnect({bool skipCleanup = false}) async {
Future<void> disconnect() async {
_cancelled = true;
HivemindService.cancel(); // abort any in-progress polling
if (_status == VpnStatus.disconnected || _status == VpnStatus.disconnecting) {
HivemindService.cancel();
if (_status == VpnStatus.disconnected ||
_status == VpnStatus.disconnecting) {
return;
}
@@ -221,18 +221,28 @@ class VpnConnection extends ChangeNotifier {
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.';
_setStatus(VpnStatus.error, 'Shutdown failed');
return;
}
if (!skipCleanup) {
HivemindService.disconnectAndCleanup();
if (timedOut) {
debugPrint('[VPN] stopVless() timed out after 5 s — '
'tunnel may still be active.');
_errorMessage = 'VPN did not shut down cleanly.\n'
'Please restart the app.';
_setStatus(VpnStatus.error, 'Shutdown failed');
return;
}
_setStatus(VpnStatus.disconnected, 'Tap to connect');
}
@@ -253,9 +263,7 @@ class VpnConnection extends ChangeNotifier {
if (_status == VpnStatus.connected || _status == VpnStatus.connecting) {
try {
_vless.stopVless();
} catch (_) {
// Best-effort — widget is being destroyed anyway
}
} catch (_) {}
}
super.dispose();
}
+10
View File
@@ -3,10 +3,12 @@ import 'dart:ui';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:revoltvpn/logic/vpn_connection.dart';
import 'package:revoltvpn/logic/session_timer.dart';
import 'package:revoltvpn/logic/ad_manager.dart';
import 'package:revoltvpn/logic/server_list.dart';
import 'package:revoltvpn/logic/consent_manager.dart';
import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/screens/intro.dart';
@@ -35,12 +37,19 @@ void main() async {
await ConsentManager.requestConsentIfNeeded();
await MobileAds.instance.initialize();
final packageInfo = await PackageInfo.fromPlatform();
ReVoltApp.appVersion = packageInfo.version;
runApp(const ReVoltApp());
}
class ReVoltApp extends StatelessWidget {
const ReVoltApp({super.key});
/// Set at startup from PackageInfo — used by sidebar and anywhere
/// the app version needs to be displayed.
static String appVersion = '';
@override
Widget build(BuildContext context) {
return MultiProvider(
@@ -51,6 +60,7 @@ class ReVoltApp extends StatelessWidget {
update: (_, vpn, prev) => prev ?? SessionTimer(vpnConnection: vpn),
),
ChangeNotifierProvider(create: (_) => AdManager()),
ChangeNotifierProvider(create: (_) => ServerList()..init()),
],
child: MaterialApp(
title: 'ReVolt VPN',
+1 -1
View File
@@ -90,7 +90,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,
+76 -44
View File
@@ -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,54 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:revoltvpn/logic/app_colors.dart';
bool hapticEnabled = false;
class HapticFeedbackTile extends StatefulWidget {
const HapticFeedbackTile({super.key});
@override
State<HapticFeedbackTile> createState() => _HapticFeedbackTileState();
}
class _HapticFeedbackTileState extends State<HapticFeedbackTile> {
bool _on = false;
@override
void initState() {
super.initState();
_load();
}
// Loads persisted state and syncs the top-level bool.
Future<void> _load() async {
final prefs = await SharedPreferences.getInstance();
final value = prefs.getBool('haptic_feedback_enabled') ?? false;
hapticEnabled = value;
if (mounted) setState(() => _on = value);
}
// Writes to SharedPreferences AND updates the live bool so the connect
// button sees the change immediately — no restart needed.
Future<void> _toggle(bool value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('haptic_feedback_enabled', value);
hapticEnabled = value;
setState(() => _on = value);
}
@override
Widget build(BuildContext context) {
return SwitchListTile(
title: const Text(
'Haptic feedback',
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,58 @@
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.
//
// Same architecture as haptic.dart: exports a top-level bool read synchronously
// by lib/components/lightning.dart. Default: true (lightning is on — opt-out).
// lib/components/lightning.dart reads this in its build method.
bool lightningEnabled = 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 {
final prefs = await SharedPreferences.getInstance();
final value = prefs.getBool('lightning_effect_enabled') ?? true;
lightningEnabled = value;
if (mounted) setState(() => _on = value);
}
Future<void> _toggle(bool value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('lightning_effect_enabled', value);
lightningEnabled = 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,58 @@
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.
//
// Same architecture as haptic.dart: exports a top-level bool read synchronously
// by lib/components/rain.dart. Default: true (rain is on — opt-out).
// lib/components/rain.dart reads this in its build method.
bool rainEnabled = 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 {
final prefs = await SharedPreferences.getInstance();
final value = prefs.getBool('rain_effect_enabled') ?? true;
rainEnabled = value;
if (mounted) setState(() => _on = value);
}
Future<void> _toggle(bool value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('rain_effect_enabled', value);
rainEnabled = 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),
);
}
}
+56
View File
@@ -0,0 +1,56 @@
import 'package:flutter/material.dart';
import 'package:revoltvpn/logic/app_colors.dart';
import 'package:revoltvpn/screens/settings/in_settings/haptic.dart';
import 'package:revoltvpn/screens/settings/in_settings/rain.dart';
import 'package:revoltvpn/screens/settings/in_settings/lightning.dart';
// ── lib/screens/settings/settings_screen.dart ────────────────────────────────
// Settings shell — full-screen page reached from the sidebar.
//
// Folder layout:
// lib/screens/settings/ ← this folder: settings family
// settings_screen.dart ← shell: Scaffold + AppBar + ListView (this file)
// *_tile.dart ← one file per setting feature (add below)
// lib/components/sidebar_contents/
// settings.dart ← thin sidebar row that navigates here
//
// To add a setting:
// 1. Create a new file in this folder, e.g. appearance_tile.dart
// 2. Import it below
// 3. Append it to the children list
class SettingsScreen extends StatelessWidget {
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 [
HapticFeedbackTile(),
RainToggleTile(),
LightningToggleTile(),
// ── Add setting tiles here ────────────────────────────────────────
// Each tile imports from its own file in this folder.
],
),
);
}
}
+28 -20
View File
@@ -97,14 +97,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:
@@ -202,10 +194,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 +207,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 +392,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:
@@ -721,10 +729,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 +769,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:
+3 -2
View File
@@ -15,7 +15,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# 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.2.1+24
environment:
sdk: ">=3.0.0 <4.0.0"
@@ -30,7 +30,7 @@ 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
@@ -38,6 +38,7 @@ dependencies:
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:
-737
View File
@@ -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)