feat: initial LD FDPI v1.7.0 open-source repository

This commit is contained in:
LilDosto 2026-11-06 04:29:58 +03:00
commit 05ca194bef
157 changed files with 27508 additions and 0 deletions

4
.env.example Normal file
View file

@ -0,0 +1,4 @@
# Build-time environment (never commit real values)
LD_FDPI_APP_SECRET=
TAURI_SIGNING_PRIVATE_KEY=
TAURI_SIGNING_PRIVATE_KEY_PASSWORD=

99
.github/workflows/release.yml vendored Normal file
View file

@ -0,0 +1,99 @@
name: Release
on:
push:
tags:
- "v*"
workflow_dispatch:
inputs:
version:
description: "Release version (without v)"
required: true
default: "1.7.0"
permissions:
contents: write
jobs:
build:
runs-on: windows-latest
timeout-minutes: 45
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Rust cache
uses: Swatinem/rust-cache@v2
with:
workspaces: src-tauri
- name: Install dependencies
run: npm ci
- name: Generate version.json
shell: pwsh
run: |
$version = node -p "require('./package.json').version"
$payload = [ordered]@{
version = $version
page_url = "https://ttmadethat.shop/ld-fdpi"
notes = "LD FDPI $version"
}
[IO.File]::WriteAllText(
(Join-Path $PWD "version.json"),
($payload | ConvertTo-Json),
(New-Object Text.UTF8Encoding($false))
)
- name: Build and publish signed release
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
LD_FDPI_APP_SECRET: ${{ secrets.LD_FDPI_APP_SECRET }}
with:
tagName: ${{ github.event_name == 'workflow_dispatch' && format('v{0}', inputs.version) || github.ref_name }}
releaseName: "LD FDPI ${{ github.event_name == 'workflow_dispatch' && inputs.version || github.ref_name }}"
releaseBody: |
LD FDPI release.
- Windows 10/11 x64
- Authenticode yok; SmartScreen uyarabilir.
- Updater paketleri Minisign ile imzalıdır.
releaseDraft: false
prerelease: false
includeUpdaterJson: true
tauriScript: npm run tauri
args: --bundles nsis
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: ld-fdpi-windows-x64
path: |
src-tauri/target/release/bundle/nsis/*.exe
src-tauri/target/release/bundle/nsis/*.sig
version.json
if-no-files-found: error
- name: Verify installer exists
shell: pwsh
run: |
$files = Get-ChildItem "src-tauri/target/release/bundle/nsis" -Filter "*.exe"
if (-not $files) { throw "Installer not found" }
$files | ForEach-Object {
Write-Host "$($_.Name) $((Get-FileHash $_.FullName -Algorithm SHA256).Hash)"
}

73
.gitignore vendored Normal file
View file

@ -0,0 +1,73 @@
# Dependencies
node_modules/
dist/
dist-ssr/
*.local
# Rust / Tauri
src-tauri/target/
src-tauri/gen/
# Target dir is a sibling of the project (see scripts/target-dir.js)
.ld-fdpi-target/
# The official SpoofDPI sidecar is pinned in the repository so a fresh clone can
# build without network access; everything else under binaries is ignored.
src-tauri/binaries/*.exe
src-tauri/binaries/*.log
!src-tauri/binaries/spoofdpi-x86_64-pc-windows-gnu.exe
!src-tauri/binaries/spoofdpi-x86_64-pc-windows-msvc.exe
!src-tauri/binaries/.gitkeep
# Build outputs (uploaded to GitHub Releases instead)
release/
# Logs & OS
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
.DS_Store
Thumbs.db
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Personal SSH shortcut (never publish)
/baðlan.bat
*.bat
# Private AmneziaWG client config (embedded locally into the installer; never publish source)
src-tauri/resources/amnezia_for_awg.conf
amnezia_for_awg.conf
# Secrets and local signing material
.env
.env.*
!.env.example
*.key
*.pem
*.p12
*.pfx
*.jks
*.keystore
*.sig
.tauri/
src-tauri/.tauri/
# Local/runtime artifacts
*.bak
*.tmp
*.old
*.orig
*.rej
.vscode/
.idea/
src-tauri/binaries/*.log
src-tauri/resources/amnezia_for_awg.conf
# Website local output
site/*.tmp

72
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,72 @@
# Katkı Rehberi
LD FDPI’ye katkı sağlamak istediğin için teşekkürler.
## Geliştirme ortamı
Gereksinimler:
- Windows 10/11 x64
- Node.js 20+
- Rust stable (MSVC)
- Visual Studio Build Tools (C++ Desktop)
- WebView2 Runtime
Kurulum:
```powershell
npm ci
npm run check:rust
npm run dev
```
## Kod kuralları
- Rust: `cargo fmt` ve `cargo check`.
- React: mevcut Tailwind/fluent tasarım dilini koru.
- Ağ/WFP değişikliklerinde geri alma ve hata yollarını da yaz.
- Kullanıcıya gösterilen metinlerde Türkçe/İngilizce karışıklığı yaratma.
- Yeni bağımlılık eklemeden önce standart kütüphane/platform çözümünü değerlendir.
## Güvenlik kuralları
Şunları **asla** commit etme:
- `LD_FDPI_APP_SECRET`
- Minisign private key veya password
- `amnezia_for_awg.conf`
- Kişisel `.conf`, log, token, IP listesi
- `src-tauri/target/`, `node_modules/`, `release/`
## Test
```powershell
npm run check:rust
npm test
npm run tauri build
```
Ağ/WFP değişikliklerini izole VM veya ayrı test cihazında doğrula. Ana
makinede doğrulanmamış kernel/network değişikliği yayınlama.
## Pull Request
- Küçük ve tek konulu PR aç.
- Değişikliğin nedenini ve test ortamını yaz.
- UI değişikliği varsa ekran görüntüsü ekle.
- Güvenlik açığı içeren bir konu varsa PR yerine `SECURITY.md` sürecini kullan.
## Commit mesajları
```text
feat: ...
fix: ...
docs: ...
refactor: ...
test: ...
chore: ...
```
## Lisans
Katkılar MIT lisansı altında kabul edilir.

21
LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 LD FDPI Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

294
README.md Normal file
View file

@ -0,0 +1,294 @@
<div align="center">
<img src="./app-icon.png" width="128" height="128" alt="LD FDPI logo" />
<h1>LD FDPI</h1>
<p><strong>Zero-touch VPN + DPI bypass for Windows.</strong><br/>
Tauri v2 · Rust · React · AmneziaWG · SpoofDPI</p>
<p>
<a href="https://github.com/L1lDosto/LD-FDPI/releases/latest">
<img src="https://img.shields.io/badge/İndir-v1.7.0-2ea44f?style=for-the-badge&logo=windows" alt="Download" />
</a>
<img src="https://img.shields.io/badge/Platform-Windows%2010%20%7C%2011-0078D6?style=for-the-badge&logo=windows" alt="Windows" />
<img src="https://img.shields.io/badge/License-MIT-10B981?style=for-the-badge" alt="MIT" />
<img src="https://img.shields.io/badge/Rust-1.80%2B-B7410E?style=for-the-badge&logo=rust" alt="Rust" />
</p>
</div>
**LD FDPI**, Windows 10/11 x64 için iki modlu bir ağ aracıdır:
- **FDPI:** SpoofDPI tabanlı yerel proxy ile DPI/SNI engellerini aşar.
- **VPN:** AmneziaWG ile Almanya çıkışlı, WFP kill-switch korumalı tünel açar.
VPN tarafı **zero-touch** çalışır: token, aktivasyon kodu, `.conf` dosyası veya
“İstemciyi Kur” adımı yoktur. İlk **BAĞLAN**’da AmneziaWG ve cihaz profili
otomatik hazırlanır.
> Bu proje eğitim ve kişisel kullanım için geliştirilmiştir. Bulunduğun ülkenin
> yasalarına ve kullandığın hizmetlerin koşullarına uymak kullanıcının
> sorumluluğundadır.
---
## Özellikler
### Zero-touch VPN
- AmneziaWG istemcisinin sessiz MSI kurulumu.
- MachineGuid + donanım parmak izi ile cihaz kimliği.
- Otomatik `/api/v1/auto-enroll`; token/.conf gerekmez.
- Sunucu tarafında idempotent peer tahsisi.
- Handshake ve servis sağlığı için watchdog.
- Peer düşerse WFP temizliği + otomatik yeniden kayıt + reconnect.
### Ağ güvenliği
- Kalıcı **WFP kill-switch**.
- Tünel DNS’i (`1.1.1.1:53`) dışındaki DNS/DoT çıkışlarının bloklanması.
- IPv6 catch-all ve WebRTC/STUN blokları.
- WFP filtreleri GUI çökse bile çekirdekte kalır; `--restore-only` temizler.
- FDPI için isteğe bağlı **QUIC (UDP/443) uyumluluk modu**.
- Yalnızca Chrome, Edge, Brave, Opera, Firefox ve Discord süreçleri.
- Ayrı WFP sublayer/GUID seti; VPN kill-switch’e dokunmaz.
- Varsayılan kapalı.
- FDPI modunda fiziksel IPv6 DNS/HTTPS sızıntısına karşı opsiyonel WFP bloğu.
### FDPI
- SpoofDPI 0.12.2 sidecar.
- Sistem proxy’si + WinHTTP desteği (game/eduroam modları).
- 3 kademeli otomatik strateji:
1. Kayıtlı/standart profil
2. Alternatif DoH + pencere boyu
3. Turbo/parçalama + yedek DoH
- Her profil `discord.com:443` CONNECT + TLS ile doğrulanır.
- Üç profil de başarısız olursa temel profil açık bırakılır; uygulama çökmez.
- DoH sağlayıcı seçimi: Cloudflare / Google / AdGuard / otomatik.
### Dayanıklılık
- Elektrik kesintisi/`taskkill` sonrası açılışta kirli durum kurtarma.
- Ölü `127.0.0.1:<port>` proxy’sinin sessizce temizlenmesi.
- Yetim `spoofdpi` süreçlerinin temizlenmesi.
- Log rotasyonu (5 MB).
- Tüm yardımcı komutlarda `CREATE_NO_WINDOW`.
- Windows Sandbox/VM testleri için ayrı ortam önerilir.
### Güncelleme
- Minisign imzalı Tauri updater.
- `latest.json` + `.sig` doğrulaması.
- İmza/indirme hatasında otomatik kurulum yapılmaz; kullanıcıya hata gösterilir.
- Güncelleme öncesi FDPI/VPN/proxy temizliği (dosya kilidi koruması).
---
## Hızlı Başlangıç
1. [ttmadethat.shop/ld-fdpi](https://ttmadethat.shop/ld-fdpi) veya
[Releases](https://github.com/L1lDosto/LD-FDPI/releases/latest) sayfasından
`LD-FDPI_*_x64-setup.exe` indir.
2. Kurulumu yönetici olarak çalıştır.
3. Uygulamayı aç.
4. **VPN → BAĞLAN**.
5. FDPI kullanacaksan **FDPI → BAĞLAN**.
İlk VPN bağlantısında:
- AmneziaWG otomatik kurulur.
- Cihaz kimliği üretilir.
- Sunucu peer’ı otomatik atanır.
- WFP kill-switch devreye girer.
Kurulum sonrası internet erişimi kesilirse:
```powershell
& "C:\Program Files\LD FDPI\ld-fdpi.exe" --restore-only
```
Bu komut kalıcı WFP filtrelerini ve proxy sentinel’ini temizler.
---
## Sistem Gereksinimleri
| Gereksinim | Değer |
|---|---|
| İşletim sistemi | Windows 10 22H2 / Windows 11 x64 |
| Yetki | Yönetici (UAC) |
| WebView2 | Installer içinde bootstrapper |
| İnternet | İlk kayıt ve VPN için |
| Desteklenmeyen | Windows 7, ARM64, Windows Sandbox |
FDPI’nin kapsamı sistem proxy’sini kullanan uygulamalarla sınırlıdır. Oyunlar,
bazı launcher’lar ve UDP ses trafiği proxy’den geçmez; bu durumda VPN modu
kullanılmalıdır.
---
## Mimari
```text
┌──────────────────────────────┐
│ React / Tauri WebView │
│ BAĞLAN · Ayarlar · Durum │
└──────────────┬───────────────┘
│ invoke / commands
┌──────────────▼───────────────┐
│ Rust core │
│ supervisor · watchdog │
│ WFP · proxy sentinel │
│ updater · identity │
└───────┬──────────────┬───────┘
│ │
┌───────▼──────┐ ┌────▼─────────────┐
│ SpoofDPI │ │ AmneziaWG │
│ local proxy │ │ Windows service │
└──────────────┘ └────┬─────────────┘
│
┌──────▼─────────────┐
│ Enrollment agent │
│ peer + /16 pool │
└────────────────────┘
```
---
## Kaynaktan Derleme
### Gereksinimler
- Node.js 20+
- Rust stable (MSVC toolchain)
- Visual Studio Build Tools (C++ Desktop)
- WebView2 Runtime (geliştirme ortamında)
### Komutlar
```powershell
npm ci
npm run tauri build
```
Çıktı:
```text
src-tauri/target/release/bundle/nsis/LD FDPI_<version>_x64-setup.exe
```
### Build-time secret
Otomatik kayıt için `LD_FDPI_APP_SECRET` derleme sırasında verilmelidir:
```powershell
$env:LD_FDPI_APP_SECRET = "<server-enrollment-secret>"
npm run tauri build
```
Secret repoya **commit edilmez**. GitHub Actions’ta repository secret olarak
tanımlanır. Bu değer istemci binary’sinden çıkarılabilir; gerçek kullanıcı
kimlik doğrulaması değildir. Sunucu tarafında rate-limit ve cihaz bazlı kayıt
koruma sağlar.
### Updater imzası
```powershell
$env:TAURI_SIGNING_PRIVATE_KEY = Get-Content "$HOME\.tauri\ld-fdpi-updater.key" -Raw
$env:TAURI_SIGNING_PRIVATE_KEY_PASSWORD = "<password>"
npm run tauri build
```
Private key ve password **asla repoya eklenmez**. Kaybedilirse yeni sürümler
imzalanamaz.
---
## Proje Yapısı
```text
.
├── src/ React arayüzü
├── src-tauri/ Rust çekirdeği
│ ├── src/
│ │ ├── engine.rs SpoofDPI yönetimi + probing
│ │ ├── vpn.rs AmneziaWG + watchdog
│ │ ├── wfp_killswitch.rs WFP filtreleri
│ │ ├── identity.rs cihaz kimliği + enrollment
│ │ ├── proxy_sentinel.rs proxy kurtarma
│ │ └── updater.rs güvenli güncelleme
│ ├── capabilities/ Tauri izinleri
│ └── resources/ AmneziaWG MSI
├── deploy/ld-fdpi-enroll/ Python enrollment agent
├── scripts/ build/test yardımcıları
├── site/ tanıtım sayfası
├── docs/ teknik dokümanlar
└── .github/workflows/ CI/CD
```
---
## Geliştirme
```powershell
npm ci
npm run dev
npm run check:rust
npm test
```
Faydalı komutlar:
```text
npm run tauri dev
npm run tauri build
npm run setup:sidecar
npm run icon:make
```
Test bayrakları yalnızca açıkça etkinleştirildiğinde çalışır:
```powershell
$env:LD_FDPI_TEST_CLI = "1"
```
---
## Güvenlik ve Gizlilik
- Kaynak kod açıktır; güvenlik açıkları için [SECURITY.md](SECURITY.md) izle.
- `APP_SECRET` bir kullanıcı hesabı değildir; cihaz kaydı için abuse bariyeridir.
- Updater yalnızca Minisign imzası doğrulanan paketleri kurar.
- WFP filtreleri yönetici gerektirir; uygulama `requireAdministrator` manifestosuyla çalışır.
- VPN yapılandırması özel anahtar içerir; `%LOCALAPPDATA%\LD-FDPI` altında tutulur.
- Loglara özel anahtar veya token yazılmaz.
- Kod imzası (Authenticode) yoktur; SmartScreen “bilinmeyen yayıncı” uyarabilir.
### Bilinen sınırlar
- FDPI, sistem proxy’sini kullanmayan uygulamaları kapsamaz.
- Discord sesi UDP kullanır; FDPI proxy’si UDP taşımaz.
- Tek VPN endpoint’i vardır; otomatik sunucu seçimi/failover yoktur.
- IPv6 için VPN tüneli sınırlıdır; FDPI modunda IPv6 sızıntı bloğu opsiyoneldir.
- Kurumsal GPO/antivirüs, proxy veya WFP değişikliklerini engelleyebilir.
---
## Katkı
Katkı rehberi: [CONTRIBUTING.md](CONTRIBUTING.md)
- Yeni özellikler için önce issue aç.
- Secret, anahtar, `.conf` veya kişisel log ekleme.
- `npm run check:rust` ve `npm test` çalıştır.
- PR açıklamasında test ortamını belirt.
---
## Lisans
[MIT](LICENSE) © 2026 LD FDPI Contributors
Üçüncü taraf bileşenler:
- [SpoofDPI](https://github.com/xvzc/SpoofDPI) — MIT
- [AmneziaWG](https://github.com/amnezia-vpn/amneziawg-windows-client) — ilgili lisans
- [Tauri](https://tauri.app) — MIT/Apache-2.0
- [React](https://react.dev) — MIT

45
SECURITY.md Normal file
View file

@ -0,0 +1,45 @@
# Güvenlik Politikası
## Desteklenen sürümler
| Sürüm | Destek |
|---|---|
| 1.7.x | ✅ |
| 1.6.x ve öncesi | ❌ |
## Güvenlik açığı bildirimi
Lütfen güvenlik açıklarını **public issue olarak açma**.
Bunun yerine GitHub’ın özel güvenlik bildirimi özelliğini kullan:
1. Depoda **Security** sekmesine git.
2. **Report a vulnerability** seç.
3. Etkilenen sürümü, yeniden üretim adımlarını ve etkiyi yaz.
Alternatif olarak depo sahibine GitHub üzerinden özel mesaj gönder.
## Kapsam
Özellikle şunlar ilgi alanına girer:
- WFP kill-switch veya FDPI filtrelerinin atlatılması
- Proxy sentinel’in ölü proxy bırakması
- Enrollment/peer yetkisiz erişim
- Updater imza doğrulamasının atlatılması
- Path traversal, komut enjeksiyonu, ayrıcalık yükseltme
- Hassas anahtar/token sızıntısı
## Bilinen tasarım sınırları
- `LD_FDPI_APP_SECRET` istemci binary’sinden çıkarılabilir; gerçek kullanıcı
kimlik doğrulaması değildir.
- Authenticode yoktur; SmartScreen uyarısı beklenir.
- FDPI yalnızca sistem proxy’sini kullanan uygulamaları kapsar.
- Windows Sandbox, host proxy politikası nedeniyle desteklenmez.
## Yanıt süreci
- Bildirim 72 saat içinde değerlendirilir.
- Düzeltme yayınlanana kadar ayrıntılar gizli tutulur.
- Hak edilen bildirimler README/CHANGELOG’da anılır.

BIN
app-icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 882 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 607 KiB

12
deploy/fix_enroll_head.py Normal file
View file

@ -0,0 +1,12 @@
from pathlib import Path
p = Path('/opt/tylorindar-safelink/main.py')
t = p.read_text(encoding='utf-8')
t = t.replace('@app.head("/{code}")\n@app.post("/api/v1/auto-enroll")', '@app.post("/api/v1/auto-enroll")', 1)
old = '@app.get("/{code}")\nasync def redirect_shortlink'
new = '@app.head("/{code}")\n@app.get("/{code}")\nasync def redirect_shortlink'
if old in t:
t = t.replace(old, new, 1)
p.write_text(t, encoding='utf-8')
print('head restored')
else:
print('redirect marker missing')

View file

@ -0,0 +1,398 @@
#!/usr/bin/env python3
"""Dependency-free LD FDPI enrollment agent (host, Docker access only locally)."""
import base64, hashlib, hmac, json, os, re, secrets, sqlite3, subprocess, sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from datetime import datetime, timezone
DB = os.environ.get("LD_FDPI_ENROLL_DB", "/opt/ld-fdpi-enroll/enroll.db")
CONTAINER = os.environ.get("LD_FDPI_AWG_CONTAINER", "amnezia-awg2")
CONF = os.environ.get("LD_FDPI_AWG_CONF", "/opt/amnezia/awg/awg0.conf")
SERVER_PUB = os.environ["LD_FDPI_SERVER_PUB"]
ENDPOINT = os.environ.get("LD_FDPI_ENDPOINT", "116.202.14.171:42771")
APP_SECRET = os.environ.get("LD_FDPI_APP_SECRET", "")
AWG_JSON = os.environ.get("LD_FDPI_AWG_PARAMS_FILE", "/opt/ld-fdpi-enroll/awg.json")
try:
with open(AWG_JSON, encoding="utf-8") as fh:
AWG = json.load(fh)
except Exception:
AWG = {}
PUBKEY_RE = re.compile(r"^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$")
DEVICE_RE = re.compile(r"^[a-f0-9]{64}$")
def conn():
c = sqlite3.connect(DB, timeout=10, isolation_level=None)
c.execute("PRAGMA journal_mode=WAL")
c.execute("PRAGMA busy_timeout=10000")
c.execute("""CREATE TABLE IF NOT EXISTS tokens (
token_hash TEXT PRIMARY KEY, used_by_device TEXT, allocated_ip TEXT,
public_key TEXT, psk TEXT, used_at TEXT)""")
c.execute("""CREATE TABLE IF NOT EXISTS devices (
device_id TEXT PRIMARY KEY, allocated_ip TEXT UNIQUE, public_key TEXT UNIQUE,
psk TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)""")
c.execute("""CREATE TABLE IF NOT EXISTS rate (
bucket TEXT PRIMARY KEY, ts INTEGER NOT NULL, count INTEGER NOT NULL)""")
return c
def th(token):
return hashlib.sha256(token.encode()).hexdigest()
def rate(c, bucket, limit=5):
now = int(datetime.now(timezone.utc).timestamp())
row = c.execute("SELECT ts,count FROM rate WHERE bucket=?", (bucket,)).fetchone()
if not row or now - row[0] > 60:
c.execute("INSERT OR REPLACE INTO rate VALUES(?,?,1)", (bucket, now))
elif row[1] >= limit:
raise ValueError("rate")
else:
c.execute("UPDATE rate SET count=count+1 WHERE bucket=?", (bucket,))
def ensure_pool_route():
"""Keep the expanded pool routed through awg0 after container restarts."""
subprocess.run(
["docker", "exec", CONTAINER, "ip", "route", "replace",
"10.8.0.0/16", "dev", "awg0"],
check=False,
)
def candidate_ips():
for i in range(20, 255):
yield f"10.8.1.{i}"
for third in range(2, 255):
for fourth in range(2, 255):
yield f"10.8.{third}.{fourth}"
def ip_alloc(c, evict=False):
def used_ips():
return {r[0] for r in c.execute(
"SELECT allocated_ip FROM devices WHERE allocated_ip IS NOT NULL "
"UNION SELECT allocated_ip FROM tokens WHERE allocated_ip IS NOT NULL"
)}
used = used_ips()
for ip in candidate_ips():
if ip not in used:
if not ip.startswith("10.8.1."):
ensure_pool_route()
return ip
if evict:
evicted = evict_inactive(c)
if evicted:
used = used_ips()
for ip in candidate_ips():
if ip not in used:
if not ip.startswith("10.8.1."):
ensure_pool_route()
return ip
raise ValueError("pool")
def awg_handshakes():
result = subprocess.run(
["docker", "exec", CONTAINER, "awg", "show", "awg0", "latest-handshakes"],
capture_output=True, text=True, check=False,
)
if result.returncode != 0:
return None
handshakes = {}
for line in result.stdout.splitlines():
parts = line.split()
if len(parts) >= 2 and parts[1].isdigit():
handshakes[parts[0]] = int(parts[1])
return handshakes
def evict_inactive(c):
"""Free one IP from a peer with no handshake for 30+ days."""
handshakes = awg_handshakes()
if handshakes is None:
return False
cutoff = int(datetime.now(timezone.utc).timestamp()) - 30 * 24 * 3600
rows = list(c.execute(
"SELECT device_id, public_key, allocated_ip, updated_at FROM devices"
))
candidates = []
for device, pub, ip, updated in rows:
last = handshakes.get(pub, 0)
if last == 0 or last < cutoff:
candidates.append((last, updated or "", device, pub, ip))
candidates.sort()
for last, _updated, device, pub, ip in candidates:
subprocess.run(
["docker", "exec", CONTAINER, "awg", "set", "awg0", "peer", pub, "remove"],
check=False,
)
awg_remove_conf(pub)
c.execute("DELETE FROM devices WHERE device_id=?", (device,))
print(f"evicted inactive peer device={device[:8]} ip={ip} last={last}", file=sys.stderr)
return True
return False
def awg_remove_conf(pub):
"""Drop a rotated peer block so a container restart cannot revive it."""
script = (
f"awk -v pub='{pub}' '"
"/^\\[Peer\\]$/ { inpeer=1; block=$0 \"\\n\"; next } "
"inpeer { block=block $0 \"\\n\"; "
"if ($0 ~ /^AllowedIPs[[:space:]]*=/) { "
"if (index(block, \"PublicKey = \" pub) == 0) printf \"%s\", block; "
"inpeer=0; block=\"\" } next } "
"{ print } END { if (inpeer) printf \"%s\", block }' "
f"{CONF} > {CONF}.tmp && mv {CONF}.tmp {CONF}"
)
subprocess.run(["docker", "exec", CONTAINER, "sh", "-c", script], check=False)
def awg_set(pub, ip, psk, persist=True):
append = ""
if persist:
append = (
f"printf '\\n[Peer]\\nPublicKey = {pub}\\nPresharedKey = ' >> {CONF}; "
f"cat /tmp/ld-fdpi.psk >> {CONF}; "
f"printf '\\nAllowedIPs = {ip}/32\\n' >> {CONF}; "
)
script = (
"umask 077; cat > /tmp/ld-fdpi.psk; "
f"awg set awg0 peer {pub} preshared-key /tmp/ld-fdpi.psk allowed-ips {ip}/32; "
+ append +
"rm -f /tmp/ld-fdpi.psk"
)
subprocess.run(["docker", "exec", "-i", CONTAINER, "sh", "-c", script],
input=psk.encode(), check=True)
def legacy_enrollment(pub, device):
c = conn()
try:
c.execute("BEGIN IMMEDIATE")
row = c.execute("SELECT used_by_device,allocated_ip,public_key,psk FROM tokens WHERE used_by_device=?",
(device,)).fetchone()
if not row:
raise ValueError("unauthorized")
used, ip, old_pub, psk = row
if old_pub == pub:
c.execute("COMMIT")
return ip, psk
token = c.execute("SELECT token_hash FROM tokens WHERE used_by_device=?", (device,)).fetchone()[0]
if old_pub:
subprocess.run(["docker", "exec", CONTAINER, "awg", "set", "awg0", "peer", old_pub, "remove"], check=False)
awg_remove_conf(old_pub)
psk = base64.b64encode(secrets.token_bytes(32)).decode()
awg_set(pub, ip, psk)
c.execute("UPDATE tokens SET public_key=?,psk=?,used_at=? WHERE token_hash=?",
(pub, psk, datetime.now(timezone.utc).isoformat(), token))
c.execute("COMMIT")
return ip, psk
finally:
c.close()
def auto_enrollment(pub, device):
"""Idempotent per-device enrollment. Same key returns the same peer/IP."""
c = conn()
try:
c.execute("BEGIN IMMEDIATE")
row = c.execute("SELECT allocated_ip,public_key,psk FROM devices WHERE device_id=?",
(device,)).fetchone()
if row:
ip, old_pub, psk = row
if old_pub == pub:
# Idempotent retry: re-apply the peer, because it may have been
# removed from the container while the DB record remained.
awg_set(pub, ip, psk, persist=False)
c.execute("COMMIT")
return ip, psk
other = c.execute("SELECT device_id FROM devices WHERE public_key=? AND device_id<>?",
(pub, device)).fetchone()
if other:
c.execute("ROLLBACK")
raise ValueError("key-in-use")
if old_pub:
subprocess.run(["docker", "exec", CONTAINER, "awg", "set", "awg0", "peer", old_pub, "remove"], check=False)
awg_remove_conf(old_pub)
psk = base64.b64encode(secrets.token_bytes(32)).decode()
awg_set(pub, ip, psk, persist=True)
c.execute("UPDATE devices SET public_key=?,psk=?,updated_at=? WHERE device_id=?",
(pub, psk, datetime.now(timezone.utc).isoformat(), device))
c.execute("COMMIT")
return ip, psk
other = c.execute("SELECT device_id FROM devices WHERE public_key=?", (pub,)).fetchone()
if other:
c.execute("ROLLBACK")
raise ValueError("key-in-use")
ip = ip_alloc(c, evict=True)
psk = base64.b64encode(secrets.token_bytes(32)).decode()
awg_set(pub, ip, psk, persist=True)
now = datetime.now(timezone.utc).isoformat()
c.execute("INSERT INTO devices(device_id,allocated_ip,public_key,psk,created_at,updated_at) "
"VALUES(?,?,?,?,?,?)", (device, ip, pub, psk, now, now))
c.execute("COMMIT")
return ip, psk
except Exception:
try:
c.execute("ROLLBACK")
except Exception:
pass
raise
finally:
c.close()
def response_for(ip, psk):
return 200, {
"address": f"{ip}/32",
"dns": ["1.1.1.1", "1.0.0.1"],
"server_public_key": SERVER_PUB,
"preshared_key": psk,
"endpoint": ENDPOINT,
"allowed_ips": ["0.0.0.0/0", "::/0"],
"awg": {
"jc": 5, "jmin": 10, "jmax": 50,
"s1": 12, "s2": 12, "s3": 12, "s4": 12,
"h1": 1, "h2": 2, "h3": 3, "h4": 4,
"header_protection_key": AWG.get("header_protection_key", ""),
"rekey_after_time": "100-120", "rekey_timeout": "3-7",
"reject_after_time": "150-180", "keepalive_timeout": "5-15",
"max_handshake_attempts": "15-20",
"random_trailers": True, "disable_cookies": True,
},
}
def parse_request(handler):
length = int(handler.headers.get("Content-Length", "0"))
if length <= 0 or length > 8192:
raise ValueError("bad request")
body = json.loads(handler.rfile.read(length))
pub = str(body.get("public_key", ""))
device = str(body.get("device_id", ""))
if not PUBKEY_RE.match(pub) or not DEVICE_RE.match(device):
raise ValueError("invalid key/device")
base64.b64decode(pub, validate=True)
return pub, device
def handle_enroll(handler):
try:
pub, device = parse_request(handler)
except Exception:
return 400, {"error": "bad request"}
token = handler.headers.get("Authorization", "").removeprefix("Bearer ").strip()
if not token:
return 401, {"error": "missing token"}
c = conn()
try:
c.execute("BEGIN IMMEDIATE")
rate(c, th(token))
row = c.execute("SELECT used_by_device,allocated_ip,public_key,psk FROM tokens WHERE token_hash=?",
(th(token),)).fetchone()
if not row:
c.execute("ROLLBACK")
return 401, {"error": "invalid token"}
used, ip, old_pub, psk = row
if used is not None and used != device:
c.execute("ROLLBACK")
return 409, {"error": "token used on another device"}
if used == device and ip and psk:
if old_pub and old_pub != pub:
subprocess.run(["docker", "exec", CONTAINER, "awg", "set", "awg0", "peer", old_pub, "remove"], check=False)
psk = base64.b64encode(secrets.token_bytes(32)).decode()
awg_set(pub, ip, psk)
else:
ip = ip_alloc(c)
psk = base64.b64encode(secrets.token_bytes(32)).decode()
awg_set(pub, ip, psk)
c.execute("UPDATE tokens SET used_by_device=?,allocated_ip=?,public_key=?,psk=?,used_at=? WHERE token_hash=?",
(device, ip, pub, psk, datetime.now(timezone.utc).isoformat(), th(token)))
c.execute("COMMIT")
except ValueError as e:
c.execute("ROLLBACK")
return (429 if str(e) == "rate" else 401), {"error": str(e)}
except Exception:
c.execute("ROLLBACK")
return 500, {"error": "enrollment failed"}
finally:
c.close()
return response_for(ip, psk)
def handle_auto_enroll(handler):
if not APP_SECRET:
return 503, {"error": "auto-enroll disabled"}
if not hmac.compare_digest(handler.headers.get("X-App-Secret", ""), APP_SECRET):
return 401, {"error": "unauthorized"}
try:
pub, device = parse_request(handler)
except Exception:
return 400, {"error": "bad request"}
ip_hint = (handler.headers.get("X-Real-IP") or handler.headers.get("CF-Connecting-IP")
or handler.client_address[0])
c = conn()
try:
c.execute("BEGIN IMMEDIATE")
rate(c, "ip:" + ip_hint, 20)
rate(c, "dev:" + ip_hint + ":" + device, 5)
c.execute("COMMIT")
except ValueError as e:
c.execute("ROLLBACK")
return (429 if str(e) == "rate" else 400), {"error": str(e)}
except Exception:
c.execute("ROLLBACK")
return 500, {"error": "enrollment failed"}
finally:
c.close()
try:
ip, psk = auto_enrollment(pub, device)
except ValueError as e:
if str(e) == "pool":
return 503, {"error": "pool exhausted"}
if str(e) == "key-in-use":
return 409, {"error": "public key already enrolled"}
return 400, {"error": str(e)}
except Exception:
return 502, {"error": "peer setup failed"}
return response_for(ip, psk)
class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt, *args):
sys.stderr.write("enroll: " + fmt % args + "\n")
def do_POST(self):
if self.path == "/api/v1/enroll":
code, payload = handle_enroll(self)
elif self.path == "/api/v1/auto-enroll":
code, payload = handle_auto_enroll(self)
else:
code, payload = 404, {"error": "not found"}
self.reply(code, payload)
def reply(self, code, payload):
data = json.dumps(payload).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == "--mint":
token = "LDFDPI-" + "-".join(
"".join(secrets.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(4))
for _ in range(3)
)
c = conn()
c.execute("INSERT INTO tokens(token_hash) VALUES(?)", (th(token),))
c.close()
print(token)
raise SystemExit(0)
ensure_pool_route()
ThreadingHTTPServer(("172.17.0.1", 9471), Handler).serve_forever()

View file

@ -0,0 +1,19 @@
[Unit]
Description=LD FDPI Enrollment Agent
After=network.target docker.service
Requires=docker.service
[Service]
Type=simple
User=root
WorkingDirectory=/opt/ld-fdpi-enroll
EnvironmentFile=/opt/ld-fdpi-enroll/.env
ExecStartPre=/usr/bin/python3 /opt/ld-fdpi-enroll/sync_peers.py
ExecStart=/usr/bin/python3 /opt/ld-fdpi-enroll/agent.py
Restart=always
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target

View file

@ -0,0 +1,209 @@
"""LD FDPI one-time, device-bound enrollment agent.
Run as a host systemd service (not inside the public FastAPI container) so it
can call `docker exec` without exposing the Docker socket to the web app.
Environment:
LD_FDPI_ENROLL_DB default /opt/ld-fdpi-enroll/enroll.db
LD_FDPI_AWG_CONTAINER default amnezia-awg2
LD_FDPI_SERVER_PUB AmneziaWG server public key (base64)
LD_FDPI_ENDPOINT default 116.202.14.171:42771
LD_FDPI_AWG_PARAMS_JSON optional JSON object with jc/jmin/... fields
LD_FDPI_ADMIN_TOKEN token that can mint enrollment codes via /admin/token
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import os
import re
import secrets
import sqlite3
import subprocess
from datetime import datetime, timezone
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel, Field
DB = os.environ.get("LD_FDPI_ENROLL_DB", "/opt/ld-fdpi-enroll/enroll.db")
CONTAINER = os.environ.get("LD_FDPI_AWG_CONTAINER", "amnezia-awg2")
CONF = os.environ.get("LD_FDPI_AWG_CONF", "/opt/amnezia/awg/awg0.conf")
SERVER_PUB = os.environ["LD_FDPI_SERVER_PUB"]
ENDPOINT = os.environ.get("LD_FDPI_ENDPOINT", "116.202.14.171:42771")
ADMIN_TOKEN = os.environ.get("LD_FDPI_ADMIN_TOKEN", "")
AWG = json.loads(os.environ.get("LD_FDPI_AWG_PARAMS_JSON", "{}"))
PUBKEY_RE = re.compile(r"^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$")
DEVICE_RE = re.compile(r"^[a-f0-9]{64}$")
app = FastAPI(title="LD FDPI enrollment", docs_url=None, redoc_url=None)
def db() -> sqlite3.Connection:
conn = sqlite3.connect(DB, timeout=10, isolation_level=None)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=10000")
conn.execute(
"""CREATE TABLE IF NOT EXISTS tokens (
token_hash TEXT PRIMARY KEY,
used_by_device TEXT,
allocated_ip TEXT,
public_key TEXT,
psk TEXT,
used_at TEXT
)"""
)
conn.execute(
"""CREATE TABLE IF NOT EXISTS rate (
bucket TEXT PRIMARY KEY,
ts INTEGER NOT NULL,
count INTEGER NOT NULL
)"""
)
return conn
def token_hash(token: str) -> str:
return hashlib.sha256(token.encode()).hexdigest()
def check_rate(conn: sqlite3.Connection, bucket: str) -> None:
now = int(datetime.now(timezone.utc).timestamp())
row = conn.execute("SELECT ts, count FROM rate WHERE bucket=?", (bucket,)).fetchone()
if not row or now - row[0] > 60:
conn.execute("INSERT OR REPLACE INTO rate(bucket, ts, count) VALUES(?,?,1)", (bucket, now))
return
if row[1] >= 5:
raise HTTPException(429, "rate limit")
conn.execute("UPDATE rate SET count=count+1 WHERE bucket=?", (bucket,))
def allocate_ip(conn: sqlite3.Connection) -> str:
used = {
row[0]
for row in conn.execute("SELECT allocated_ip FROM tokens WHERE allocated_ip IS NOT NULL")
}
for i in range(20, 251):
ip = f"10.8.1.{i}"
if ip not in used:
return ip
raise HTTPException(503, "IP pool exhausted")
def awg_set(public_key: str, ip: str, psk: str) -> None:
script = (
"umask 077; cat > /tmp/ld-fdpi.psk; "
f"awg set awg0 peer {public_key} preshared-key /tmp/ld-fdpi.psk allowed-ips {ip}/32; "
f"printf '\\n[Peer]\\nPublicKey = {public_key}\\nPresharedKey = %s\\nAllowedIPs = {ip}/32\\n' "
'"$(cat /tmp/ld-fdpi.psk)" >> ' + CONF + "; rm -f /tmp/ld-fdpi.psk"
)
subprocess.run(
["docker", "exec", "-i", CONTAINER, "sh", "-c", script],
input=psk.encode(),
check=True,
)
class Enroll(BaseModel):
public_key: str = Field(min_length=44, max_length=44)
client_version: str = Field(max_length=32)
device_id: str = Field(min_length=64, max_length=64)
@app.post("/api/v1/enroll")
def enroll(req: Enroll, authorization: str = Header(default="")):
token = authorization.removeprefix("Bearer ").strip()
if not token or not PUBKEY_RE.match(req.public_key) or not DEVICE_RE.match(req.device_id):
raise HTTPException(400, "invalid request")
base64.b64decode(req.public_key, validate=True)
th = token_hash(token)
conn = db()
try:
conn.execute("BEGIN IMMEDIATE")
check_rate(conn, th)
row = conn.execute(
"SELECT used_by_device, allocated_ip, public_key, psk FROM tokens WHERE token_hash=?",
(th,),
).fetchone()
if not row:
raise HTTPException(401, "invalid token")
used_by, ip, old_pub, psk = row
if used_by is not None and used_by != req.device_id:
raise HTTPException(409, "token already used on another device")
if used_by == req.device_id and ip and psk:
# Idempotent re-install: same device gets the same IP/PSK.
if old_pub and old_pub != req.public_key:
subprocess.run(
["docker", "exec", CONTAINER, "awg", "set", "awg0", "peer", old_pub, "remove"],
check=False,
)
psk = base64.b64encode(secrets.token_bytes(32)).decode()
awg_set(req.public_key, ip, psk)
else:
ip = allocate_ip(conn)
psk = base64.b64encode(secrets.token_bytes(32)).decode()
awg_set(req.public_key, ip, psk)
conn.execute(
"UPDATE tokens SET used_by_device=?, allocated_ip=?, public_key=?, psk=?, used_at=? "
"WHERE token_hash=?",
(req.device_id, ip, req.public_key, psk, datetime.now(timezone.utc).isoformat(), th),
)
conn.execute("COMMIT")
except HTTPException:
conn.execute("ROLLBACK")
raise
except Exception as exc:
conn.execute("ROLLBACK")
raise HTTPException(500, "enrollment failed") from exc
finally:
conn.close()
return {
"address": f"{ip}/32",
"dns": ["1.1.1.1", "1.0.0.1"],
"server_public_key": SERVER_PUB,
"preshared_key": psk,
"endpoint": ENDPOINT,
"allowed_ips": ["0.0.0.0/0", "::/0"],
"awg": {
"jc": 5, "jmin": 10, "jmax": 50,
"s1": 12, "s2": 12, "s3": 12, "s4": 12,
"h1": 1, "h2": 2, "h3": 3, "h4": 4,
"header_protection_key": AWG.get("header_protection_key", ""),
"rekey_after_time": "100-120", "rekey_timeout": "3-7",
"reject_after_time": "150-180", "keepalive_timeout": "5-15",
"max_handshake_attempts": "15-20",
"random_trailers": True, "disable_cookies": True,
},
}
class TokenRequest(BaseModel):
note: str = ""
@app.post("/admin/token")
def mint_token(req: TokenRequest, authorization: str = Header(default="")):
if not ADMIN_TOKEN or not hmac.compare_digest(
authorization.removeprefix("Bearer ").strip(), ADMIN_TOKEN
):
raise HTTPException(401, "unauthorized")
token = "LDFDPI-" + "-".join(
"".join(secrets.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(4))
for _ in range(3)
)
conn = db()
try:
conn.execute(
"INSERT INTO tokens(token_hash) VALUES(?)",
(token_hash(token),),
)
finally:
conn.close()
return {"token": token, "note": req.note}

View file

@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Restore persisted LD FDPI peers after a container/host restart."""
import os, sqlite3, subprocess
DB = os.environ.get("LD_FDPI_ENROLL_DB", "/opt/ld-fdpi-enroll/enroll.db")
CONTAINER = os.environ.get("LD_FDPI_AWG_CONTAINER", "amnezia-awg2")
conn = sqlite3.connect(DB)
conn.execute(
"""CREATE TABLE IF NOT EXISTS tokens (
token_hash TEXT PRIMARY KEY, used_by_device TEXT, allocated_ip TEXT,
public_key TEXT, psk TEXT, used_at TEXT)"""
)
conn.execute(
"""CREATE TABLE IF NOT EXISTS devices (
device_id TEXT PRIMARY KEY, allocated_ip TEXT UNIQUE, public_key TEXT UNIQUE,
psk TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"""
)
rows = conn.execute(
"SELECT public_key, psk, allocated_ip FROM tokens "
"WHERE public_key IS NOT NULL AND allocated_ip IS NOT NULL AND psk IS NOT NULL "
"UNION "
"SELECT public_key, psk, allocated_ip FROM devices "
"WHERE public_key IS NOT NULL AND allocated_ip IS NOT NULL AND psk IS NOT NULL"
).fetchall()
conn.close()
for pub, psk, ip in rows:
script = (
"umask 077; cat > /tmp/psk_sync; "
f"awg set awg0 peer {pub} preshared-key /tmp/psk_sync allowed-ips {ip}/32; "
"rm -f /tmp/psk_sync"
)
subprocess.run(
["docker", "exec", "-i", CONTAINER, "sh", "-c", script],
input=psk.encode(),
check=False,
)

View file

@ -0,0 +1,33 @@
from pathlib import Path
p = Path('/opt/tylorindar-safelink/static/index.html')
t = p.read_text(encoding='utf-8')
old_desc = ("Windows için yerel proxy ve DPI bypass aracı. v1.5.10: kalıcı WFP kill-switch, "
"VPN endpoint/DHCP/LAN izinleri, DNS 53-853 engeli, IPv6 catch-all ve WebRTC STUN blokları. "
"GUI veya tünel servisi çökse bile filtreler çekirdekte kalır; --restore-only temizler. "
"C1 cihaz kaydı ve C3 NetMode korunuyor. Rust/Tauri v2 + React + SpoofDPI 0.12.2.")
new_desc = ("Windows için DPI bypass + AmneziaWG VPN. Kur, BAĞLAN'a bas: cihaz profili otomatik oluşur; "
"token veya .conf gerekmez. Kalıcı WFP kill-switch, DNS/IPv6/STUN sızıntı koruması ve "
"10 saniyede kendini onaran tünel. Rust/Tauri v2 + React + SpoofDPI 0.12.2.")
if old_desc not in t:
raise SystemExit('card desc not found')
t = t.replace(old_desc, new_desc, 1)
old_actions = ('<div class="ld-app-actions"><a class="ld-app-btn ld-app-btn-source" '
'href="/static/downloads/ld-apps/LD-FDPI-1.5.10-44a7360-portable.zip" download>📦 Portable ZIP '
'<span class="ld-app-size">5.1 MB</span></a><a class="ld-app-btn ld-app-btn-source" '
'href="/static/downloads/ld-apps/ld-fdpi-1.5.10-source.zip" download>📦 Kaynak ZIP '
'<span class="ld-app-size">14.2 MB</span></a><a class="ld-app-btn ld-app-btn-readme" '
'href="/static/downloads/ld-apps/readmes/ld-fdpi-v1.5.10-44a7360-README.md" target="_blank" '
'rel="noopener">📄 README</a><a class="ld-app-btn ld-app-btn-apps" '
'href="https://ttmadethat.shop/ld-fdpi" target="_blank" rel="noopener">🧭 LD Apps\'e Git</a>'
'<span class="ld-app-updated" data-ldapp="ld-fdpi">Son güncelleme: —</span>'
'<span class="ld-app-foot">Windows 10/11 · x64</span></div>')
new_actions = ('<div class="ld-app-actions"><a class="ld-app-btn ld-app-btn-apps" '
'href="https://ttmadethat.shop/ld-fdpi" target="_blank" rel="noopener">🧭 Detaylar</a>'
'<span class="ld-app-updated" data-ldapp="ld-fdpi">Son güncelleme: —</span>'
'<span class="ld-app-foot">Windows 10/11 · x64</span></div>')
if old_actions not in t:
raise SystemExit('card actions not found')
t = t.replace(old_actions, new_actions, 1)
p.write_text(t, encoding='utf-8')
print('index card updated')

View file

@ -0,0 +1,14 @@
from pathlib import Path
old_name = "LD-FDPI_1.5.10_44a7360_x64-setup.exe"
new_name = "LD-FDPI_1.5.10_568239d_x64-setup.exe"
old_query = "?v=44a7360"
new_query = "?v=568239d"
for path in [
Path('/opt/tylorindar-safelink/static/index.html'),
Path('/opt/tylorindar-safelink/static/downloads/ld-fdpi.html'),
]:
text = path.read_text(encoding='utf-8')
text = text.replace(old_name, new_name).replace(old_query, new_query)
path.write_text(text, encoding='utf-8')
print('updated', path)

93
docs/ARCHITECTURE.md Normal file
View file

@ -0,0 +1,93 @@
# LD FDPI — Teknik Mimari
## 1. Katmanlar
- **Arayüz (`src/`):** React 18 + Tailwind. `src/utils/engineArgs.js` saf yardımcılar (CLI argümanları, PAC, Tauri tespiti), `src/utils/tauriBridge.js` ise `invoke` sarmalayıcısı ve DOMPurify süzgeci. Simülasyon/mock dalı yoktur; Tauri yoksa açık hata verir.
- **Ayarlar (`src-tauri/src/config.rs`):** `%LOCALAPPDATA%\LD-FDPI\config.json`; `autoStart`, `autoConnect`, `minimizeToTray` varsayılan olarak `true`. Webview yüklenmeden Rust tarafından okunur.
- **Otomatik başlatma (`src-tauri/src/autostart.rs`):** `schtasks /Create /TN LD_FDPI_AutoStart /SC ONLOGON /RL HIGHEST /DELAY 0000:20 /F`. `HKCU\...\Run` kullanılmaz; `requireAdministrator` bir exe oradan UAC'siz başlayamaz.
- **Durum & komutlar (`src-tauri/src/lib.rs`):** `AppState` → `Runtime` + `AppConfig` + `PacHandle`. Uzun işler `spawn_blocking`; UI `get_status` ile 2,5 sn'de bir hafif durum okur.
- **Motor (`src-tauri/src/engine.rs`):** SpoofDPI 0.12.2 sidecar'ı (exe dizini → `binaries/` → manifest), PE + ≥1.5 MB doğrulama, gerçek bayraklar, port bekleme, CONNECT + SChannel TLS probu.
- **Sistem proxy (`src-tauri/src/proxy_sentinel.rs`):** Tam yedek (ProxyEnable, ProxyServer, ProxyOverride, AutoConfigURL, AutoDetect), PAC/WPAD'i devre dışı bırakma, `InternetSetOptionW` + `WM_SETTINGCHANGE`, yedek yoksa no-op, dış değişiklik koruması, WinHTTP bayrağı.
- **WinHTTP (`src-tauri/src/winhttp.rs`):** Oyun Modu'nda yalnızca mevcut ayar "Direct access" ise `netsh winhttp set proxy`; geri yüklemede `reset proxy`.
- **PAC (`src-tauri/src/pac_server.rs`):** `0.0.0.0:<port>`, tokio, `Semaphore(50)`, RFC1918 + `.local` için DIRECT.
## 2. "Kur ve unut" akışı
1. `run()` açılmadan önce `run_startup_sentinel_check()` + zombi temizliği.
2. `config.json` okunur, normalize edilir, yazılır.
3. `autostart::apply(auto_start)` görevi oluşturur/siler.
4. `setup`:
- `--minimized`/`--autostart` yoksa pencere gösterilir (config'te `visible:false`).
- `auto_connect` ise **React'ten önce** bir iş parçacığı `do_start` çağırır.
- `lan_sharing` ise PAC sunucusu arka planda başlatılır.
- 15 sn'lik supervisor başlatılır.
5. Supervisor her turda: `desired_connected`, `connecting`, çocuk süreç, sistem proxy yönlendirmesi ve uyanma (`sleep > 45 sn`) kontrolü. Gerekiyorsa `do_restart`/`do_start`; hata olursa 30 sn backoff.
## 3. Bağlanma akışı
1. Config doğrulanır; zombi `spoofdpi` süreçleri öldürülür.
2. Port boş mu? (gerçek bind testi)
3. Sidecar spawn + log; 8 sn içinde dinlemezse/çıkarsa hata (log tail'i ile).
4. Proxy üzerinden `discord.com:443` ve `www.cloudflare.com:443` TLS probu (retry'lı).
5. Başarılıysa WinINet proxy'si yazılır; Oyun Modu'nda WinHTTP de denenir.
6. State güncellenir, watchdog kurulur.
Herhangi bir adım başarısızsa çocuk süreç öldürülür ve sistem proxy'sine dokunulmaz; kısmi yazma olduysa `restore_system_proxy(true)` ile geri alınır.
## 4. Geri yükleme
- Normal kesme: yalnızca `dirty_sentinel = true` ve `ProxyServer` hâlâ bizim yazdığımız değer ise geri yüklenir; başka araç değiştirdiyse dokunulmaz.
- Zorla: acil onarım / kaldırma / çökme sonrası; WinHTTP de sıfırlanır.
- Yedek yoksa veya oturum temizse: hiçbir yazma yapılmaz (`noBackup` / `alreadyClean`).
## 5. UAC manifestosu
- `src-tauri/windows-app-manifest.xml`: `requestedExecutionLevel level="requireAdministrator"`, Common Controls v6, DPI ve long path.
- `build.rs`: `tauri_build::WindowsAttributes::app_manifest(...)`.
- **GNU ld sorunu:** MinGW CRT kendi `asInvoker` manifestosunu gömer; iki RT_MANIFEST birleşir ve Windows asInvoker'ı uygular. `scripts/patch-manifest.mjs`, `rcedit` ile exe'nin manifest kaynağını tek `requireAdministrator` olarak değiştirir.
- `scripts/tauri.js`: `build --no-bundle` → `rcedit` → `tauri bundle`. `LD_FDPI_NO_ADMIN=1` test derlemesinde bu adım atlanır.
## 6. Kaldırma
`nsis/hooks.nsh` → `taskkill ld-fdpi.exe` → `ld-fdpi.exe --restore-only` → `schtasks /Delete /TN LD_FDPI_AutoStart /F` → `taskkill spoofdpi.exe`.
## 7. Test kapsamı
- `npm test` (21): sidecar SHA-256 + `-v`, CLI bayrak eşleşmesi, DoH listesi, CSP/IPC, simülasyon yokluğu, PAC eşliği, sentinel güvenliği, **canlı TLS**, i18n, config varsayılanları, UAC/`RL HIGHEST`, 15 sn supervisor, **hash pin + shell/unwrap yokluğu**, **PAC 4 KB/5 sn/peer filtresi**, **sıfır capability + panic hook**, **Eduroam modu**, **Smart DoH/TCP_NODELAY/LTO**, **logo entegrasyonu**, **captive portal asistanı**, **sürüm 1.5.6**.
- `npm run test:gui` (24): WebView2 IPC, sade arayüz, BAĞLAN/KES, LAN rebind, config.json, autostart uyarısı, `--minimized` + auto-connect + gizli pencere.
- `node scripts/security-e2e.mjs` (11): LAN kapalı loopback, LAN açık erişim, PAC 200/413/408, LAN kapatınca geri dönüş, Eduroam modu/status/tanılama/kapanış.
- `ld-fdpi.exe --self-test` (12): motor + registry + WinHTTP bayrağı + config round-trip.
## 8. Güvenlik sıkılaştırması
- **Ağ:** LAN kapalıyken `127.0.0.1`; LAN açıkken `0.0.0.0` + RFC1918 peer filtresi; PAC 4 KB/5 sn; firewall `remoteip=localsubnet`; açılışta LAN zorla kapalı.
- **Sidecar:** SHA-256 pin (`16a5c8”¦ea5e`), spawn öncesi tekrar doğrulama; uyuşmazsa hard fail.
- **Süreç:** shell yok; `netsh`/`schtasks` System32 tam yolu; `schtasks /TR` tırnaklı; katı config whitelist.
- **Dosya:** config/sentinel 64 KB + typed serde; `LOCALAPPDATA`/`System32` Win32 API'den.
- **WebView:** katı CSP + sıfır capability.
- **DNS:** yalnızca DoH (`-enable-doh`, `-dns-port` yok).
- **Fail-safe:** panic hook motoru PID ile öldürür, proxy/WinHTTP'yi geri yükler, exit(1).
- **Rust:** `.unwrap()`/`.expect()` yok; `npm audit` 0; `cargo check` temiz.
## 9. Logo / ikon
`assets/branding/ld-fdpi-logo-source.png` (doğru logo: şeffaf lacivert zemin, siyah cam paneller, buz mavisi tüpler) → `npm run icon:make` → `app-icon.png` (1024) + `public/logo.png` (512) → `node scripts/tauri.js icon app-icon.png` → `src-tauri/icons/*` (ico/png/icns/Store). `tauri.conf.json` `bundle.icon`, exe/installer/tepsi, arayüz ve site kartı bu logoyu kullanır. Arayüz paleti Tailwind `slate/blue/cyan` + `fluent` tokenlarında lacivert-grafit ve buz mavisi aralığına eşlenir.
## 10. Eduroam Modu
- **Algılama:** `netsh wlan show interfaces` → SSID / arayüz / kimlik doğrulama; `is_eduroam` = SSID içinde `eduroam`.
- **Bağlantı:** `netsh wlan connect name=eduroam` (yalnızca kayıtlı Windows profili). 802.1X kullanıcı adı/şifresi uygulamaya girmez; ilk giriş Windows Wi-Fi ayarlarından yapılır.
- **MTU:** Wi-Fi IPv4 MTU 1400; `eduroam_mtu_backup.json` ile çökme güvenli yedek; duruş/çökme/açılışta geri yükleme.
- **Proxy:** `eduroam`, WinHTTP + WinINet kapsamına girer (`is_system_wide`). PAC'ta `*.edu`, `*.edu.tr`, `*.ac.uk`, `eduroam.org` ve özel IP'ler DIRECT.
- **Tanılama:** SSID, 802.1X, MTU, `discord.com:443`, `discord.media:443/2087`, UDP/STUN.
- **Sınır:** Kurum güvenlik duvarı aşılmaz; Discord sesi UDP (19294-19344 / 50000-50100) HTTP proxy'den geçmez.
## 11. Performans
- Smart DoH: 3 sağlayıcı × 3 paralel TCP, medyan, 10 dk cache.
- PAC: `set_nodelay(true)`, `Cache-Control: public, max-age=3600`.
- Süreç: `ABOVE_NORMAL_PRIORITY_CLASS`.
- Derleme: `opt-level=3`, `lto="fat"`, `codegen-units=1`, `panic="abort"`, `strip=true`.
- Geçiş kilidi (`TRANSITION`), supervisor `probe_local_port`, log ring buffer 150, tepsi odağında UI timer duraklatma.

159
docs/ZERO_TOUCH.md Normal file
View file

@ -0,0 +1,159 @@
# Zero-touch Auto-Enrollment
The old one-time token flow is replaced by a per-device, idempotent
auto-enrollment flow.
## Flow
```text
BAĞLAN
-> AmneziaWG missing? install MSI silently (app runs elevated)
-> config missing? POST /api/v1/auto-enroll
-> save %LOCALAPPDATA%\LD-FDPI\ld-fdpi.conf
-> install/start AmneziaWGTunnel$ld-fdpi
-> enable WFP kill-switch
-> wait up to 10 s for tunnel egress
-> on failure: delete config, re-enroll, retry once
```
## Identity
- Windows `HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid`
- SHA-256(`ld-fdpi-hwid-v1` + lowercased MachineGuid) = 64-char hex `device_id`
- X25519 key pair remains local; private key sealed with DPAPI
- `device_id` is stable across app reinstall and `%LOCALAPPDATA%` deletion
## API
`POST https://ttmadethat.shop/api/v1/auto-enroll`
Headers:
```text
Content-Type: application/json
X-App-Secret: <embedded shared secret>
```
Body:
```json
{"public_key":"...","device_id":"<64 hex>","client_version":"1.5.10"}
```
Behavior:
- New device -> next free `10.8.1.x/32`, new PSK, peer added.
- Existing device + same public key -> same IP/PSK, peer re-applied.
- Existing device + new public key -> old peer removed, same IP reused.
- Public key already bound to another device -> `409`.
- IP pool exhausted -> `503`.
- Per-IP rate limit: **5 requests / minute**.
- `X-App-Secret` wrong/missing -> `401`.
## Server deployment
`/opt/ld-fdpi-enroll/.env`:
```text
LD_FDPI_APP_SECRET=<same value embedded in client>
```
The FastAPI site proxies `/api/v1/auto-enroll` to `172.17.0.1:9471` and forwards
`X-App-Secret`, `X-Real-IP` (Cloudflare client IP). Backup:
`/opt/tylorindar-safelink/backups/main.py.bak-auto-enroll`.
## Watchdog
After a successful connect, a watchdog checks the tunnel every 3 seconds. It
does **not** use the local `latest handshake` age: WireGuard only rekeys about
every 2 minutes, and deleting the server peer does not immediately reset the
client's displayed handshake time.
Checks:
1. If the AWG service stopped unexpectedly, recovery starts immediately.
2. Otherwise a DNS query to `1.1.1.1:53` goes through the tunnel. WFP blocks
port 53 on the physical interface and permits only the tunnel LUID, so a
direct WAN response cannot mask a dead peer.
3. Three consecutive failed checks (~9 s) trigger WFP teardown, service
stop/delete, config removal, auto-enroll, service reinstall, and WFP re-arm.
4. Recovery is attempted at most 3 times; after that the watchdog stops and
reports an error instead of looping forever.
If WFP teardown fails, recovery aborts instead of attempting an HTTPS request
through the catch-all block.
## MSI installation
The bundled MSI is copied out of `Program Files` to a plain
`%WINDIR%\Temp\ld-amneziawg.msi` path before `msiexec` runs. This avoids
extended `\\?\` paths and Program Files/MSI open failures (`1619`). The MSI log
is written to `%WINDIR%\Temp\ld-awg-msi.log` and its tail is included in the
error if installation fails.
## Sandbox acceptance result
Windows Sandbox (`--auto-connect-vpn`) passed:
- WebView2 + app install
- Silent AmneziaWG MSI install via temp copy
- Automatic enrollment (new `10.8.1.x/32`)
- Service start + handshake
- Tunnel ping (8.8.8.8 through VPN, ~55 ms)
- Server peer deletion -> peer re-added, `latest handshake` refreshed in <40 s
Not tested: forced WFP-teardown failure and reboot persistence.
## Headless acceptance flag
`ld-fdpi.exe --auto-connect-vpn` starts the normal zero-touch pipeline without
UI interaction and writes:
```text
%LOCALAPPDATA%\LD-FDPI\auto-connect-result.txt
```
This exists for Windows Sandbox/CI acceptance testing.
## Key rotation / stale peer blocks
When a device re-enrolls with a new public key, the old peer is removed from
the running AWG interface **and** its `[Peer]` block is removed from
`awg0.conf`. Otherwise a container restart could revive the old key on the same
`10.8.1.x/32`, causing endpoint flapping.
## WFP / retry ordering
The kill-switch blocks physical egress. Re-enrolling while it is still active
would make the HTTPS request to `ttmadethat.shop` fail, so the retry path is:
```text
handshake fail
-> disable_killswitch() with 3 attempts
-> if teardown fails: ABORT, keep the tunnel/service state, report error
-> stop service
-> delete config
-> auto-enroll over normal physical HTTPS
-> reinstall/start service
```
The API IP is not permanently whitelisted in WFP; that would punch a hole in the
kill-switch. The teardown result is checked instead.
## Security warning
`APP_SECRET` is embedded in the installer and is extractable. This is **not**
real authentication; it only stops random scanners. Anyone who extracts it can
enroll devices until the shared secret is rotated and a new client is shipped.
The IP rate limit also means shared NAT (school/office) can hit 5/minute.
Token enrollment remains available as a legacy endpoint but is no longer used
by the UI.
## Known limitation
`MachineGuid` is per Windows installation, not per Windows user. Two Windows
users on the same PC share `device_id`; the last enrollment wins. Disk-cloned
Windows images without Sysprep can also share it. If that becomes common, add
the SMBIOS UUID/baseboard serial to the hash; the current audience is fine with
MachineGuid alone.

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

BIN
docs/screenshot-home.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

13
index.html Normal file
View file

@ -0,0 +1,13 @@
<!doctype html>
<html lang="tr" class="dark">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/logo.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>LD FDPI — Yerel Proxy & DPI Bypass</title>
</head>
<body class="bg-fluent-bg text-slate-100 antialiased selection:bg-blue-500/30 selection:text-blue-200 overflow-hidden select-none">
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

30
mobile-app/.gitignore vendored Normal file
View file

@ -0,0 +1,30 @@
# Flutter/Dart
.dart_tool/
.packages
.pub-cache/
.pub/
build/
.flutter-plugins
.flutter-plugins-dependencies
# Android
android/.gradle/
android/local.properties
android/app/debug/
android/app/profile/
android/app/release/
android/key.properties
*.jks
*.keystore
# IDE
.idea/
.vscode/
*.iml
# OS
.DS_Store
Thumbs.db
# Native build cache
android/app/.cxx/

87
mobile-app/BUILD.md Normal file
View file

@ -0,0 +1,87 @@
# Build
## Prerequisites
- Flutter 3.29+ (Dart 3.4+)
- Android SDK Platform 35
- Android Build Tools 35.0.0
- JDK 17 or 21
- Windows: `JAVA_HOME` set to the JDK
## SDK setup (Windows, no Android Studio)
```powershell
# 1. Flutter
Expand-Archive C:\src\flutter.zip C:\src
$env:Path = "C:\src\flutter\bin;$env:Path"
flutter --version
# 2. Android command-line tools
Expand-Archive C:\Android\cmdline-tools.zip C:\Android\cmdline-tools
# move so sdkmanager is at C:\Android\cmdline-tools\latest\bin
$env:ANDROID_HOME = "C:\Android\Sdk"
$env:Path = "C:\Android\cmdline-tools\latest\bin;$env:Path"
sdkmanager --sdk_root=$env:ANDROID_HOME "platform-tools" "platforms;android-35" "build-tools;35.0.0"
sdkmanager --sdk_root=$env:ANDROID_HOME --licenses
flutter config --android-sdk $env:ANDROID_HOME
flutter doctor
```
## Project config
Create `mobile-app/android/local.properties`:
```properties
sdk.dir=C:\\Android\\Sdk
flutter.sdk=C:\\src\\flutter
```
## Build APK
```powershell
cd mobile-app
flutter pub get
flutter build apk --release
```
Output:
```text
mobile-app/build/app/outputs/flutter-apk/app-release.apk
```
## Signing
The scaffold uses the debug signing config for `release` so it can be installed
for testing. Create a real keystore before distribution:
```powershell
keytool -genkeypair -v -keystore ld-fdpi-mobile.jks -keyalg RSA -keysize 2048 -validity 10000 -alias ld-fdpi
```
Then replace `signingConfig = signingConfigs.debug` in
`android/app/build.gradle` with a `signingConfigs.release` block and store
credentials outside the repository.
## Install
```powershell
adb install -r mobile-app\build\app\outputs\flutter-apk\app-release.apk
```
## Important limitation
The generated APK **will not establish a tunnel** until
`android/app/src/main/jniLibs/<abi>/libawg.so` exists. See
`docs/TUNNEL_BACKEND.md`. The app intentionally refuses to connect instead of
shipping a fake WireGuard fallback that the AmneziaWG server would reject.
## Tests before distribution
1. Clean install on Android 10 and Android 14.
2. Activation code → enrollment succeeds.
3. Connect → TUN + handshake.
4. Kill the native process/service → traffic must not leak.
5. Enable Always-on + Block without VPN in Android settings; reboot.
6. Disconnect → internet returns; DNS/egress IP test.

77
mobile-app/README.md Normal file
View file

@ -0,0 +1,77 @@
# Mobile app
LD FDPI Android client scaffold.
## What is implemented
- Flutter dark UI: connection state, assigned IP, endpoint, ping, activation code.
- X25519 key generation in Dart (`cryptography`).
- Private key and enrollment config in **Android EncryptedSharedPreferences**
via `flutter_secure_storage`.
- One-time device enrollment against `https://ttmadethat.shop/api/v1/enroll`.
- Android `VpnService` shell with:
- TUN establishment, all-IPv4/IPv6 routes, DNS 1.1.1.1/1.0.0.1.
- Foreground notification.
- `BIND_VPN_SERVICE` manifest permission.
- Native `libawg.so` JNI boundary (`NativeTunnel`).
- Settings screen with Android VPN settings deep link for Always-on/Block without VPN.
## What is not bundled
`android/app/src/main/jniLibs/*/libawg.so` is **not** included. The stock
WireGuard Android backend does not implement AmneziaWG obfuscation
(`Jc/Jmin/Jmax/S1-S4/H1-H4/HeaderProtectionKey`). Without that native core the
APK installs and the UI runs, but **Connect reports “AmneziaWG çekirdeği yok”**
and does not open a TUN. This is deliberate: a fake tunnel that silently leaks
or blocks all traffic is worse.
See `docs/TUNNEL_BACKEND.md` for the required JNI contract and build steps.
## Build
```bash
cd mobile-app
flutter pub get
flutter build apk --release
```
APK output:
```text
build/app/outputs/flutter-apk/app-release.apk
```
The project expects:
- Flutter 3.29+ / Dart 3.4+
- Android SDK platform 35, build-tools 35.0.0
- JDK 17+ (tested with JDK 21)
- `android/local.properties`:
```properties
sdk.dir=C:\\Users\\<you>\\AppData\\Local\\Android\\Sdk
flutter.sdk=C:\\src\\flutter
```
If the Gradle wrapper jar is missing:
```bash
cd android
gradle wrapper --gradle-version 8.10.2
```
## Install / test
```bash
adb install -r build/app/outputs/flutter-apk/app-release.apk
adb shell am start -n com.ldfdpi.mobile/.MainActivity
```
Then:
1. Enter the one-time activation code.
2. Allow Android VPN consent.
3. For kill-switch, open **Settings → VPN ayarlarını aç** and enable
**Always-on VPN** + **Block connections without VPN** for LD FDPI.
4. With `libawg.so` present, Connect starts the tunnel; without it, Connect is
rejected rather than leaking traffic.

View file

@ -0,0 +1,5 @@
include: package:flutter_lints/flutter.yaml
linter:
rules:
avoid_print: false

View file

@ -0,0 +1,50 @@
plugins {
id "com.android.application"
id "kotlin-android"
id "dev.flutter.flutter-gradle-plugin"
}
android {
namespace = "com.ldfdpi.mobile"
compileSdk = 35
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
defaultConfig {
applicationId = "com.ldfdpi.mobile"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "0.1.0"
}
buildTypes {
release {
// Replace with a real keystore before Play/APK distribution.
signingConfig = signingConfigs.debug
minifyEnabled = false
shrinkResources = false
}
}
packaging {
jniLibs {
useLegacyPackaging = true
}
}
}
flutter {
source = "../.."
}
dependencies {
implementation "androidx.core:core-ktx:1.13.1"
}

View file

@ -0,0 +1,52 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.BIND_VPN_SERVICE" />
<application
android:name="${applicationName}"
android:label="LD FDPI"
android:icon="@drawable/ic_launcher"
android:allowBackup="false"
android:usesCleartextTraffic="false"
android:supportsRtl="true"
android:theme="@style/LaunchTheme">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".LdFdpiVpnService"
android:permission="android.permission.BIND_VPN_SERVICE"
android:exported="false"
android:foregroundServiceType="specialUse">
<intent-filter>
<action android:name="android.net.VpnService" />
</intent-filter>
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="vpn" />
</service>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>

View file

@ -0,0 +1,29 @@
package io.flutter.plugins;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import io.flutter.Log;
import io.flutter.embedding.engine.FlutterEngine;
/**
* Generated file. Do not edit.
* This file is generated by the Flutter tool based on the
* plugins that support the Android platform.
*/
@Keep
public final class GeneratedPluginRegistrant {
private static final String TAG = "GeneratedPluginRegistrant";
public static void registerWith(@NonNull FlutterEngine flutterEngine) {
try {
flutterEngine.getPlugins().add(new com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin());
} catch (Exception e) {
Log.e(TAG, "Error registering plugin flutter_secure_storage, com.it_nomads.fluttersecurestorage.FlutterSecureStoragePlugin", e);
}
try {
flutterEngine.getPlugins().add(new io.flutter.plugins.pathprovider.PathProviderPlugin());
} catch (Exception e) {
Log.e(TAG, "Error registering plugin path_provider_android, io.flutter.plugins.pathprovider.PathProviderPlugin", e);
}
}
}

View file

@ -0,0 +1,235 @@
package com.ldfdpi.mobile
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.VpnService
import android.os.Build
import android.os.ParcelFileDescriptor
import androidx.core.app.NotificationCompat
import org.json.JSONObject
class LdFdpiVpnService : VpnService() {
private var tun: ParcelFileDescriptor? = null
private var running = false
companion object {
const val ACTION_START = "com.ldfdpi.mobile.START"
const val ACTION_STOP = "com.ldfdpi.mobile.STOP"
const val EXTRA_CONFIG = "config"
private const val CHANNEL_ID = "ld_fdpi_tunnel"
private const val NOTIFICATION_ID = 4201
private val state = TunnelRuntime()
fun start(context: Context, config: String) {
val intent = Intent(context, LdFdpiVpnService::class.java)
.setAction(ACTION_START)
.putExtra(EXTRA_CONFIG, config)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent)
} else {
context.startService(intent)
}
}
fun stop(context: Context) {
context.startService(
Intent(context, LdFdpiVpnService::class.java).setAction(ACTION_STOP)
)
}
fun snapshot(): Map<String, Any?> = state.snapshot()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_START -> {
val config = intent.getStringExtra(EXTRA_CONFIG)
if (config.isNullOrBlank()) {
state.setError("Tünel yapılandırması boş.")
} else {
startTunnel(config)
}
}
ACTION_STOP -> stopTunnel()
else -> {
if (!running) stopSelf()
}
}
return START_STICKY
}
private fun startTunnel(configJson: String) {
if (running) return
state.connecting()
createNotificationChannel()
startForeground(NOTIFICATION_ID, buildNotification("LD FDPI bağlanıyor", "Tünel hazırlanıyor"))
try {
val config = JSONObject(configJson)
val address = config.optString("address", "10.8.1.2/32").substringBefore('/')
val dns = config.optJSONArray("dns")
val builder = Builder()
.setSession("LD FDPI")
.setMtu(1420)
.addAddress(address, 32)
.addRoute("0.0.0.0", 0)
.addRoute("::", 0)
if (dns != null && dns.length() > 0) {
for (i in 0 until dns.length()) {
val server = dns.optString(i, "")
if (server.isNotBlank()) builder.addDnsServer(server)
}
} else {
builder.addDnsServer("1.1.1.1")
builder.addDnsServer("1.0.0.1")
}
if (!NativeTunnel.available()) {
state.setError("AmneziaWG çekirdeği (libawg.so) APK içinde yok.")
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
return
}
val descriptor = builder.establish()
if (descriptor == null) {
state.setError("Android VpnService TUN arayüzü açılamadı.")
stopSelf()
return
}
tun = descriptor
val nativeStarted = try {
NativeTunnel.start(descriptor.fd, configJson)
} catch (_: Throwable) {
false
}
if (!nativeStarted) {
descriptor.close()
tun = null
state.setError("AmneziaWG tüneli başlatılamadı.")
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
return
}
running = true
state.connected(address, config.optString("endpoint", "—"))
updateNotification("LD FDPI bağlı", "Trafik tünelden geçiyor")
} catch (e: Throwable) {
closeTunnel()
state.setError(e.message ?: "Tünel başlatma hatası.")
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
}
private fun stopTunnel() {
closeTunnel()
state.disconnected()
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
private fun closeTunnel() {
running = false
try {
NativeTunnel.stop()
} catch (_: Throwable) {
}
try {
tun?.close()
} catch (_: Throwable) {
}
tun = null
}
override fun onRevoke() {
closeTunnel()
state.disconnected()
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
super.onRevoke()
}
override fun onDestroy() {
closeTunnel()
super.onDestroy()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val manager = getSystemService(NotificationManager::class.java)
val channel = NotificationChannel(
CHANNEL_ID,
"LD FDPI tüneli",
NotificationManager.IMPORTANCE_LOW
).apply { description = "VPN tüneli durumu" }
manager.createNotificationChannel(channel)
}
private fun buildNotification(title: String, text: String): Notification {
val open = PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
return NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_lock_lock)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(open)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build()
}
private fun updateNotification(title: String, text: String) {
val manager = getSystemService(NotificationManager::class.java)
manager.notify(NOTIFICATION_ID, buildNotification(title, text))
}
}
class TunnelRuntime {
@Volatile private var state = "disconnected"
@Volatile private var address: String? = null
@Volatile private var endpoint: String? = null
@Volatile private var error: String? = null
fun connecting() {
state = "connecting"
error = null
}
fun connected(address: String, endpoint: String) {
state = "connected"
this.address = address
this.endpoint = endpoint
error = null
}
fun disconnected() {
state = "disconnected"
address = null
endpoint = null
error = null
}
fun setError(message: String) {
state = "error"
error = message
}
fun snapshot(): Map<String, Any?> = mapOf(
"state" to state,
"address" to address,
"endpoint" to endpoint,
"error" to error
)
}

View file

@ -0,0 +1,84 @@
package com.ldfdpi.mobile
import android.content.Intent
import android.net.VpnService
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.net.InetSocketAddress
import java.net.Socket
class MainActivity : FlutterActivity() {
private val channelName = "ld_fdpi/native"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName)
.setMethodCallHandler { call, result ->
when (call.method) {
"startTunnel" -> {
val config = call.argument<String>("config")
if (config.isNullOrBlank()) {
result.error("config", "Tunnel config is empty", null)
} else {
try {
LdFdpiVpnService.start(applicationContext, config)
result.success(null)
} catch (e: Exception) {
result.error("start", e.message, null)
}
}
}
"stopTunnel" -> {
try {
LdFdpiVpnService.stop(applicationContext)
result.success(null)
} catch (e: Exception) {
result.error("stop", e.message, null)
}
}
"status" -> result.success(LdFdpiVpnService.snapshot())
"openVpnSettings" -> {
try {
val intent = Intent(android.provider.Settings.ACTION_VPN_SETTINGS)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
result.success(null)
} catch (e: Exception) {
result.error("settings", e.message, null)
}
}
"ping" -> {
Thread {
val started = System.nanoTime()
var ms: Int? = null
try {
Socket().use { socket ->
socket.connect(InetSocketAddress("1.1.1.1", 443), 1500)
ms = ((System.nanoTime() - started) / 1_000_000).toInt()
}
} catch (_: Exception) {
ms = null
}
runOnUiThread { result.success(ms) }
}.start()
}
"prepare" -> {
val intent = VpnService.prepare(applicationContext)
result.success(intent == null)
}
"requestVpnPermission" -> {
val intent = VpnService.prepare(applicationContext)
if (intent == null) {
result.success(true)
} else {
startActivityForResult(intent, 1001)
result.success(false)
}
}
else -> result.notImplemented()
}
}
}
}

View file

@ -0,0 +1,28 @@
package com.ldfdpi.mobile
/**
* JNI contract for the AmneziaWG userspace tunnel.
*
* Implementations must:
* - accept a connected VpnService TUN fd,
* - apply Jc/Jmin/Jmax/S1-S4/H1-H4/HeaderProtectionKey parameters,
* - pump packets until nativeStop() is called,
* - never log private keys or preshared keys.
*
* The stock WireGuard Android backend does not understand AWG obfuscation, so
* libawg.so must be built from amneziawg-go with gomobile/NDK and placed under
* android/app/src/main/jniLibs/<abi>/.
*/
object NativeTunnel {
private val loaded: Boolean = try {
System.loadLibrary("awg")
true
} catch (_: UnsatisfiedLinkError) {
false
}
fun available(): Boolean = loaded
external fun start(tunFd: Int, configJson: String): Boolean
external fun stop()
}

View file

@ -0,0 +1,15 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#0D151D"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#8FE3F5"
android:pathData="M54,20L82,32V52C82,69 70,82 54,88C38,82 26,69 26,52V32L54,20ZM54,30L36,38V52C36,64 43,73 54,78C65,73 72,64 72,52V38L54,30Z" />
<path
android:fillColor="#8DFFAD"
android:pathData="M48,52L58,62L70,46L74,50L58,70L44,56Z" />
</vector>

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/launch_bg" />
</layer-list>

View file

@ -0,0 +1,14 @@
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Material.NoActionBar">
<item name="android:windowBackground">@drawable/launch_background</item>
<item name="android:statusBarColor">#05080B</item>
<item name="android:navigationBarColor">#05080B</item>
<item name="android:windowLightStatusBar">false</item>
</style>
<style name="NormalTheme" parent="@android:style/Theme.Material.NoActionBar">
<item name="android:windowBackground">#05080B</item>
<item name="android:statusBarColor">#05080B</item>
<item name="android:navigationBarColor">#05080B</item>
<item name="android:windowLightStatusBar">false</item>
</style>
</resources>

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="launch_bg">#05080B</color>
</resources>

View file

@ -0,0 +1,14 @@
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Material.NoActionBar">
<item name="android:windowBackground">@drawable/launch_background</item>
<item name="android:statusBarColor">#05080B</item>
<item name="android:navigationBarColor">#05080B</item>
<item name="android:windowLightStatusBar">false</item>
</style>
<style name="NormalTheme" parent="@android:style/Theme.Material.NoActionBar">
<item name="android:windowBackground">#05080B</item>
<item name="android:statusBarColor">#05080B</item>
<item name="android:navigationBarColor">#05080B</item>
<item name="android:windowLightStatusBar">false</item>
</style>
</resources>

View file

@ -0,0 +1,20 @@
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = "../build"
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(":app")
}
tasks.register("clean", Delete) {
delete rootProject.buildDir
}

View file

@ -0,0 +1,4 @@
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
android.useAndroidX=true
android.enableJetifier=true
kotlin.code.style=official

Binary file not shown.

View file

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip

9
mobile-app/android/gradlew vendored Normal file
View file

@ -0,0 +1,9 @@
#!/usr/bin/env sh
DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
CLASSPATH="$DIR/gradle/wrapper/gradle-wrapper.jar"
if [ -n "$JAVA_HOME" ]; then
JAVA_EXE="$JAVA_HOME/bin/java"
else
JAVA_EXE=java
fi
exec "$JAVA_EXE" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"

View file

@ -0,0 +1,25 @@
pluginManagement {
def flutterSdkPath = {
def properties = new Properties()
file("local.properties").withInputStream { properties.load(it) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
return flutterSdkPath
}()
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id "dev.flutter.flutter-plugin-loader" version "1.0.0"
id "com.android.application" version "8.7.0" apply false
id "org.jetbrains.kotlin.android" version "2.1.0" apply false
}
include ":app"

View file

@ -0,0 +1,109 @@
# AmneziaWG native backend
The app deliberately does **not** fake a VPN. `LdFdpiVpnService` only calls
`Builder.establish()` when the native core is present. Without the core the UI
stays usable but Connect is rejected with:
> AmneziaWG çekirdeği (libawg.so) APK içinde yok.
## Why not the stock WireGuard Android library?
`com.wireguard.android:tunnel` implements WireGuard but has no notion of
AmneziaWG's `Jc/Jmin/Jmax/S1-S4/H1-H4/HeaderProtectionKey` fields. A standard
WireGuard handshake will not be accepted by the AWG server. Shipping it and
pretending it works would create a silent leak/blackhole.
## JNI contract
Kotlin (`NativeTunnel.kt`):
```kotlin
external fun start(tunFd: Int, configJson: String): Boolean
external fun stop()
```
C/C++/Go exports:
```c
JNIEXPORT jboolean JNICALL
Java_com_ldfdpi_mobile_NativeTunnel_start(JNIEnv *env, jobject thiz,
jint tun_fd, jstring config_json);
JNIEXPORT void JNICALL
Java_com_ldfdpi_mobile_NativeTunnel_stop(JNIEnv *env, jobject thiz);
```
`configJson` has:
```json
{
"address": "10.8.1.20/32",
"dns": ["1.1.1.1", "1.0.0.1"],
"endpoint": "116.202.14.171:42771",
"server_public_key": "...",
"preshared_key": "...",
"allowed_ips": ["0.0.0.0/0", "::/0"],
"private_key": "...",
"awg": {
"jc": 5, "jmin": 10, "jmax": 50,
"s1": 12, "s2": 12, "s3": 12, "s4": 12,
"h1": 1, "h2": 2, "h3": 3, "h4": 4,
"header_protection_key": "...",
"rekey_after_time": "100-120",
"rekey_timeout": "3-7",
"reject_after_time": "150-180",
"keepalive_timeout": "5-15"
}
}
```
The native side must:
1. Take ownership of the TUN fd (do not close it twice).
2. Apply AWG obfuscation parameters before the first handshake.
3. Pump packets until `stop()`.
4. Never log `private_key` or `preshared_key`.
5. Return `false` on bad config/handshake failure so Kotlin closes the TUN and
reports an error.
## Building `libawg.so` from amneziawg-go
High-level, on Linux/WSL with Go + Android NDK:
```bash
git clone https://github.com/amnezia-vpn/amneziawg-go
cd amneziawg-go
# Add a small JNI export file that:
# - parses configJson
# - creates awg device with TUN fd
# - applies Jc/Jmin/Jmax/S1-S4/H1-H4/HeaderProtectionKey
# - runs device.Wait()
GOOS=android GOARCH=arm64 CGO_ENABLED=1 \
CC=$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android26-clang \
go build -buildmode=c-shared -o libawg.so ./jni
```
Place per ABI:
```text
android/app/src/main/jniLibs/arm64-v8a/libawg.so
android/app/src/main/jniLibs/x86_64/libawg.so # emulator
```
Then rebuild:
```bash
flutter build apk --release
```
## Kill-switch reality on Android
Android does not allow an app to silently enable **Always-on VPN** or
**Block connections without VPN**. Those are user-controlled system settings.
The app deep-links to `Settings.ACTION_VPN_SETTINGS`; the UI explains that both
must be enabled manually for a true fail-closed behavior.
`VpnService` itself captures all IPv4/IPv6 traffic while active and uses the
tunnel DNS; that prevents normal DNS leaks. If the native core dies, the TUN
remains and traffic is blackholed until Android tears the service down or the
user disconnects. This is intentionally fail-closed, not a silent fallback.

688
mobile-app/lib/main.dart Normal file
View file

@ -0,0 +1,688 @@
import 'package:flutter/material.dart';
import 'src/app_state.dart';
import 'src/models.dart';
const _bg = Color(0xFF05080B);
const _panel = Color(0xFF0C151D);
const _line = Color(0xFF1E303A);
const _cyan = Color(0xFF8FE3F5);
const _green = Color(0xFF8DFFAD);
const _muted = Color(0xFF91AAB7);
const _red = Color(0xFFFF8F9F);
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final state = AppState();
await state.initialize();
runApp(LdFdpiApp(state: state));
}
class LdFdpiApp extends StatelessWidget {
final AppState state;
const LdFdpiApp({super.key, required this.state});
@override
Widget build(BuildContext context) {
final scheme = ColorScheme.fromSeed(
seedColor: _cyan,
brightness: Brightness.dark,
).copyWith(
surface: _panel,
primary: _cyan,
secondary: _green,
error: _red,
);
return MaterialApp(
title: 'LD FDPI',
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
brightness: Brightness.dark,
colorScheme: scheme,
scaffoldBackgroundColor: _bg,
fontFamily: 'sans-serif',
textTheme: const TextTheme(
headlineLarge: TextStyle(fontWeight: FontWeight.w900, letterSpacing: -1.4),
headlineMedium: TextStyle(fontWeight: FontWeight.w800, letterSpacing: -0.8),
titleMedium: TextStyle(fontWeight: FontWeight.w700),
bodyMedium: TextStyle(color: _muted, height: 1.45),
bodySmall: TextStyle(color: _muted, height: 1.4),
),
),
home: HomeScreen(state: state),
);
}
}
class HomeScreen extends StatelessWidget {
final AppState state;
const HomeScreen({super.key, required this.state});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
const _Aurora(),
SafeArea(
child: ListenableBuilder(
listenable: state,
builder: (context, _) {
return ListView(
padding: const EdgeInsets.fromLTRB(20, 18, 20, 28),
children: [
_Header(onSettings: () => _openSettings(context)),
const SizedBox(height: 28),
_StatusOrb(state: state),
const SizedBox(height: 18),
Center(child: _statusLabel(state)),
const SizedBox(height: 6),
Center(
child: Text(
state.connecting
? 'El sıkışma bekleniyor...'
: state.connected
? 'Trafik tünelden geçiyor'
: 'Bağlanmaya hazır',
style: const TextStyle(color: _muted, fontSize: 12),
),
),
const SizedBox(height: 24),
_ConnectButton(state: state),
if (state.error != null) ...[
const SizedBox(height: 12),
_ErrorBox(message: state.error!),
],
const SizedBox(height: 22),
_InfoGrid(state: state),
const SizedBox(height: 12),
_ActivationCard(state: state),
const SizedBox(height: 12),
_SecurityCard(state: state),
const SizedBox(height: 12),
_Footer(),
],
);
},
),
),
],
),
);
}
void _openSettings(BuildContext context) {
Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => SettingsScreen(state: state)),
);
}
}
class _Header extends StatelessWidget {
final VoidCallback onSettings;
const _Header({required this.onSettings});
@override
Widget build(BuildContext context) {
return Row(
children: [
Container(
width: 38,
height: 38,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(11),
border: Border.all(color: _cyan.withOpacity(0.35)),
color: _cyan.withOpacity(0.08),
),
child: const Icon(Icons.shield_outlined, color: _cyan, size: 21),
),
const SizedBox(width: 11),
const Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('LD FDPI', style: TextStyle(fontWeight: FontWeight.w900, fontSize: 16, letterSpacing: -0.3)),
Text('MOBILE TUNNEL', style: TextStyle(color: _muted, fontSize: 9, letterSpacing: 2)),
],
),
),
IconButton(
onPressed: onSettings,
icon: const Icon(Icons.tune_rounded, color: _muted),
tooltip: 'Ayarlar',
),
],
);
}
}
class _StatusOrb extends StatelessWidget {
final AppState state;
const _StatusOrb({required this.state});
@override
Widget build(BuildContext context) {
final connected = state.connected;
final busy = state.connecting;
final color = connected ? _green : busy ? const Color(0xFFFFD27A) : _cyan;
return Center(
child: AnimatedContainer(
duration: const Duration(milliseconds: 450),
curve: Curves.easeOutCubic,
width: 196,
height: 196,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
colors: [
color.withOpacity(0.18),
color.withOpacity(0.04),
Colors.transparent,
],
stops: const [0.0, 0.55, 1.0],
),
border: Border.all(color: color.withOpacity(0.35), width: 1),
boxShadow: [
BoxShadow(color: color.withOpacity(0.14), blurRadius: 50, spreadRadius: 8),
],
),
child: Center(
child: AnimatedContainer(
duration: const Duration(milliseconds: 350),
width: 116,
height: 116,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _panel.withOpacity(0.9),
border: Border.all(color: color.withOpacity(0.45)),
),
child: busy
? Padding(
padding: const EdgeInsets.all(40),
child: CircularProgressIndicator(strokeWidth: 2, color: color),
)
: Icon(
connected ? Icons.shield_rounded : Icons.shield_outlined,
color: color,
size: 46,
),
),
),
),
);
}
}
Widget _statusLabel(AppState state) {
final text = state.connected
? 'BAĞLI'
: state.connecting
? 'BAĞLANIYOR'
: state.status.state == TunnelState.error
? 'HATA'
: 'BAĞLI DEĞİL';
final color = state.connected ? _green : state.connecting ? const Color(0xFFFFD27A) : _muted;
return Text(
text,
style: TextStyle(color: color, fontSize: 11, fontWeight: FontWeight.w800, letterSpacing: 3),
);
}
class _ConnectButton extends StatelessWidget {
final AppState state;
const _ConnectButton({required this.state});
@override
Widget build(BuildContext context) {
final disabled = state.busy;
if (state.connected) {
return SizedBox(
height: 54,
child: FilledButton.icon(
onPressed: disabled ? null : state.disconnect,
style: FilledButton.styleFrom(
backgroundColor: _panel,
foregroundColor: _red,
side: BorderSide(color: _red.withOpacity(0.35)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
),
icon: const Icon(Icons.power_settings_new_rounded),
label: const Text('BAĞLANTIYI KES', style: TextStyle(fontWeight: FontWeight.w800, letterSpacing: 0.6)),
),
);
}
return SizedBox(
height: 54,
child: FilledButton.icon(
onPressed: disabled ? null : state.connect,
style: FilledButton.styleFrom(
backgroundColor: _cyan,
foregroundColor: _bg,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
),
icon: const Icon(Icons.bolt_rounded),
label: const Text('BAĞLAN', style: TextStyle(fontWeight: FontWeight.w900, letterSpacing: 0.8)),
),
);
}
}
class _InfoGrid extends StatelessWidget {
final AppState state;
const _InfoGrid({required this.state});
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(child: _InfoTile(label: 'ATANAN IP', value: state.address, icon: Icons.lan_outlined)),
const SizedBox(width: 10),
Expanded(child: _InfoTile(label: 'ÇIKIŞ', value: state.endpoint, icon: Icons.public_rounded)),
],
);
}
}
class _InfoTile extends StatelessWidget {
final String label;
final String value;
final IconData icon;
const _InfoTile({required this.label, required this.value, required this.icon});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: _panel,
borderRadius: BorderRadius.circular(14),
border: Border.all(color: _line),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(icon, size: 13, color: _cyan),
const SizedBox(width: 6),
Text(label, style: const TextStyle(color: _muted, fontSize: 8, letterSpacing: 1.3)),
],
),
const SizedBox(height: 8),
Text(
value,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontFamily: 'monospace', fontSize: 11, fontWeight: FontWeight.w700),
),
],
),
);
}
}
class _ActivationCard extends StatelessWidget {
final AppState state;
const _ActivationCard({required this.state});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: _panel,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: _line),
),
child: Row(
children: [
const Icon(Icons.key_rounded, color: _cyan, size: 20),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(state.hasConfig ? 'Cihaz kayıtlı' : 'Etkinleştirme gerekli',
style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 12)),
const SizedBox(height: 3),
Text(
state.hasConfig
? 'Kimlik bu cihazda şifreli saklanıyor.'
: 'Tek kullanımlık kodunu gir, tüneli aç.',
style: const TextStyle(color: _muted, fontSize: 10.5),
),
],
),
),
TextButton(
onPressed: () => _showEnrollment(context),
child: Text(state.hasConfig ? 'YENİLE' : 'KOD GİR', style: const TextStyle(fontSize: 10, fontWeight: FontWeight.w800)),
),
],
),
);
}
void _showEnrollment(BuildContext context) {
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
backgroundColor: _panel,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(22))),
builder: (sheetContext) => Padding(
padding: EdgeInsets.only(bottom: MediaQuery.of(sheetContext).viewInsets.bottom),
child: _EnrollmentSheet(state: state),
),
);
}
}
class _EnrollmentSheet extends StatefulWidget {
final AppState state;
const _EnrollmentSheet({required this.state});
@override
State<_EnrollmentSheet> createState() => _EnrollmentSheetState();
}
class _EnrollmentSheetState extends State<_EnrollmentSheet> {
final _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(20, 18, 20, 24),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Etkinleştirme kodu', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w900)),
const SizedBox(height: 6),
const Text('Kod tek kullanımlık ve bu cihaza bağlanır.', style: TextStyle(color: _muted, fontSize: 12)),
const SizedBox(height: 18),
TextField(
controller: _controller,
autofocus: true,
textCapitalization: TextCapitalization.characters,
style: const TextStyle(fontFamily: 'monospace', letterSpacing: 1),
decoration: InputDecoration(
hintText: 'LDFDPI-XXXX-XXXX-XXXX',
filled: true,
fillColor: _bg,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _line)),
enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _line)),
focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _cyan)),
),
onSubmitted: (_) => _submit(),
),
if (widget.state.error != null) ...[
const SizedBox(height: 10),
Text(widget.state.error!, style: const TextStyle(color: _red, fontSize: 11)),
],
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
height: 48,
child: ListenableBuilder(
listenable: widget.state,
builder: (context, _) {
return FilledButton(
onPressed: widget.state.busy ? null : _submit,
style: FilledButton.styleFrom(backgroundColor: _cyan, foregroundColor: _bg, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),
child: widget.state.busy
? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: _bg))
: const Text('KAYDI TAMAMLA', style: TextStyle(fontWeight: FontWeight.w900, letterSpacing: 0.6)),
);
},
),
),
],
),
);
}
Future<void> _submit() async {
await widget.state.enroll(_controller.text);
if (widget.state.hasConfig && mounted) Navigator.of(context).pop();
}
}
class _SecurityCard extends StatelessWidget {
final AppState state;
const _SecurityCard({required this.state});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: _panel,
borderRadius: BorderRadius.circular(16),
border: Border.all(color: _line),
),
child: Column(
children: [
_SecurityRow(icon: Icons.dns_outlined, label: 'DNS', value: state.config?.dns.join(', ') ?? '1.1.1.1'),
const SizedBox(height: 10),
_SecurityRow(icon: Icons.speed_rounded, label: 'GECİKME', value: state.pingMs == null ? '—' : '${state.pingMs} ms'),
const SizedBox(height: 10),
_SecurityRow(icon: Icons.block_rounded, label: 'SIZINTI', value: state.connected ? 'KORUMALI' : 'PASİF'),
],
),
);
}
}
class _SecurityRow extends StatelessWidget {
final IconData icon;
final String label;
final String value;
const _SecurityRow({required this.icon, required this.label, required this.value});
@override
Widget build(BuildContext context) {
return Row(
children: [
Icon(icon, size: 15, color: _cyan),
const SizedBox(width: 9),
Text(label, style: const TextStyle(color: _muted, fontSize: 9, letterSpacing: 1.1)),
const Spacer(),
Flexible(
child: Text(
value,
textAlign: TextAlign.right,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontFamily: 'monospace', fontSize: 10.5, color: Color(0xFFD8ECF2)),
),
),
],
);
}
}
class _ErrorBox extends StatelessWidget {
final String message;
const _ErrorBox({required this.message});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: _red.withOpacity(0.07),
border: Border.all(color: _red.withOpacity(0.3)),
borderRadius: BorderRadius.circular(11),
),
child: Text(message, style: const TextStyle(color: _red, fontSize: 11)),
);
}
}
class _Footer extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.only(top: 8),
child: Text(
'LD FDPI v0.1.0 · Android VpnService · AES-GCM secure storage',
textAlign: TextAlign.center,
style: TextStyle(color: Color(0xFF536B77), fontSize: 9),
),
);
}
}
class _Aurora extends StatelessWidget {
const _Aurora();
@override
Widget build(BuildContext context) {
return IgnorePointer(
child: Stack(
children: [
Positioned(
top: -180,
right: -120,
child: Container(
width: 420,
height: 420,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(colors: [_cyan.withOpacity(0.13), Colors.transparent]),
),
),
),
Positioned(
bottom: -220,
left: -160,
child: Container(
width: 460,
height: 460,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(colors: [_green.withOpacity(0.06), Colors.transparent]),
),
),
),
],
),
);
}
}
class SettingsScreen extends StatelessWidget {
final AppState state;
const SettingsScreen({super.key, required this.state});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: _bg,
title: const Text('Ayarlar', style: TextStyle(fontWeight: FontWeight.w800)),
leading: IconButton(onPressed: () => Navigator.pop(context), icon: const Icon(Icons.arrow_back_rounded)),
),
body: ListenableBuilder(
listenable: state,
builder: (context, _) => ListView(
padding: const EdgeInsets.all(20),
children: [
_SettingsCard(
title: 'Tünel',
rows: [
_SettingsRow('Sunucu', state.config?.endpoint ?? '—'),
_SettingsRow('Adres', state.config?.address ?? '—'),
_SettingsRow('DNS', state.config?.dns.join(', ') ?? '1.1.1.1'),
_SettingsRow('AmneziaWG', state.config == null ? '—' : 'Jc ${state.config!.awg.jc} · S1 ${state.config!.awg.s1}'),
],
),
const SizedBox(height: 12),
_SettingsCard(
title: 'Sızıntı koruması',
rows: const [
_SettingsRow('VPN', 'Android VpnService'),
_SettingsRow('DNS', 'Tünel içi 1.1.1.1 / 1.0.0.1'),
_SettingsRow('Kill-switch', 'Always-on VPN + Block without VPN'),
],
),
const SizedBox(height: 10),
FilledButton.tonalIcon(
onPressed: state.openVpnSettings,
icon: const Icon(Icons.open_in_new_rounded, size: 17),
label: const Text('Android VPN ayarlarını aç'),
),
const SizedBox(height: 8),
const Text(
'Android, “Always-on VPN” ve “Block connections without VPN” ayarlarını uygulama adına açmaya izin vermez. Ayarlar ekranından kullanıcı tarafından açılmalıdır.',
style: TextStyle(color: _muted, fontSize: 10.5, height: 1.45),
),
const SizedBox(height: 22),
const _SettingsCard(
title: 'Uygulama',
rows: [
_SettingsRow('Sürüm', '0.1.0'),
_SettingsRow('Depolama', 'EncryptedSharedPreferences'),
_SettingsRow('Kimlik', 'X25519 · cihaz başına'),
],
),
],
),
),
);
}
}
class _SettingsCard extends StatelessWidget {
final String title;
final List<Widget> rows;
const _SettingsCard({required this.title, required this.rows});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(color: _panel, borderRadius: BorderRadius.circular(16), border: Border.all(color: _line)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title.toUpperCase(), style: const TextStyle(color: _muted, fontSize: 9, letterSpacing: 1.4, fontWeight: FontWeight.w700)),
const SizedBox(height: 10),
...rows,
],
),
);
}
}
class _SettingsRow extends StatelessWidget {
final String label;
final String value;
const _SettingsRow(this.label, this.value);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Row(
children: [
Expanded(child: Text(label, style: const TextStyle(fontSize: 11.5, color: _muted))),
Flexible(
child: Text(
value,
textAlign: TextAlign.right,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontFamily: 'monospace', fontSize: 10.5, color: Color(0xFFD8ECF2)),
),
),
],
),
);
}
}

View file

@ -0,0 +1,94 @@
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'models.dart';
class EnrollmentException implements Exception {
final String message;
const EnrollmentException(this.message);
@override
String toString() => message;
}
class EnrollmentApi {
static const endpoint = 'https://ttmadethat.shop/api/v1/enroll';
final http.Client _client;
EnrollmentApi([http.Client? client]) : _client = client ?? http.Client();
Future<VpnConfig> enroll({
required String token,
required String publicKey,
required String deviceId,
required String privateKey,
}) async {
late final http.Response response;
try {
response = await _client
.post(
Uri.parse(endpoint),
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: jsonEncode({
'public_key': publicKey,
'device_id': deviceId,
'client_version': 'android-0.1.0',
}),
)
.timeout(const Duration(seconds: 20));
} on SocketException {
throw const EnrollmentException('Sunucuya ulaşılamadı. İnterneti kontrol et.');
} on HttpException {
throw const EnrollmentException('Sunucu bağlantısı kesildi.');
} catch (_) {
throw const EnrollmentException('Enrollment zaman aşımına uğradı.');
}
if (response.statusCode == 409) {
throw const EnrollmentException('Bu kod başka bir cihazda kullanılmış.');
}
if (response.statusCode == 401) {
throw const EnrollmentException('Etkinleştirme kodu geçersiz.');
}
if (response.statusCode == 429) {
throw const EnrollmentException('Çok fazla deneme. Bir dakika sonra tekrar dene.');
}
if (response.statusCode != 200) {
throw EnrollmentException('Enrollment başarısız (HTTP ${response.statusCode}).');
}
final Object? decoded;
try {
decoded = jsonDecode(response.body);
} catch (_) {
throw const EnrollmentException('Sunucu geçersiz yanıt döndürdü.');
}
if (decoded is! Map<String, dynamic>) {
throw const EnrollmentException('Sunucu geçersiz yanıt döndürdü.');
}
if ((decoded['server_public_key'] ?? '').toString().isEmpty) {
throw const EnrollmentException('Sunucu public key döndürmedi.');
}
return VpnConfig.fromEnrollment(decoded, privateKey: privateKey, deviceId: deviceId);
}
Future<int?> ping() async {
final watch = Stopwatch()..start();
try {
final socket = await Socket.connect('1.1.1.1', 443, timeout: const Duration(milliseconds: 1500));
socket.destroy();
watch.stop();
return watch.elapsedMilliseconds;
} catch (_) {
return null;
}
}
void close() => _client.close();
}

View file

@ -0,0 +1,181 @@
import 'dart:async';
import 'dart:convert';
import 'package:cryptography/cryptography.dart';
import 'package:flutter/foundation.dart';
import 'api.dart';
import 'models.dart';
import 'secure_store.dart';
import 'tunnel.dart';
class AppState extends ChangeNotifier {
final SecureStore _store = SecureStore();
final EnrollmentApi _api = EnrollmentApi();
final TunnelPlatform _tunnel = TunnelPlatform();
VpnConfig? config;
TunnelStatus status = TunnelStatus.disconnected;
bool initialized = false;
bool busy = false;
String? error;
String? publicKey;
int? pingMs;
Timer? _statusTimer;
bool get hasConfig => config != null;
bool get connected => status.connected;
bool get connecting => status.busy || busy;
String get address => status.address ?? config?.address ?? '—';
String get endpoint => status.endpoint ?? config?.endpoint ?? '—';
Future<void> initialize() async {
try {
config = await _store.readConfig();
publicKey = await _readPublicKey();
if (config != null) {
status = await _tunnel.status();
}
} catch (e) {
error = 'Yerel kimlik okunamadı: $e';
} finally {
initialized = true;
notifyListeners();
_startPolling();
}
}
Future<String?> _readPublicKey() async {
final raw = await _store.readPrivateKey();
if (raw == null) return null;
try {
final algorithm = X25519();
final keyPair = await algorithm.newKeyPairFromSeed(base64Decode(raw));
final pub = await keyPair.extractPublicKey();
return base64Encode(pub.bytes);
} catch (_) {
return null;
}
}
Future<void> enroll(String token) async {
final clean = token.trim();
if (clean.isEmpty) {
error = 'Etkinleştirme kodu boş olamaz.';
notifyListeners();
return;
}
busy = true;
error = null;
notifyListeners();
try {
var privateKey = await _store.readPrivateKey();
if (privateKey == null) {
final algorithm = X25519();
final keyPair = await algorithm.newKeyPair();
final privateBytes = await keyPair.extractPrivateKeyBytes();
privateKey = base64Encode(privateBytes);
await _store.writePrivateKey(privateKey);
}
final algorithm = X25519();
final keyPair = await algorithm.newKeyPairFromSeed(base64Decode(privateKey));
final public = await keyPair.extractPublicKey();
publicKey = base64Encode(public.bytes);
final deviceId = await _store.deviceId();
final enrolled = await _api.enroll(
token: clean,
publicKey: publicKey!,
deviceId: deviceId,
privateKey: privateKey,
);
await _store.writeConfig(enrolled);
config = enrolled;
status = await _tunnel.status();
await refreshPing();
} on EnrollmentException catch (e) {
error = e.message;
} catch (e) {
error = 'Kayıt tamamlanamadı: $e';
} finally {
busy = false;
notifyListeners();
}
}
Future<void> connect() async {
final cfg = config;
if (cfg == null) {
error = 'Önce etkinleştirme kodunu gir.';
notifyListeners();
return;
}
busy = true;
error = null;
notifyListeners();
try {
if (!await _tunnel.prepare()) {
error = 'Android VPN izni verilmedi. Tekrar dene ve sistem onayını kabul et.';
return;
}
await _tunnel.start(cfg);
status = await _tunnel.status();
await refreshPing();
} catch (e) {
error = 'Tünel başlatılamadı: $e';
status = TunnelStatus(state: TunnelState.error, error: error);
} finally {
busy = false;
notifyListeners();
}
}
Future<void> disconnect() async {
busy = true;
error = null;
notifyListeners();
try {
await _tunnel.stop();
status = await _tunnel.status();
} catch (e) {
error = 'Tünel kapatılamadı: $e';
} finally {
busy = false;
notifyListeners();
}
}
Future<void> refreshStatus() async {
try {
status = await _tunnel.status();
notifyListeners();
} catch (_) {}
}
Future<void> refreshPing() async {
pingMs = await _api.ping();
notifyListeners();
}
Future<void> openVpnSettings() => _tunnel.openVpnSettings();
void _startPolling() {
_statusTimer?.cancel();
_statusTimer = Timer.periodic(const Duration(seconds: 2), (_) async {
if (!initialized) return;
try {
final next = await _tunnel.status();
if (next.state != status.state || next.address != status.address) {
status = next;
notifyListeners();
}
} catch (_) {}
});
}
@override
void dispose() {
_statusTimer?.cancel();
_api.close();
super.dispose();
}
}

View file

@ -0,0 +1,204 @@
import 'dart:convert';
class AwgParams {
final int jc;
final int jmin;
final int jmax;
final int s1;
final int s2;
final int s3;
final int s4;
final int h1;
final int h2;
final int h3;
final int h4;
final String headerProtectionKey;
final String rekeyAfter;
final String rekeyTimeout;
final String rejectAfter;
final String keepalive;
final bool randomTrailers;
final bool disableCookies;
const AwgParams({
this.jc = 5,
this.jmin = 10,
this.jmax = 50,
this.s1 = 12,
this.s2 = 12,
this.s3 = 12,
this.s4 = 12,
this.h1 = 1,
this.h2 = 2,
this.h3 = 3,
this.h4 = 4,
this.headerProtectionKey = '',
this.rekeyAfter = '100-120',
this.rekeyTimeout = '3-7',
this.rejectAfter = '150-180',
this.keepalive = '5-15',
this.randomTrailers = true,
this.disableCookies = true,
});
factory AwgParams.fromJson(Map<String, dynamic>? json) {
final j = json ?? const <String, dynamic>{};
int readInt(String key, int fallback) {
final value = j[key];
if (value is num) return value.toInt();
if (value is String) return int.tryParse(value) ?? fallback;
return fallback;
}
return AwgParams(
jc: readInt('jc', 5),
jmin: readInt('jmin', 10),
jmax: readInt('jmax', 50),
s1: readInt('s1', 12),
s2: readInt('s2', 12),
s3: readInt('s3', 12),
s4: readInt('s4', 12),
h1: readInt('h1', 1),
h2: readInt('h2', 2),
h3: readInt('h3', 3),
h4: readInt('h4', 4),
headerProtectionKey: (j['header_protection_key'] ?? j['headerProtectionKey'] ?? '').toString(),
rekeyAfter: (j['rekey_after_time'] ?? '100-120').toString(),
rekeyTimeout: (j['rekey_timeout'] ?? '3-7').toString(),
rejectAfter: (j['reject_after_time'] ?? '150-180').toString(),
keepalive: (j['keepalive_timeout'] ?? '5-15').toString(),
randomTrailers: j['random_trailers'] != false,
disableCookies: j['disable_cookies'] != false,
);
}
Map<String, dynamic> toJson() => {
'jc': jc,
'jmin': jmin,
'jmax': jmax,
's1': s1,
's2': s2,
's3': s3,
's4': s4,
'h1': h1,
'h2': h2,
'h3': h3,
'h4': h4,
'header_protection_key': headerProtectionKey,
'rekey_after_time': rekeyAfter,
'rekey_timeout': rekeyTimeout,
'reject_after_time': rejectAfter,
'keepalive_timeout': keepalive,
'random_trailers': randomTrailers,
'disable_cookies': disableCookies,
};
}
class VpnConfig {
final String address;
final List<String> dns;
final String endpoint;
final String serverPublicKey;
final String presharedKey;
final List<String> allowedIps;
final AwgParams awg;
final String privateKey;
final String deviceId;
const VpnConfig({
required this.address,
required this.dns,
required this.endpoint,
required this.serverPublicKey,
required this.presharedKey,
required this.allowedIps,
required this.awg,
required this.privateKey,
required this.deviceId,
});
factory VpnConfig.fromEnrollment(
Map<String, dynamic> json, {
required String privateKey,
required String deviceId,
}) {
final dns = (json['dns'] as List?)?.map((e) => e.toString()).toList() ?? <String>['1.1.1.1'];
final allowed = (json['allowed_ips'] as List?)?.map((e) => e.toString()).toList() ??
<String>['0.0.0.0/0', '::/0'];
return VpnConfig(
address: (json['address'] ?? '10.8.1.2/32').toString(),
dns: dns.isEmpty ? <String>['1.1.1.1'] : dns,
endpoint: (json['endpoint'] ?? '116.202.14.171:42771').toString(),
serverPublicKey: (json['server_public_key'] ?? '').toString(),
presharedKey: (json['preshared_key'] ?? '').toString(),
allowedIps: allowed,
awg: AwgParams.fromJson(json['awg'] as Map<String, dynamic>?),
privateKey: privateKey,
deviceId: deviceId,
);
}
Map<String, dynamic> toJson() => {
'address': address,
'dns': dns,
'endpoint': endpoint,
'server_public_key': serverPublicKey,
'preshared_key': presharedKey,
'allowed_ips': allowedIps,
'awg': awg.toJson(),
'private_key': privateKey,
'device_id': deviceId,
};
factory VpnConfig.fromJson(Map<String, dynamic> json) => VpnConfig(
address: json['address'].toString(),
dns: (json['dns'] as List).map((e) => e.toString()).toList(),
endpoint: json['endpoint'].toString(),
serverPublicKey: json['server_public_key'].toString(),
presharedKey: json['preshared_key'].toString(),
allowedIps: (json['allowed_ips'] as List).map((e) => e.toString()).toList(),
awg: AwgParams.fromJson(json['awg'] as Map<String, dynamic>?),
privateKey: json['private_key'].toString(),
deviceId: json['device_id'].toString(),
);
String toTunnelJson() => jsonEncode(toJson());
}
enum TunnelState { disconnected, connecting, connected, error }
class TunnelStatus {
final TunnelState state;
final String? address;
final String? endpoint;
final String? error;
const TunnelStatus({
required this.state,
this.address,
this.endpoint,
this.error,
});
static const disconnected = TunnelStatus(state: TunnelState.disconnected);
bool get connected => state == TunnelState.connected;
bool get busy => state == TunnelState.connecting;
factory TunnelStatus.fromMap(Object? value) {
if (value is! Map) return disconnected;
final raw = (value['state'] ?? 'disconnected').toString();
final state = switch (raw) {
'connected' => TunnelState.connected,
'connecting' => TunnelState.connecting,
'error' => TunnelState.error,
_ => TunnelState.disconnected,
};
return TunnelStatus(
state: state,
address: value['address']?.toString(),
endpoint: value['endpoint']?.toString(),
error: value['error']?.toString(),
);
}
}

View file

@ -0,0 +1,57 @@
import 'dart:convert';
import 'dart:math';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'models.dart';
/// Android implementation uses EncryptedSharedPreferences through
/// flutter_secure_storage (AES-256-GCM, Keystore-backed master key).
class SecureStore {
static const _configKey = 'ld_fdpi.config.v1';
static const _privateKey = 'ld_fdpi.private_key.v1';
static const _deviceIdKey = 'ld_fdpi.device_id.v1';
final FlutterSecureStorage _storage;
SecureStore([FlutterSecureStorage? storage])
: _storage = storage ??
const FlutterSecureStorage(
aOptions: AndroidOptions(encryptedSharedPreferences: true),
);
Future<String?> readPrivateKey() => _storage.read(key: _privateKey);
Future<void> writePrivateKey(String value) => _storage.write(key: _privateKey, value: value);
Future<String?> readDeviceId() => _storage.read(key: _deviceIdKey);
Future<void> writeDeviceId(String value) => _storage.write(key: _deviceIdKey, value: value);
Future<VpnConfig?> readConfig() async {
final raw = await _storage.read(key: _configKey);
if (raw == null || raw.isEmpty) return null;
try {
final map = jsonDecode(raw) as Map<String, dynamic>;
return VpnConfig.fromJson(map);
} catch (_) {
await clearConfig();
return null;
}
}
Future<void> writeConfig(VpnConfig config) =>
_storage.write(key: _configKey, value: jsonEncode(config.toJson()));
Future<void> clearConfig() => _storage.delete(key: _configKey);
Future<String> deviceId() async {
final existing = await readDeviceId();
if (existing != null && existing.length == 64) return existing;
final random = Random.secure();
final id = List<int>.generate(32, (_) => random.nextInt(256))
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join();
await writeDeviceId(id);
return id;
}
}

View file

@ -0,0 +1,36 @@
import 'package:flutter/services.dart';
import 'models.dart';
class TunnelPlatform {
static const _channel = MethodChannel('ld_fdpi/native');
Future<bool> prepare() async {
final value = await _channel.invokeMethod<bool>('requestVpnPermission');
return value == true;
}
Future<void> start(VpnConfig config) async {
await _channel.invokeMethod<void>('startTunnel', {
'config': config.toTunnelJson(),
});
}
Future<void> stop() async {
await _channel.invokeMethod<void>('stopTunnel');
}
Future<TunnelStatus> status() async {
final value = await _channel.invokeMethod<Object?>('status');
return TunnelStatus.fromMap(value);
}
Future<void> openVpnSettings() async {
await _channel.invokeMethod<void>('openVpnSettings');
}
Future<int?> ping() async {
final value = await _channel.invokeMethod<int>('ping');
return value;
}
}

410
mobile-app/pubspec.lock Normal file
View file

@ -0,0 +1,410 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
async:
dependency: transitive
description:
name: async
sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63
url: "https://pub.dev"
source: hosted
version: "2.12.0"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
characters:
dependency: transitive
description:
name: characters
sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803
url: "https://pub.dev"
source: hosted
version: "1.4.0"
clock:
dependency: transitive
description:
name: clock
sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b
url: "https://pub.dev"
source: hosted
version: "1.1.2"
collection:
dependency: transitive
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
url: "https://pub.dev"
source: hosted
version: "1.19.1"
crypto:
dependency: transitive
description:
name: crypto
sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4
url: "https://pub.dev"
source: hosted
version: "3.0.8"
cryptography:
dependency: "direct main"
description:
name: cryptography
sha256: "3eda3029d34ec9095a27a198ac9785630fe525c0eb6a49f3d575272f8e792ef0"
url: "https://pub.dev"
source: hosted
version: "2.9.0"
cupertino_icons:
dependency: "direct main"
description:
name: cupertino_icons
sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6
url: "https://pub.dev"
source: hosted
version: "1.0.8"
fake_async:
dependency: transitive
description:
name: fake_async
sha256: "6a95e56b2449df2273fd8c45a662d6947ce1ebb7aafe80e550a3f68297f3cacc"
url: "https://pub.dev"
source: hosted
version: "1.3.2"
ffi:
dependency: transitive
description:
name: ffi
sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"
url: "https://pub.dev"
source: hosted
version: "2.2.0"
flutter:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_lints:
dependency: "direct dev"
description:
name: flutter_lints
sha256: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c"
url: "https://pub.dev"
source: hosted
version: "4.0.0"
flutter_secure_storage:
dependency: "direct main"
description:
name: flutter_secure_storage
sha256: "9cad52d75ebc511adfae3d447d5d13da15a55a92c9410e50f67335b6d21d16ea"
url: "https://pub.dev"
source: hosted
version: "9.2.4"
flutter_secure_storage_linux:
dependency: transitive
description:
name: flutter_secure_storage_linux
sha256: be76c1d24a97d0b98f8b54bce6b481a380a6590df992d0098f868ad54dc8f688
url: "https://pub.dev"
source: hosted
version: "1.2.3"
flutter_secure_storage_macos:
dependency: transitive
description:
name: flutter_secure_storage_macos
sha256: "6c0a2795a2d1de26ae202a0d78527d163f4acbb11cde4c75c670f3a0fc064247"
url: "https://pub.dev"
source: hosted
version: "3.1.3"
flutter_secure_storage_platform_interface:
dependency: transitive
description:
name: flutter_secure_storage_platform_interface
sha256: cf91ad32ce5adef6fba4d736a542baca9daf3beac4db2d04be350b87f69ac4a8
url: "https://pub.dev"
source: hosted
version: "1.1.2"
flutter_secure_storage_web:
dependency: transitive
description:
name: flutter_secure_storage_web
sha256: f4ebff989b4f07b2656fb16b47852c0aab9fed9b4ec1c70103368337bc1886a9
url: "https://pub.dev"
source: hosted
version: "1.2.1"
flutter_secure_storage_windows:
dependency: transitive
description:
name: flutter_secure_storage_windows
sha256: b20b07cb5ed4ed74fc567b78a72936203f587eba460af1df11281c9326cd3709
url: "https://pub.dev"
source: hosted
version: "3.1.2"
flutter_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
flutter_web_plugins:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
http:
dependency: "direct main"
description:
name: http
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
url: "https://pub.dev"
source: hosted
version: "1.6.0"
http_parser:
dependency: transitive
description:
name: http_parser
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev"
source: hosted
version: "4.1.2"
js:
dependency: transitive
description:
name: js
sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3
url: "https://pub.dev"
source: hosted
version: "0.6.7"
leak_tracker:
dependency: transitive
description:
name: leak_tracker
sha256: c35baad643ba394b40aac41080300150a4f08fd0fd6a10378f8f7c6bc161acec
url: "https://pub.dev"
source: hosted
version: "10.0.8"
leak_tracker_flutter_testing:
dependency: transitive
description:
name: leak_tracker_flutter_testing
sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573
url: "https://pub.dev"
source: hosted
version: "3.0.9"
leak_tracker_testing:
dependency: transitive
description:
name: leak_tracker_testing
sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"
url: "https://pub.dev"
source: hosted
version: "3.0.1"
lints:
dependency: transitive
description:
name: lints
sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235"
url: "https://pub.dev"
source: hosted
version: "4.0.0"
matcher:
dependency: transitive
description:
name: matcher
sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2
url: "https://pub.dev"
source: hosted
version: "0.12.17"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec
url: "https://pub.dev"
source: hosted
version: "0.11.1"
meta:
dependency: transitive
description:
name: meta
sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
url: "https://pub.dev"
source: hosted
version: "1.16.0"
path:
dependency: transitive
description:
name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
url: "https://pub.dev"
source: hosted
version: "1.9.1"
path_provider:
dependency: transitive
description:
name: path_provider
sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
url: "https://pub.dev"
source: hosted
version: "2.1.5"
path_provider_android:
dependency: transitive
description:
name: path_provider_android
sha256: "3b4c1fc3aa55ddc9cd4aa6759984330d5c8e66aa7702a6223c61540dc6380c37"
url: "https://pub.dev"
source: hosted
version: "2.2.19"
path_provider_foundation:
dependency: transitive
description:
name: path_provider_foundation
sha256: "16eef174aacb07e09c351502740fa6254c165757638eba1e9116b0a781201bbd"
url: "https://pub.dev"
source: hosted
version: "2.4.2"
path_provider_linux:
dependency: transitive
description:
name: path_provider_linux
sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279
url: "https://pub.dev"
source: hosted
version: "2.2.1"
path_provider_platform_interface:
dependency: transitive
description:
name: path_provider_platform_interface
sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
path_provider_windows:
dependency: transitive
description:
name: path_provider_windows
sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
url: "https://pub.dev"
source: hosted
version: "2.3.0"
platform:
dependency: transitive
description:
name: platform
sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984"
url: "https://pub.dev"
source: hosted
version: "3.1.6"
plugin_platform_interface:
dependency: transitive
description:
name: plugin_platform_interface
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
url: "https://pub.dev"
source: hosted
version: "2.1.8"
sky_engine:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
source_span:
dependency: transitive
description:
name: source_span
sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c"
url: "https://pub.dev"
source: hosted
version: "1.10.1"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
url: "https://pub.dev"
source: hosted
version: "1.12.1"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
string_scanner:
dependency: transitive
description:
name: string_scanner
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
url: "https://pub.dev"
source: hosted
version: "1.2.2"
test_api:
dependency: transitive
description:
name: test_api
sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd
url: "https://pub.dev"
source: hosted
version: "0.7.4"
typed_data:
dependency: transitive
description:
name: typed_data
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
url: "https://pub.dev"
source: hosted
version: "1.4.0"
vector_math:
dependency: transitive
description:
name: vector_math
sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
vm_service:
dependency: transitive
description:
name: vm_service
sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14"
url: "https://pub.dev"
source: hosted
version: "14.3.1"
web:
dependency: transitive
description:
name: web
sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a"
url: "https://pub.dev"
source: hosted
version: "1.1.1"
win32:
dependency: transitive
description:
name: win32
sha256: "329edf97fdd893e0f1e3b9e88d6a0e627128cc17cc316a8d67fda8f1451178ba"
url: "https://pub.dev"
source: hosted
version: "5.13.0"
xdg_directories:
dependency: transitive
description:
name: xdg_directories
sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
sdks:
dart: ">=3.7.0 <4.0.0"
flutter: ">=3.29.0"

23
mobile-app/pubspec.yaml Normal file
View file

@ -0,0 +1,23 @@
name: ld_fdpi_mobile
description: LD FDPI Android client — AmneziaWG tunnel, enrollment and leak protection.
publish_to: "none"
version: 0.1.0+1
environment:
sdk: ">=3.4.0 <4.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.8
http: ^1.2.2
cryptography: ^2.7.0
flutter_secure_storage: ^9.2.4
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^4.0.0
flutter:
uses-material-design: true

3782
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

39
package.json Normal file
View file

@ -0,0 +1,39 @@
{
"name": "ld-fdpi",
"private": true,
"version": "1.7.0",
"description": "LD FDPI - zero-touch AmneziaWG VPN and SpoofDPI DPI bypass for Windows (Tauri v2, Rust, React)",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"tauri": "node scripts/tauri.js",
"check:rust": "node scripts/cargo.js check",
"setup:sidecar": "node scripts/download-sidecar.js",
"icon:make": "node scripts/make-icon.mjs",
"test": "node scripts/verify-all.mjs",
"test:gui": "node scripts/e2e-gui.mjs"
},
"dependencies": {
"@tauri-apps/api": "^2.2.0",
"@tauri-apps/plugin-updater": "^2.14.1",
"dompurify": "^3.2.3",
"lucide-react": "^0.474.0",
"qrcode.react": "^4.2.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@tauri-apps/cli": "^2.2.0",
"@types/dompurify": "^3.0.5",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"postcss": "^8.5.1",
"sharp": "^0.35.5",
"tailwindcss": "^3.4.17",
"vite": "^6.0.7"
}
}

6
postcss.config.js Normal file
View file

@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

BIN
public/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 241 KiB

18
scripts/cargo.js Normal file
View file

@ -0,0 +1,18 @@
/**
* `npm run check:rust <args>` / `npm run build:rust` wrapper.
* Runs Cargo inside src-tauri with a space-free CARGO_TARGET_DIR.
*/
import { spawnSync } from "node:child_process";
import path from "node:path";
import { ROOT, resolveTargetDir } from "./target-dir.js";
const cargo = process.env.CARGO || "cargo";
const targetDir = resolveTargetDir();
const result = spawnSync(cargo, process.argv.slice(2), {
stdio: "inherit",
cwd: path.join(ROOT, "src-tauri"),
env: { ...process.env, CARGO_TARGET_DIR: targetDir },
});
process.exit(result.status ?? 1);

117
scripts/download-sidecar.js Normal file
View file

@ -0,0 +1,117 @@
/**
* LD FDPI — fetch the *real* SpoofDPI Windows x64 engine.
*
* There is no stub branch: this script either installs a verified official binary
* (SpoofDPI 0.12.2, the last release that ships a Windows build) or exits with an
* error. The old version silently wrote a 32-byte "MZ-...-STUB" file, which made
* `tauri build` succeed while the application could never bypass anything.
*
* Usage: npm run setup:sidecar [-- --force]
*/
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, "..");
const BIN_DIR = path.join(ROOT, "src-tauri", "binaries");
const VERSION = "0.12.2";
const ASSET_URL = `https://github.com/xvzc/spoofdpi/releases/download/v${VERSION}/spoofdpi-windows-amd64.exe`;
// SHA-256 of the official release asset (computed from the downloaded v0.12.2 exe).
const SHA256 = "16a5c81265d908d31aaf9be69d577ec91588282ae5c366cc73e8bff878a3ea5e";
const MIN_SIZE = 1_500_000;
const TARGETS = [
path.join(BIN_DIR, "spoofdpi-x86_64-pc-windows-gnu.exe"),
path.join(BIN_DIR, "spoofdpi-x86_64-pc-windows-msvc.exe"),
];
const force = process.argv.includes("--force");
function sha256(file) {
return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
}
function isValid(file) {
try {
const stat = fs.statSync(file);
if (!stat.isFile() || stat.size < MIN_SIZE) return false;
const fd = fs.openSync(file, "r");
const header = Buffer.alloc(2);
fs.readSync(fd, header, 0, 2, 0);
fs.closeSync(fd);
return header[0] === 0x4d && header[1] === 0x5a && sha256(file) === SHA256;
} catch {
return false;
}
}
function printVersion(file) {
try {
execFileSync(file, ["-v"], { stdio: "inherit", windowsHide: true });
return true;
} catch (error) {
console.error("[LD FDPI] Binary could not be executed:", error.message);
return false;
}
}
fs.mkdirSync(BIN_DIR, { recursive: true });
fs.writeFileSync(path.join(BIN_DIR, ".gitkeep"), "");
if (!force && TARGETS.every(isValid)) {
console.log("[LD FDPI] Verified SpoofDPI", VERSION, "is already installed.");
printVersion(TARGETS[0]);
process.exit(0);
}
for (const existing of TARGETS) {
if (fs.existsSync(existing) && fs.statSync(existing).size < MIN_SIZE) {
console.warn("[LD FDPI] Removing placeholder sidecar:", existing);
fs.unlinkSync(existing);
}
}
const tempFile = path.join(BIN_DIR, `spoofdpi-${VERSION}.download.exe`);
console.log("[LD FDPI] Downloading official SpoofDPI", VERSION, "Windows x64 engine...");
console.log(" ", ASSET_URL);
const response = await fetch(ASSET_URL, { redirect: "follow" });
if (!response.ok) {
console.error(`[LD FDPI] Download failed: HTTP ${response.status} ${response.statusText}`);
process.exit(1);
}
const buffer = Buffer.from(await response.arrayBuffer());
fs.writeFileSync(tempFile, buffer);
const digest = sha256(tempFile);
if (digest !== SHA256) {
fs.unlinkSync(tempFile);
console.error("[LD FDPI] SHA-256 mismatch — refusing to install an unverified binary.");
console.error(" expected:", SHA256);
console.error(" actual: ", digest);
process.exit(1);
}
if (buffer.length < MIN_SIZE || buffer[0] !== 0x4d || buffer[1] !== 0x5a) {
fs.unlinkSync(tempFile);
console.error("[LD FDPI] Downloaded file is not a valid Windows PE binary.");
process.exit(1);
}
for (const target of TARGETS) {
fs.copyFileSync(tempFile, target);
}
fs.unlinkSync(tempFile);
console.log("[LD FDPI] Installed verified engine (SHA-256 OK,", buffer.length, "bytes):");
for (const target of TARGETS) {
console.log(" ", target);
}
if (!printVersion(TARGETS[0])) {
process.exit(1);
}
console.log("[LD FDPI] Sidecar ready.");

531
scripts/e2e-gui.mjs Normal file
View file

@ -0,0 +1,531 @@
/**
* LD FDPI — GUI end-to-end smoke test (WebView2 CDP).
*
* Covers the new "set & forget" behaviour:
* 1. Real Tauri IPC + simplified UI render
* 2. BAĞLAN / BAĞLANTIYI KES through the actual buttons
* 3. LAN sharing rebinds SpoofDPI to 0.0.0.0 and back
* 4. config.json round-trip (camelCase persistence)
* 5. `--minimized` silent start: hidden window, auto-connect before React
* 6. Task Scheduler autostart path (admin warning in an asInvoker test build)
*
* Usage: LD_FDPI_NO_ADMIN=1 npm run tauri build -- --no-bundle && npm run test:gui
*/
import { spawn, spawnSync } from "node:child_process";
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const CONFIG_DIR = path.join(process.env.LOCALAPPDATA || os.tmpdir(), "LD-FDPI");
const CONFIG_PATH = path.join(CONFIG_DIR, "config.json");
const exeCandidates = [
process.argv[2],
path.join(ROOT, "..", ".ld-fdpi-target", "release", "ld-fdpi.exe"),
path.join(ROOT, "src-tauri", "target", "release", "ld-fdpi.exe"),
].filter(Boolean);
const exe = exeCandidates.find((p) => fs.existsSync(p));
if (!exe) {
console.error("ld-fdpi.exe bulunamadı. Önce `npm run tauri build -- --no-bundle` çalıştırın.");
process.exit(1);
}
const BASE_CONFIG = {
version: 1,
autoStart: false,
autoConnect: false,
minimizeToTray: true,
lanSharing: false,
connectionMode: "normal",
bypassMode: 1,
chunkSize: 8,
dohProvider: "cloudflare",
proxyPort: 18080,
pacPort: 18081,
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function readConfigFile() {
try {
return JSON.parse(fs.readFileSync(CONFIG_PATH, "utf8"));
} catch {
return null;
}
}
const originalConfig = readConfigFile();
// Always restore the user's config, even if a check throws.
process.on("exit", () => {
try {
restoreConfig();
} catch {
/* ignore */
}
});
function writeConfig(overrides = {}) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
fs.writeFileSync(CONFIG_PATH, JSON.stringify({ ...BASE_CONFIG, ...overrides }, null, 2));
}
function restoreConfig() {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
if (originalConfig) {
fs.writeFileSync(CONFIG_PATH, JSON.stringify(originalConfig, null, 2));
} else {
fs.writeFileSync(CONFIG_PATH, JSON.stringify(BASE_CONFIG, null, 2));
}
}
function freePort(start) {
return new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.once("error", () => resolve(freePort(start + 1)));
server.listen(start, "127.0.0.1", () => {
const { port } = server.address();
server.close(() => resolve(port));
});
});
}
/** TCP reachability (proves 0.0.0.0 vs 127.0.0.1 binding). */
function canConnect(host, port, timeoutMs = 2500) {
return new Promise((resolve) => {
const socket = net.connect({ host, port });
let done = false;
const finish = (ok) => {
if (done) return;
done = true;
try {
socket.destroy();
} catch {
/* ignore */
}
resolve(ok);
};
socket.setTimeout(timeoutMs, () => finish(false));
socket.once("connect", () => finish(true));
socket.once("error", () => finish(false));
});
}
class Cdp {
constructor(url) {
this.ws = new WebSocket(url);
this.nextId = 0;
this.pending = new Map();
this.ready = new Promise((resolve, reject) => {
this.ws.onopen = resolve;
this.ws.onerror = reject;
});
this.ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.id && this.pending.has(message.id)) {
this.pending.get(message.id)(message);
this.pending.delete(message.id);
}
};
}
async send(method, params = {}) {
await this.ready;
const id = ++this.nextId;
const promise = new Promise((resolve) => this.pending.set(id, resolve));
this.ws.send(JSON.stringify({ id, method, params }));
return promise;
}
async eval(expression, awaitPromise = false) {
const response = await this.send("Runtime.evaluate", {
expression,
awaitPromise,
returnByValue: true,
userGesture: true,
});
if (response.result?.exceptionDetails) {
throw new Error(
response.result.exceptionDetails.exception?.description ||
JSON.stringify(response.result.exceptionDetails)
);
}
return response.result?.result?.value;
}
async invoke(command, args = {}) {
const raw = await this.eval(
`window.__TAURI_INTERNALS__.invoke(${JSON.stringify(command)}, ${JSON.stringify(
args
)}).then(r => JSON.stringify({ ok: true, value: r })).catch(e => JSON.stringify({ ok: false, error: String(e) }))`,
true
);
const parsed = JSON.parse(raw);
if (!parsed.ok) throw new Error(parsed.error);
return parsed.value;
}
async click(label) {
return this.eval(
`(() => { const b = [...document.querySelectorAll('button')].find(x => x.innerText.trim() === ${JSON.stringify(
label
)}); if (!b) return false; b.click(); return true; })()`
);
}
close() {
try {
this.ws.close();
} catch {
/* ignore */
}
}
}
async function waitForCdp(port, timeoutMs = 30000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
const list = await fetch(`http://127.0.0.1:${port}/json/list`).then((r) => r.json());
const page = list.find((t) => t.type === "page");
if (page?.webSocketDebuggerUrl) return page;
} catch {
/* not up yet */
}
await sleep(250);
}
throw new Error("WebView2 CDP endpoint açılmadı (başka bir örnek çalışıyor olabilir)");
}
async function launch({ args = [], cdpPort }) {
const child = spawn(exe, args, {
env: {
...process.env,
WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${cdpPort}`,
},
stdio: "ignore",
});
const page = await waitForCdp(cdpPort);
const cdp = new Cdp(page.webSocketDebuggerUrl);
await cdp.ready;
for (let i = 0; i < 120; i++) {
const state = JSON.parse(
await cdp.eval(
"JSON.stringify({ ready: document.readyState, internals: typeof window.__TAURI_INTERNALS__?.invoke, body: (document.body && document.body.innerText || '').length })"
)
);
if (state.ready === "complete" && state.internals === "function" && state.body > 20) break;
await sleep(250);
}
return { child, cdp };
}
async function stopSession(session) {
if (!session) return;
try {
if (session.cdp) {
await Promise.race([session.cdp.invoke("stop_connection"), sleep(3000)]);
}
} catch {
/* ignore */
}
session.cdp?.close();
if (session.child) {
session.child.kill();
await sleep(800);
}
// Last-resort cleanup: restore a dirty proxy even if the app was killed.
try {
spawnSync(exe, ["--restore-only"], { windowsHide: true, stdio: "ignore" });
} catch {
/* ignore */
}
}
let passed = 0;
let failed = 0;
function check(name, ok, detail = "") {
console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`);
if (ok) passed++;
else failed++;
}
// ---------------------------------------------------------------------------
// Session 1: normal launch, UI click-through, LAN, config persistence
// ---------------------------------------------------------------------------
writeConfig();
let session = null;
try {
session = await launch({ cdpPort: 9333 });
const { cdp, child } = session;
const internals = JSON.parse(
await cdp.eval(
"JSON.stringify({ obj: typeof window.__TAURI_INTERNALS__, invoke: typeof window.__TAURI_INTERNALS__?.invoke })"
)
);
check(
"Tauri v2 çalışma zamanı enjekte edildi",
internals.obj === "object" && internals.invoke === "function",
JSON.stringify(internals)
);
const init = await cdp.invoke("get_initial_state");
check(
"get_initial_state · gerçek motor",
init.engineFound === true && Boolean(init.engineVersion),
`${init.engineVersion} | admin=${init.isAdmin}`
);
let body = "";
for (let i = 0; i < 40; i++) {
body = await cdp.eval("document.body.innerText");
if (body.includes("BAĞLAN")) break;
await sleep(250);
}
check(
"Sadeleştirilmiş arayüz çizildi",
body.includes("BAĞLAN") && body.includes("Bağlantı") && !body.includes("ClientHello"),
`${body.length} karakter`
);
const status0 = await cdp.invoke("get_status");
check("Normal başlatmada pencere görünür", status0.windowVisible === true, "");
check("Açılışta bağlı değil (autoConnect kapalı)", status0.isConnected === false, "");
const diag = await cdp.invoke("run_diagnostics");
check(
"run_diagnostics gerçek sonuçlar",
Array.isArray(diag) && diag.length >= 6,
Array.isArray(diag) ? `${diag.filter((d) => d.passed).length}/${diag.length}` : String(diag)
);
// LAN while disconnected
const lanPacPort = await freePort(18181);
const lan = await cdp.invoke("toggle_lan_sharing", {
enabled: true,
proxyPort: 18080,
pacPort: lanPacPort,
});
const pacBody = await fetch(`http://127.0.0.1:${lanPacPort}/proxy.pac`)
.then((r) => r.text())
.catch(() => "");
check(
"LAN paylaşımı + PAC sunucusu",
lan.enabled === true && pacBody.includes("FindProxyForURL"),
lan.pacUrl
);
await cdp.invoke("toggle_lan_sharing", {
enabled: false,
proxyPort: 18080,
pacPort: lanPacPort,
});
// Connect through the real button
check("BAĞLAN düğmesi bulundu", (await cdp.click("BAĞLAN")) === true, "");
let connectedText = "";
for (let i = 0; i < 160; i++) {
connectedText = await cdp.eval("document.body.innerText");
if (connectedText.includes("FDPI Bağlı")) break;
await sleep(250);
}
check(
"Arayüz 'FDPI Bağlı'",
connectedText.includes("FDPI Bağlı"),
connectedText.includes("Bağlantı başlatılamadı") ? "arayüzde hata var" : ""
);
const status1 = await cdp.invoke("get_status");
check(
"Motor + proxy gerçekten etkin",
status1.isConnected === true && status1.engineAlive === true && status1.proxyRouted === true,
`engine=${status1.engineAlive} proxy=${status1.proxyRouted}`
);
const reg = await cdp.invoke("get_initial_state");
check(
"Windows proxy'si yazıldı",
reg.systemProxy?.proxyEnable === 1 && reg.systemProxy?.pointsToLdFdpiPort === 18080,
`ProxyEnable=${reg.systemProxy?.proxyEnable} ProxyServer=${reg.systemProxy?.proxyServer}`
);
const persisted = readConfigFile();
check(
"config.json kalıcı (camelCase)",
persisted?.proxyPort === 18080 &&
persisted?.connectionMode === "normal" &&
persisted?.autoConnect === false,
`${CONFIG_PATH}`
);
// LAN while connected → 0.0.0.0 rebind
const lanIp = reg.localIp;
const lanPac2 = await freePort(18281);
const lanOn = await cdp.invoke("toggle_lan_sharing", {
enabled: true,
proxyPort: 18080,
pacPort: lanPac2,
});
const lanReachable = await canConnect(lanIp, 18080);
check(
"LAN açıkken motor 0.0.0.0'da",
lanOn.enabled === true && lanReachable === true,
`${lanIp}:18080 reachable=${lanReachable}`
);
await cdp.invoke("toggle_lan_sharing", {
enabled: false,
proxyPort: 18080,
pacPort: lanPac2,
});
const lanClosed = await canConnect(lanIp, 18080);
check(
"LAN kapatınca 127.0.0.1'e döndü",
lanClosed === false,
`${lanIp}:18080 reachable=${lanClosed}`
);
// Settings persistence through save_config
const saved = await cdp.invoke("save_config", {
config: {
...reg.config,
bypassMode: 2,
chunkSize: 4,
dohProvider: "google",
minimizeToTray: false,
},
});
const afterSave = readConfigFile();
check(
"Ayarlar diske yazıldı",
afterSave?.bypassMode === 2 &&
afterSave?.chunkSize === 4 &&
afterSave?.dohProvider === "google" &&
afterSave?.minimizeToTray === false,
`warning=${saved.warning || "yok"}`
);
if (!init.isAdmin) {
const auto = await cdp.invoke("save_config", {
config: { ...saved.config, autoStart: true },
});
check(
"Autostart, yönetici olmadan uyarı üretiyor",
// A pre-existing elevated task from an older install can leave the
// effective flag true even though apply() failed; the warning invariant
// is what matters in this asInvoker test build.
Boolean(auto.warning),
auto.warning || ""
);
await cdp.invoke("save_config", {
config: { ...auto.config, autoStart: false },
});
}
// Restore the test settings
await cdp.invoke("save_config", {
config: {
...saved.config,
bypassMode: 1,
chunkSize: 8,
dohProvider: "cloudflare",
minimizeToTray: true,
},
});
// Disconnect through the real button
check("BAĞLANTIYI KES düğmesi bulundu", (await cdp.click("BAĞLANTIYI KES")) === true, "");
let disconnectedText = "";
for (let i = 0; i < 80; i++) {
disconnectedText = await cdp.eval("document.body.innerText");
if (disconnectedText.includes("Bağlı Değil")) break;
await sleep(250);
}
check("Arayüz 'Bağlı Değil'", disconnectedText.includes("Bağlı Değil"), "");
const after = await cdp.invoke("get_initial_state");
check(
"Proxy orijinal değerine döndü",
after.systemProxy?.proxyEnable === 0 && after.systemProxy?.proxyServer === null,
`ProxyEnable=${after.systemProxy?.proxyEnable} ProxyServer=${after.systemProxy?.proxyServer}`
);
child.kill();
await sleep(800);
} catch (error) {
check("GUI oturumu 1", false, error.message);
} finally {
await stopSession(session);
}
// ---------------------------------------------------------------------------
// Session 2: --minimized + auto_connect, before React
// ---------------------------------------------------------------------------
writeConfig({ autoConnect: true, proxyPort: 18090, pacPort: 18091 });
session = null;
try {
session = await launch({ args: ["--minimized"], cdpPort: 9334 });
const { cdp } = session;
let autoStatus = null;
for (let i = 0; i < 120; i++) {
autoStatus = await cdp.invoke("get_status");
if (autoStatus.isConnected) break;
await sleep(250);
}
check(
"--minimized otomatik bağlandı",
autoStatus?.isConnected === true && autoStatus?.proxyRouted === true,
`connected=${autoStatus?.isConnected} routed=${autoStatus?.proxyRouted}`
);
check(
"Sessiz başlangıçta pencere gizli",
autoStatus?.windowVisible === false,
`windowVisible=${autoStatus?.windowVisible}`
);
const init2 = await cdp.invoke("get_initial_state");
check(
"Otomatik bağlantı kaydedilmiş ayarları kullandı",
init2.isConnected === true && init2.config.proxyPort === 18090,
`port=${init2.config.proxyPort}`
);
// The hidden webview may lag behind the backend poll; stop through IPC.
const stopRes = await cdp.invoke("stop_connection");
await sleep(1000);
check(
"Otomatik oturum bağlantıyı kesti",
stopRes.connected === false && stopRes.restoredOriginalProxy === true,
stopRes.message
);
const stopped = await cdp.invoke("get_initial_state");
check(
"Otomatik oturum proxy'yi geri yükledi",
stopped.systemProxy?.proxyEnable === 0,
`ProxyEnable=${stopped.systemProxy?.proxyEnable}`
);
session.child.kill();
await sleep(800);
} catch (error) {
check("GUI oturumu 2 (auto-connect)", false, error.message);
} finally {
await stopSession(session);
}
// ---------------------------------------------------------------------------
// Restore the user's original config
// ---------------------------------------------------------------------------
restoreConfig();
console.log(`\nSONUÇ: ${passed} başarılı, ${failed} başarısız`);
process.exit(failed === 0 ? 0 : 1);

47
scripts/make-icon.mjs Normal file
View file

@ -0,0 +1,47 @@
/**
* Builds app-icon.png (1024) and public/logo.png (512) from the supplied
* 2048x2048 transparent PNG. Run: npm run icon:make
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import sharp from "sharp";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const SOURCE = path.join(ROOT, "assets", "branding", "ld-fdpi-logo-source.png");
const APP_ICON = path.join(ROOT, "app-icon.png");
const PUBLIC_LOGO = path.join(ROOT, "public", "logo.png");
if (!fs.existsSync(SOURCE)) {
console.error("assets/branding/ld-fdpi-logo-source.png bulunamadı.");
process.exit(1);
}
// The source already has transparent corners; trim the transparent margin so
// the mark fills the taskbar/installer icon instead of looking tiny.
const base = sharp(SOURCE)
.ensureAlpha()
.trim({ background: { r: 0, g: 0, b: 0, alpha: 0 }, threshold: 10 });
await base
.clone()
.resize(1024, 1024, {
fit: "contain",
background: { r: 0, g: 0, b: 0, alpha: 0 },
})
.png({ compressionLevel: 9, adaptiveFiltering: true })
.toFile(APP_ICON);
await base
.clone()
.resize(512, 512, {
fit: "contain",
background: { r: 0, g: 0, b: 0, alpha: 0 },
})
.png({ compressionLevel: 9, adaptiveFiltering: true })
.toFile(PUBLIC_LOGO);
const meta = await sharp(APP_ICON).metadata();
console.log(
`[LD FDPI] app-icon.png ${meta.width}x${meta.height}; public/logo.png 512x512`
);

100
scripts/patch-manifest.mjs Normal file
View file

@ -0,0 +1,100 @@
/**
* Replaces the Windows application manifest of the built executable.
*
* Why this is needed: with the GNU toolchain the MinGW CRT embeds its own
* `asInvoker` manifest (RT_MANIFEST id 1) in addition to the one generated by
* `tauri-winres`. GNU ld reports "multiple non-default manifests" and Windows
* ends up honouring the CRT's asInvoker manifest, so `requireAdministrator`
* never takes effect. `rcedit` rewrites the resource table with exactly one
* manifest, which makes UAC work.
*
* Runs automatically from `scripts/tauri.js` after `tauri build`; skipped for
* the `LD_FDPI_NO_ADMIN=1` test build.
*/
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { ROOT, resolveTargetDir } from "./target-dir.js";
const RCEDIT_VERSION = "2.0.0";
const RCEDIT_URL = `https://github.com/electron/rcedit/releases/download/v${RCEDIT_VERSION}/rcedit-x64.exe`;
const RCEDIT_SHA256 = "3e7801db1a5edbec91b49a24a094aad776cb4515488ea5a4ca2289c400eade2a";
const TOOLS_DIR = path.join(
process.env.LOCALAPPDATA || os.tmpdir(),
"LD-FDPI",
"build-tools"
);
function sha256(file) {
return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
}
async function ensureRcedit() {
const cached = path.join(TOOLS_DIR, "rcedit-x64.exe");
if (fs.existsSync(cached) && sha256(cached) === RCEDIT_SHA256) {
return cached;
}
fs.mkdirSync(TOOLS_DIR, { recursive: true });
console.log("[LD FDPI] Downloading rcedit (manifest patcher)...");
const response = await fetch(RCEDIT_URL, { redirect: "follow" });
if (!response.ok) {
throw new Error(`rcedit indirilemedi: HTTP ${response.status}`);
}
const buffer = Buffer.from(await response.arrayBuffer());
const digest = crypto.createHash("sha256").update(buffer).digest("hex");
if (digest !== RCEDIT_SHA256) {
throw new Error(`rcedit SHA-256 uyuşmuyor (${digest})`);
}
fs.writeFileSync(cached, buffer);
return cached;
}
export async function patchManifest() {
const exe = path.join(resolveTargetDir(), "release", "ld-fdpi.exe");
if (!fs.existsSync(exe)) {
throw new Error(`Derlenmiş uygulama bulunamadı: ${exe}`);
}
const manifest = path.join(ROOT, "src-tauri", "windows-app-manifest.xml");
if (!fs.existsSync(manifest)) {
throw new Error(`Manifest bulunamadı: ${manifest}`);
}
const before = fs.readFileSync(exe);
if (before.includes(Buffer.from("asInvoker"))) {
const rcedit = await ensureRcedit();
const ico = path.join(ROOT, "src-tauri", "icons", "icon.ico");
const rceditArgs = [exe, "--application-manifest", manifest];
if (fs.existsSync(ico)) {
rceditArgs.push("--set-icon", ico);
}
const result = spawnSync(rcedit, rceditArgs, {
stdio: "inherit",
windowsHide: true,
});
if (result.status !== 0) {
throw new Error(`rcedit başarısız (çıkış kodu ${result.status})`);
}
}
const after = fs.readFileSync(exe);
const hasAdmin = after.includes(Buffer.from("requireAdministrator"));
const hasInvoker = after.includes(Buffer.from("asInvoker"));
if (!hasAdmin || hasInvoker) {
throw new Error(
`Manifest doğrulanamadı (requireAdministrator=${hasAdmin}, asInvoker=${hasInvoker}).`
);
}
console.log("[LD FDPI] UAC manifest doğrulandı: requireAdministrator");
return exe;
}
// Allow direct invocation: node scripts/patch-manifest.mjs
if (import.meta.url === `file://${process.argv[1].replace(/\\/g, "/")}`) {
patchManifest().catch((error) => {
console.error("[LD FDPI]", error.message);
process.exit(1);
});
}

351
scripts/security-e2e.mjs Normal file
View file

@ -0,0 +1,351 @@
/**
* LD FDPI — network security regression test.
*
* * LAN off => SpoofDPI listens on 127.0.0.1 only (LAN IP refused).
* * LAN on => 0.0.0.0 works for private peers, PAC answers normally.
* * PAC request cap: >4096 bytes => 413.
* * PAC slowloris timeout: 5 s => 408 / close.
* * LAN off again => PAC closed, engine back to loopback.
*
* Usage: LD_FDPI_NO_ADMIN=1 npm run tauri build -- --no-bundle && node scripts/security-e2e.mjs
*/
import { spawn, spawnSync } from "node:child_process";
import fs from "node:fs";
import net from "node:net";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const CONFIG_DIR = path.join(process.env.LOCALAPPDATA || os.tmpdir(), "LD-FDPI");
const CONFIG_PATH = path.join(CONFIG_DIR, "config.json");
const exe =
[process.argv[2], path.join(ROOT, "..", ".ld-fdpi-target", "release", "ld-fdpi.exe")].find(
(candidate) => candidate && fs.existsSync(candidate)
) || "";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const originalConfig = fs.existsSync(CONFIG_PATH) ? fs.readFileSync(CONFIG_PATH, "utf8") : null;
const BASE = {
version: 1,
autoStart: false,
autoConnect: false,
minimizeToTray: true,
lanSharing: false,
connectionMode: "normal",
bypassMode: 1,
chunkSize: 8,
dohProvider: "cloudflare",
proxyPort: 18480,
pacPort: 18481,
};
function writeConfig() {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
fs.writeFileSync(CONFIG_PATH, JSON.stringify(BASE, null, 2));
}
function restoreConfig() {
if (originalConfig !== null) fs.writeFileSync(CONFIG_PATH, originalConfig);
else fs.writeFileSync(CONFIG_PATH, JSON.stringify({ ...BASE, autoStart: true, autoConnect: true }, null, 2));
}
function canConnect(host, port, timeout = 2000) {
return new Promise((resolve) => {
const socket = net.connect({ host, port });
let done = false;
const finish = (ok) => {
if (done) return;
done = true;
try {
socket.destroy();
} catch {
/* ignore */
}
resolve(ok);
};
socket.setTimeout(timeout, () => finish(false));
socket.once("connect", () => finish(true));
socket.once("error", () => finish(false));
});
}
function request(port, payload, waitMs = 9000) {
return new Promise((resolve) => {
const socket = net.connect({ host: "127.0.0.1", port });
let data = "";
let done = false;
const finish = (value) => {
if (done) return;
done = true;
try {
socket.destroy();
} catch {
/* ignore */
}
resolve(value);
};
socket.setTimeout(waitMs, () => finish(data || "TIMEOUT"));
socket.once("error", (error) => finish(data || `ERROR:${error.code}`));
socket.once("connect", () => socket.write(payload));
socket.on("data", (chunk) => {
data += chunk.toString("latin1");
if (data.includes("\r\n\r\n")) {
// Wait a moment for the body, then return.
setTimeout(() => finish(data), 80);
}
});
socket.on("end", () => finish(data));
});
}
class Cdp {
constructor(url) {
this.ws = new WebSocket(url);
this.id = 0;
this.pending = new Map();
this.ready = new Promise((resolve, reject) => {
this.ws.onopen = resolve;
this.ws.onerror = reject;
});
this.ws.onmessage = (event) => {
const message = JSON.parse(event.data);
if (message.id && this.pending.has(message.id)) {
this.pending.get(message.id)(message);
this.pending.delete(message.id);
}
};
}
async eval(expression, awaitPromise = false) {
await this.ready;
const id = ++this.id;
const response = new Promise((resolve) => this.pending.set(id, resolve));
this.ws.send(
JSON.stringify({
id,
method: "Runtime.evaluate",
params: { expression, awaitPromise, returnByValue: true, userGesture: true },
})
);
const result = await response;
if (result.result?.exceptionDetails) {
throw new Error(JSON.stringify(result.result.exceptionDetails));
}
return result.result?.result?.value;
}
async invoke(command, args = {}) {
const raw = await this.eval(
`window.__TAURI_INTERNALS__.invoke(${JSON.stringify(command)}, ${JSON.stringify(
args
)}).then(r => JSON.stringify({ ok: true, value: r })).catch(e => JSON.stringify({ ok: false, error: String(e) }))`,
true
);
const parsed = JSON.parse(raw);
if (!parsed.ok) throw new Error(parsed.error);
return parsed.value;
}
close() {
try {
this.ws.close();
} catch {
/* ignore */
}
}
}
async function waitForCdp(port) {
for (let i = 0; i < 120; i++) {
try {
const list = await fetch(`http://127.0.0.1:${port}/json/list`).then((r) => r.json());
const page = list.find((t) => t.type === "page");
if (page?.webSocketDebuggerUrl) return page;
} catch {
/* not up */
}
await sleep(250);
}
throw new Error("CDP endpoint açılmadı");
}
let passed = 0;
let failed = 0;
const check = (name, ok, detail = "") => {
console.log(`${ok ? "PASS" : "FAIL"} ${name}${detail ? ` — ${detail}` : ""}`);
if (ok) passed++;
else failed++;
};
if (!exe) {
console.error("ld-fdpi.exe bulunamadı.");
process.exit(1);
}
writeConfig();
process.on("exit", () => {
try {
restoreConfig();
} catch {
/* ignore */
}
});
const child = spawn(exe, [], {
env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: "--remote-debugging-port=9337" },
stdio: "ignore",
});
let cdp = null;
try {
const page = await waitForCdp(9337);
cdp = new Cdp(page.webSocketDebuggerUrl);
await cdp.ready;
for (let i = 0; i < 100; i++) {
const ready = await cdp.eval(
"typeof window.__TAURI_INTERNALS__?.invoke === 'function' && (document.body?.innerText || '').includes('BAĞLAN')"
);
if (ready) break;
await sleep(250);
}
// LAN off: engine must be loopback-only
const conn = await cdp.invoke("start_connection", {
config: {
connectionMode: "normal",
bypassMode: 1,
chunkSize: 8,
dohProvider: "cloudflare",
lanSharing: true, // deliberately malicious/stale: must be ignored
proxyPort: 18480,
pacPort: 18481,
},
});
const init = await cdp.invoke("get_initial_state");
const lanIp = init.localIp;
// Small wait for the engine to be fully wired.
await sleep(300);
const loopbackOnly = !(await canConnect(lanIp, 18480));
check(
"LAN kapalıyken motor yalnızca 127.0.0.1'de",
conn.connected === true && loopbackOnly,
`${lanIp}:18480 reachable=${!loopbackOnly}`
);
// Enable LAN
const pacPort = 18481;
const lan = await cdp.invoke("toggle_lan_sharing", {
enabled: true,
proxyPort: 18480,
pacPort,
});
const lanReachable = await canConnect(lanIp, 18480);
check(
"LAN açıkken özel ağdan erişilebilir",
lan.enabled === true && lanReachable === true,
`${lanIp}:18480`
);
const normal = await request(pacPort, "GET /proxy.pac HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n");
check(
"PAC normal istek 200",
normal.startsWith("HTTP/1.1 200") && normal.includes("FindProxyForURL"),
normal.split("\r\n")[0]
);
const oversized = await request(
pacPort,
`GET / HTTP/1.1\r\nHost: x\r\n${"A".repeat(5000)}`
);
check(
"PAC 4096 bayt sınırı (413)",
oversized.includes("413"),
oversized.split("\r\n")[0] || oversized
);
const slow = await new Promise((resolve) => {
const socket = net.connect({ host: "127.0.0.1", port: pacPort }, () => socket.write("G"));
let data = "";
socket.on("data", (chunk) => {
data += chunk.toString("latin1");
});
socket.on("end", () => resolve(data));
socket.on("error", () => resolve(data));
setTimeout(() => {
socket.destroy();
resolve(data);
}, 7000);
});
check(
"PAC 5 sn Slowloris zaman aşımı (408 / kapanış)",
slow.includes("408") || slow.length === 0,
slow.split("\r\n")[0] || "bağlantı kapandı"
);
// Disable LAN: PAC must be gone, engine loopback only
await cdp.invoke("toggle_lan_sharing", { enabled: false, proxyPort: 18480, pacPort });
await sleep(400);
const pacClosed = !(await canConnect("127.0.0.1", pacPort));
const loopbackAgain = !(await canConnect(lanIp, 18480));
check(
"LAN kapatınca PAC kapanır + motor loopback'e döner",
pacClosed && loopbackAgain,
`pacClosed=${pacClosed} loopback=${loopbackAgain}`
);
const stop = await cdp.invoke("stop_connection");
check("Bağlantı kesildi ve proxy geri yüklendi", stop.restoredOriginalProxy === true, stop.message);
// Eduroam mode smoke test. On this desktop there is no Wi-Fi adapter, so the
// mode must still connect (WinHTTP + WinINet) and report an honest warning.
const eduroamPort = 18482;
const eduroamPac = 18483;
const edu = await cdp.invoke("start_connection", {
config: {
connectionMode: "eduroam",
bypassMode: 1,
chunkSize: 4,
dohProvider: "auto",
lanSharing: false,
proxyPort: eduroamPort,
pacPort: eduroamPac,
},
});
check(
"Eduroam Modu bağlanır (Wi-Fi yoksa dürüst uyarı)",
edu.connected === true && Boolean(edu.warning),
edu.warning || edu.message
);
const eduStatus = await cdp.invoke("get_eduroam_status");
check(
"Eduroam durumu SSID/MTU/802.1X alanlarını döndürür",
eduStatus?.targetMtu === 1400 && typeof eduStatus?.wifi?.available === "boolean",
`ssid=${eduStatus?.wifi?.ssid || "—"} mtu=${eduStatus?.mtu ?? "—"}`
);
const eduDiag = await cdp.invoke("run_eduroam_diagnostics");
check(
"Eduroam ağ testi (SSID/MTU/Discord TCP/UDP)",
Array.isArray(eduDiag) && eduDiag.length >= 6,
Array.isArray(eduDiag) ? `${eduDiag.filter((item) => item.passed).length}/${eduDiag.length}` : "—"
);
const eduStop = await cdp.invoke("stop_connection");
check(
"Eduroam modu kapanınca proxy/MTU geri yüklenir",
eduStop.restoredOriginalProxy === true,
eduStop.message
);
} catch (error) {
check("Güvenlik E2E", false, error.message);
} finally {
cdp?.close();
child.kill();
await sleep(800);
try {
spawnSync(exe, ["--restore-only"], { windowsHide: true, stdio: "ignore" });
} catch {
/* ignore */
}
}
restoreConfig();
console.log(`\nSONUÇ: ${passed} başarılı, ${failed} başarısız`);
process.exit(failed === 0 ? 0 : 1);

28
scripts/target-dir.js Normal file
View file

@ -0,0 +1,28 @@
/**
* Resolves a space-free Cargo target directory.
*
* Why this exists: on Windows with the `x86_64-pc-windows-gnu` toolchain,
* `tauri-winres` → `embed-resource` → GNU `windres` passes the output/include
* directory to `cc1` without quoting. A project path containing a space
* (e.g. "...\LD FDPI\...") therefore aborts the build with:
* cc1.exe: fatal error: FDPI\src-tauri\target\...: No such file or directory
*
* We keep the target directory as a sibling of the project when that path is
* space-free, and fall back to %LOCALAPPDATA% otherwise. Fully relative and
* machine-independent.
*/
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
export function resolveTargetDir() {
let dir = path.resolve(ROOT, "..", ".ld-fdpi-target");
if (dir.includes(" ")) {
dir = path.join(process.env.LOCALAPPDATA || os.tmpdir(), "ld-fdpi-build", "target");
}
fs.mkdirSync(dir, { recursive: true });
return dir;
}

67
scripts/tauri.js Normal file
View file

@ -0,0 +1,67 @@
/**
* `npm run tauri <args>` wrapper.
*
* 1. Sets CARGO_TARGET_DIR to a space-free path so GNU windres does not break on
* spaces in the project path (see target-dir.js).
* 2. After `build`, replaces the executable's manifest with the single
* `requireAdministrator` one (GNU ld otherwise keeps the CRT's asInvoker
* manifest and UAC never triggers).
* 3. Re-runs `tauri bundle` so the installer contains the patched executable.
*
* Set LD_FDPI_NO_ADMIN=1 for an asInvoker test build (skips the manifest patch).
*/
import { spawnSync } from "node:child_process";
import path from "node:path";
import { ROOT, resolveTargetDir } from "./target-dir.js";
import { patchManifest } from "./patch-manifest.mjs";
const cli = path.join(ROOT, "node_modules", "@tauri-apps", "cli", "tauri.js");
const targetDir = resolveTargetDir();
const env = { ...process.env, CARGO_TARGET_DIR: targetDir };
const args = process.argv.slice(2);
const noAdmin = Boolean(process.env.LD_FDPI_NO_ADMIN);
const command = args[0];
const isBuild = command === "build";
const isBundle = command === "bundle";
const noBundle = args.includes("--no-bundle");
console.log(`[LD FDPI] CARGO_TARGET_DIR=${targetDir}`);
function run(list) {
const result = spawnSync(process.execPath, [cli, ...list], {
stdio: "inherit",
cwd: ROOT,
env,
});
return result.status ?? 1;
}
(async () => {
// Test builds stay asInvoker so they can be launched without UAC.
if (noAdmin) {
process.exit(run(args));
}
if (isBundle) {
await patchManifest();
process.exit(run(args));
}
if (isBuild && !noBundle) {
const buildStatus = run([...args, "--no-bundle"]);
if (buildStatus !== 0) process.exit(buildStatus);
await patchManifest();
// Package the already-patched binary into the NSIS installer.
process.exit(run(["bundle"]));
}
const status = run(args);
if (status === 0 && isBuild) {
await patchManifest();
}
process.exit(status);
})().catch((error) => {
console.error("[LD FDPI]", error.message);
process.exit(1);
});

543
scripts/verify-all.mjs Normal file
View file

@ -0,0 +1,543 @@
/**
* LD FDPI — real end-to-end verification suite.
*
* Unlike the previous suite (which asserted that fabricated flags and simulation
* branches existed), every check here validates behaviour that actually ships:
* the official binary hash, the real SpoofDPI 0.12.2 argv, the absence of mock
* fallbacks, and a live TLS handshake through the spawned proxy.
*
* Run with: npm test
*/
import assert from "node:assert/strict";
import crypto from "node:crypto";
import { spawn } from "node:child_process";
import fs from "node:fs";
import net from "node:net";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
SPOOFDPI_VERSION,
DOH_PROVIDERS,
buildSpoofDpiArgs,
generatePacScript,
getDohIpv4,
windowSizeFor,
} from "../src/utils/engineArgs.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, "..");
const BIN_DIR = path.join(ROOT, "src-tauri", "binaries");
const SIDECAR = path.join(BIN_DIR, "spoofdpi-x86_64-pc-windows-gnu.exe");
const SIDECAR_SHA256 =
"16a5c81265d908d31aaf9be69d577ec91588282ae5c366cc73e8bff878a3ea5e";
let passed = 0;
let failed = 0;
async function runTest(name, fn) {
try {
await fn();
console.log(`PASS ${name}`);
passed++;
} catch (error) {
console.error(`FAIL ${name}\n ${error.message}`);
failed++;
}
}
const read = (rel) => fs.readFileSync(path.join(ROOT, rel), "utf8");
const sha256 = (file) =>
crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
function freePort() {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on("error", reject);
server.listen(0, "127.0.0.1", () => {
const { port } = server.address();
server.close(() => resolve(port));
});
});
}
function waitForPort(port, timeoutMs = 8000) {
const deadline = Date.now() + timeoutMs;
return new Promise((resolve, reject) => {
const attempt = () => {
const socket = net.connect({ host: "127.0.0.1", port });
socket.setTimeout(400);
socket.once("connect", () => {
socket.destroy();
resolve();
});
socket.once("timeout", () => {
socket.destroy();
retry();
});
socket.once("error", () => {
socket.destroy();
retry();
});
};
const retry = () => {
if (Date.now() > deadline) reject(new Error(`${port} dinlenmeye başlamadı`));
else setTimeout(attempt, 120);
};
attempt();
});
}
import tls from "node:tls";
/** CONNECT + full TLS handshake (certificate validated) through the local proxy. */
function probeThroughProxy(port, host = "discord.com", timeoutMs = 10000) {
return new Promise((resolve) => {
const socket = net.connect({ host: "127.0.0.1", port });
let settled = false;
const finish = (result) => {
if (settled) return;
settled = true;
try {
socket.destroy();
} catch {
/* ignore */
}
resolve(result);
};
socket.setTimeout(timeoutMs, () =>
finish({ connect: false, tls: false, detail: "timeout" })
);
socket.once("error", (error) =>
finish({ connect: false, tls: false, detail: error.code || error.message })
);
socket.once("connect", () =>
socket.write(`CONNECT ${host}:443 HTTP/1.1\r\nHost: ${host}:443\r\n\r\n`, "ascii")
);
let head = Buffer.alloc(0);
const onData = (chunk) => {
head = Buffer.concat([head, chunk]);
const end = head.indexOf("\r\n\r\n");
if (end === -1) return;
socket.removeListener("data", onData);
const status = head.subarray(0, end).toString("ascii").split("\r\n")[0];
if (!status.includes("200")) {
finish({ connect: false, tls: false, detail: status });
return;
}
const leftover = head.subarray(end + 4);
socket.pause();
if (leftover.length > 0) socket.unshift(leftover);
const tlsSocket = tls.connect(
{ socket, servername: host, rejectUnauthorized: true },
() => {
tlsSocket.write(
`HEAD / HTTP/1.1\r\nHost: ${host}\r\nConnection: close\r\n\r\n`
);
tlsSocket.once("data", (response) => {
const line = response.toString("ascii").split("\r\n")[0];
finish({
connect: true,
tls: line.startsWith("HTTP/"),
detail: `TLS ${tlsSocket.getProtocol()} — ${line}`,
});
});
}
);
tlsSocket.once("error", (error) =>
finish({ connect: true, tls: false, detail: `TLS: ${error.message}` })
);
tlsSocket.setTimeout(timeoutMs, () =>
finish({ connect: true, tls: false, detail: "TLS timeout" })
);
};
socket.on("data", onData);
});
}
console.log("==============================================================");
console.log("LD FDPI — gerçek uçtan uca doğrulama (SpoofDPI " + SPOOFDPI_VERSION + ")");
console.log("==============================================================\n");
await runTest("1. Sidecar gerçek SpoofDPI ikilisi (boyut + PE + SHA-256 + sürüm)", async () => {
assert.ok(fs.existsSync(SIDECAR), `Eksik: ${SIDECAR}`);
const stat = fs.statSync(SIDECAR);
assert.ok(stat.size > 1_500_000, `Sahte/eksik ikili: ${stat.size} bayt`);
const header = fs.readFileSync(SIDECAR).subarray(0, 2).toString("latin1");
assert.equal(header, "MZ", "PE başlığı yok");
assert.equal(sha256(SIDECAR), SIDECAR_SHA256, "Resmi sürümle SHA-256 uyuşmuyor");
const { spawnSync } = await import("node:child_process");
const run = spawnSync(SIDECAR, ["-v"], { encoding: "utf8", windowsHide: true });
const out = `${run.stdout || ""}${run.stderr || ""}`;
assert.ok(out.includes(`spoofdpi v${SPOOFDPI_VERSION}`), `Beklenmeyen sürüm: ${out}`);
});
await runTest("2. CLI argümanları gerçek SpoofDPI 0.12.2 bayraklarıyla uyumlu", async () => {
const rust = read("src-tauri/src/engine.rs");
assert.ok(rust.includes('"-listen-addr"'), "Rust -listen-addr göndermiyor");
assert.ok(rust.includes('"-listen-port"'), "Rust -listen-port göndermiyor");
assert.ok(rust.includes('"-system-proxy=false"'), "SpoofDPI kendi system proxy'sini yönetmemeli");
assert.ok(rust.includes('"-enable-doh"'), "DoH kapalı");
assert.ok(!rust.includes('"-addr"'), "Var olmayan -addr bayrağı hâlâ kodda");
assert.ok(!rust.includes('"-port"'), "Var olmayan -port bayrağı hâlâ kodda");
assert.ok(!rust.includes("--mode"), "Uydurma --mode bayrağı");
assert.ok(!rust.includes("--chunk-size"), "Uydurma --chunk-size bayrağı");
assert.ok(!rust.includes("--disorder"), "Uydurma --disorder bayrağı");
const args = buildSpoofDpiArgs({ proxyPort: 8080, bypassMode: 1, chunkSize: 8, dohProvider: "cloudflare" });
assert.deepEqual(args, [
"-listen-addr", "127.0.0.1",
"-listen-port", "8080",
"-dns-addr", "1.1.1.1",
"-enable-doh",
"-system-proxy=false",
"-window-size", "8",
"-timeout", "8000",
"-silent",
]);
assert.equal(windowSizeFor({ bypassMode: 0 }), 1);
assert.equal(windowSizeFor({ bypassMode: 1, chunkSize: 16 }), 16);
assert.equal(windowSizeFor({ bypassMode: 2, chunkSize: 16 }), 2);
});
await runTest("3. DoH sağlayıcıları yalnızca IP sertifikası geçerli olanlar", async () => {
assert.deepEqual(DOH_PROVIDERS.map((p) => p.id), ["cloudflare", "google", "adguard"]);
assert.equal(getDohIpv4("google"), "8.8.8.8");
assert.equal(getDohIpv4("adguard"), "94.140.14.14");
assert.equal(getDohIpv4("quad9"), "1.1.1.1", "Desteklenmeyen sağlayıcı güvenli varsayılana düşmeli");
const i18n = read("src/i18n.js");
assert.ok(!i18n.includes("quad9"), "Kaldırılan Quad9 seçeneği arayüzde duruyor");
});
await runTest("4. Tauri v2 yapılandırması: externalBin, CSP/IPC, shell yetkisi yok", async () => {
const conf = JSON.parse(read("src-tauri/tauri.conf.json"));
assert.deepEqual(conf.bundle.externalBin, ["binaries/spoofdpi"]);
assert.ok(conf.app.security.csp.includes("ipc:"), "CSP ipc: şemasına izin vermiyor");
assert.ok(
conf.app.security.csp.includes("http://ipc.localhost"),
"CSP http://ipc.localhost adresine izin vermiyor"
);
const cap = JSON.parse(read("src-tauri/capabilities/default.json"));
const flat = JSON.stringify(cap.permissions);
assert.ok(!flat.includes("shell:"), "Webview'e shell yetkisi verilmiş");
assert.ok(cap.windows.includes("main"), "Capability ana pencereye bağlı değil");
});
await runTest("5. Frontend sahte/simülasyon modu içermiyor", async () => {
const bridge = read("src/utils/tauriBridge.js");
const args = read("src/utils/engineArgs.js");
assert.ok(args.includes("window.__TAURI_INTERNALS__"), "Tauri tespiti yok");
assert.ok(bridge.includes("isTauriRuntime"), "Köprü Tauri tespitini kullanmıyor");
assert.ok(!bridge.includes("simulate"), "Simülasyon kodu hâlâ mevcut");
assert.ok(!bridge.includes("setTimeout"), "Gecikmeli sahte yanıt üretimi mevcut");
assert.ok(bridge.includes("Tauri v2 çalışma zamanı bulunamadı"), "Tauri dışında sessiz kalmamalı");
const app = read("src/App.jsx");
assert.ok(!app.includes("simulateWintunMissing"), "Wintun simülasyonu hâlâ UI'da");
const appVersion = JSON.parse(read("package.json")).version;
assert.ok(
app.includes(`useState("${appVersion}")`),
`UI sürümü package.json (${appVersion}) ile uyuşmuyor`
);
});
await runTest("6. PAC betiği Rust ve JS tarafında birebir aynı kuralları kullanıyor", async () => {
const rust = read("src-tauri/src/pac_server.rs");
const js = generatePacScript("192.168.1.42", 8080);
for (const token of [
"FindProxyForURL",
"a === 127",
"a === 10",
"a === 192",
"a === 172",
"*.edu",
"eduroam.org",
"DIRECT",
"PROXY",
]) {
assert.ok(rust.includes(token), `Rust PAC'inde eksik: ${token}`);
assert.ok(js.includes(token), `JS PAC'inde eksik: ${token}`);
}
assert.ok(js.includes("PROXY 192.168.1.42:8080; DIRECT"));
assert.ok(rust.includes("PROXY {local_ip}:{proxy_port}; DIRECT"));
});
await runTest("7. Sentinel: yedek yoksa kayıt defterine dokunmuyor", async () => {
const rust = read("src-tauri/src/proxy_sentinel.rs");
assert.ok(rust.includes("InternetSetOptionW"), "WinInet bildirimi yok");
assert.ok(rust.includes("INTERNET_OPTION_SETTINGS_CHANGED"));
assert.ok(rust.includes("INTERNET_OPTION_REFRESH"));
assert.ok(rust.includes("noBackup"), "Yedek yoksa no-op koruması yok");
assert.ok(!rust.includes("ProxyBackupSnapshot"), "Eski varsayılan-yedek (yıkıcı) tipi kaldı");
assert.ok(rust.includes('delete_value("AutoConfigURL")'), "PAC bağlantısı temizlenmiyor");
assert.ok(rust.includes("dirty_sentinel"), "Kirli oturum bayrağı yok");
});
await runTest("8. Engelleyici süreç yok + canlı proxy üzerinden TLS el sıkışması", async () => {
const port = await freePort();
const args = buildSpoofDpiArgs({
proxyPort: port,
bypassMode: 1,
chunkSize: 8,
dohProvider: "cloudflare",
lanSharing: false,
});
const logPath = path.join(ROOT, "src-tauri", "binaries", "verify-engine.log");
const logFd = fs.openSync(logPath, "w");
const child = spawn(SIDECAR, args, {
windowsHide: true,
stdio: ["ignore", logFd, logFd],
});
try {
await waitForPort(port);
const discord = await probeThroughProxy(port, "discord.com");
assert.ok(discord.connect, `CONNECT başarısız: ${discord.detail}`);
assert.ok(discord.tls, `TLS yanıtı yok: ${discord.detail}`);
const control = await probeThroughProxy(port, "www.cloudflare.com");
assert.ok(control.tls, `Kontrol sitesi TLS başarısız: ${control.detail}`);
} finally {
child.kill();
await new Promise((resolve) => {
if (child.exitCode !== null) resolve();
else child.once("exit", resolve);
setTimeout(resolve, 2000);
});
fs.closeSync(logFd);
}
});
await runTest("9. TR/EN sözlük anahtarları eşleşiyor", async () => {
const { TEXT } = await import("../src/i18n.js");
assert.deepEqual(Object.keys(TEXT.tr), Object.keys(TEXT.en));
for (const section of ["nav", "status", "actions", "mode", "power", "settings", "advanced", "logs"]) {
assert.deepEqual(
Object.keys(TEXT.tr[section]),
Object.keys(TEXT.en[section]),
`${section} anahtarları eşleşmiyor`
);
}
});
await runTest("10. package.json scriptleri doğru", async () => {
const pkg = JSON.parse(read("package.json"));
assert.ok(pkg.scripts["setup:sidecar"].includes("download-sidecar"));
assert.ok(pkg.scripts.test.includes("verify-all"));
assert.ok(pkg.scripts["test:gui"].includes("e2e-gui"));
assert.ok(!pkg.dependencies["@tauri-apps/plugin-shell"], "Kullanılmayan shell eklentisi kaldırılmalı");
assert.ok(
!pkg.dependencies["@tauri-apps/plugin-autostart"],
"Autostart artık Görev Zamanlayıcı ile Rust'ta yönetiliyor"
);
});
await runTest("11. Manuel başlangıç: varsayılanlar ve config.json kalıcılığı", async () => {
const configRs = read("src-tauri/src/config.rs");
assert.ok(configRs.includes("auto_start: true"), "auto_start varsayılanı açık olmalı");
assert.ok(configRs.includes("auto_connect: false"), "auto_connect varsayılanı kapalı olmalı (manuel mod)");
assert.ok(configRs.includes("minimize_to_tray: true"), "minimize_to_tray varsayılanı açık olmalı");
assert.ok(configRs.includes("config.json"), "config.json yolu tanımlı olmalı");
assert.ok(configRs.includes("pub fn save"), "config kaydetme fonksiyonu yok");
});
await runTest("12. Yönetici UAC manifestosu + RL HIGHEST Görev Zamanlayıcı", async () => {
const manifest = read("src-tauri/windows-app-manifest.xml");
assert.ok(manifest.includes('level="requireAdministrator"'), "UAC requireAdministrator yok");
const build = read("src-tauri/build.rs");
assert.ok(build.includes("app_manifest"), "build.rs özel manifesti gömmüyor");
assert.ok(build.includes("LD_FDPI_NO_ADMIN"), "Test için asInvoker anahtarı yok");
const auto = read("src-tauri/src/autostart.rs");
assert.ok(auto.includes('"HIGHEST"'), "RL HIGHEST eksik");
assert.ok(auto.includes('"ONLOGON"'), "ONLOGON tetikleyicisi eksik");
assert.ok(auto.includes("schtasks"), "schtasks kullanılmıyor");
assert.ok(auto.includes("--minimized"), "--minimized argümanı görevde yok");
const conf = JSON.parse(read("src-tauri/tauri.conf.json"));
assert.equal(conf.app.windows[0].visible, false, "Pencere gizli başlamalı (sessiz tray)");
});
await runTest("13. Otomatik bağlantı + 15 sn kendi kendini onarma döngüsü", async () => {
const lib = read("src-tauri/src/lib.rs");
assert.ok(lib.includes("auto_connect"), "auto_connect okunmuyor");
assert.ok(lib.includes("start_supervisor"), "supervisor başlatılmıyor");
assert.ok(lib.includes("Duration::from_secs(15)"), "15 saniyelik sağlık kontrolü yok");
assert.ok(lib.includes("woke"), "uyku sonrası uyanma tespiti yok");
assert.ok(lib.includes("get_status"), "hafif durum komutu yok");
const app = read("src/App.jsx");
assert.ok(app.includes("get_status"), "arayüz durum yoklaması yapmıyor");
assert.ok(app.includes("save_config"), "arayüz ayarları kaydetmiyor");
assert.ok(!app.includes("ClientHello"), "teknik paket şeması ana ekranda kalmış");
});
await runTest("14. Sidecar SHA-256 pin + shell/unsafe çağrı yok", async () => {
const engine = read("src-tauri/src/engine.rs");
assert.ok(engine.includes("SIDECAR_SHA256"), "SHA-256 pin sabiti yok");
assert.ok(engine.includes("GÜVENLİK HATASI"), "Hash uyuşmazlığı güvenlik hatası üretmiyor");
assert.ok(engine.includes("sha256_file"), "Hash hesaplama fonksiyonu yok");
assert.ok(
engine.indexOf("sha256_file(&path)") < engine.indexOf("let args = build_spoofdpi_args"),
"Spawn öncesi tekrar doğrulama yok"
);
const rustFiles = [];
const walk = (dir) => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) walk(full);
else if (entry.name.endsWith(".rs")) rustFiles.push(full);
}
};
walk(path.join(ROOT, "src-tauri", "src"));
rustFiles.push(path.join(ROOT, "src-tauri", "build.rs"));
for (const file of rustFiles) {
const source = fs.readFileSync(file, "utf8");
assert.ok(!/\.unwrap\(\)/.test(source), `${path.basename(file)}: .unwrap() kaldı`);
assert.ok(!/\.expect\(/.test(source), `${path.basename(file)}: .expect() kaldı`);
assert.ok(!/cmd\.exe|powershell(\.exe)?\s/i.test(source), `${path.basename(file)}: shell çağrısı var`);
}
});
await runTest("15. PAC istek limiti + peer filtresi + loopback", async () => {
const pac = read("src-tauri/src/pac_server.rs");
assert.ok(pac.includes("MAX_REQUEST_BYTES: usize = 4096"), "4 KB istek sınırı yok");
assert.ok(pac.includes("READ_TIMEOUT: Duration = Duration::from_secs(5)"), "5 sn okuma zaman aşımı yok");
assert.ok(pac.includes("is_allowed_peer"), "RFC1918 peer filtresi yok");
assert.ok(pac.includes("413"), "Aşırı istek 413 döndürmüyor");
assert.ok(pac.includes("408"), "Zaman aşımı 408 döndürmüyor");
assert.ok(pac.includes('if allow_lan { "0.0.0.0" } else { "127.0.0.1" }'), "Koşullu LAN bind yok");
const lib = read("src-tauri/src/lib.rs");
assert.ok(lib.includes("app_config.lan_sharing = false"), "Açılışta LAN zorla kapatılmıyor");
assert.ok(lib.includes("if !lan_allowed"), "LAN izin parametresi doğrulanmıyor");
assert.ok(lib.includes("0.0.0.0"), "LAN bind mantığı yok");
});
await runTest("16. CSP, sıfır capability ve panic fail-safe", async () => {
const conf = JSON.parse(read("src-tauri/tauri.conf.json"));
assert.equal(
conf.app.security.csp,
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost"
);
const cap = JSON.parse(read("src-tauri/capabilities/default.json"));
assert.deepEqual(cap.permissions, [], "Webview'e gereksiz izin verilmiş");
const lib = read("src-tauri/src/lib.rs");
assert.ok(lib.includes("set_hook"), "Panic hook yok");
assert.ok(lib.includes("restore_system_proxy(true)"), "Panikte proxy geri yükleme yok");
assert.ok(lib.includes("CHILD_PID"), "Panikte motor PID takibi yok");
const config = read("src-tauri/src/config.rs");
assert.ok(config.includes("deny_unknown_fields"), "Config şema doğrulaması yok");
assert.ok(config.includes("64 * 1024"), "Config boyut sınırı yok");
});
await runTest("17. Eduroam modu: SSID, 802.1X, MTU 1400, PAC DIRECT", async () => {
const eduroam = read("src-tauri/src/eduroam.rs");
assert.ok(eduroam.includes("wlan"), "Wi-Fi SSID tespiti yok");
assert.ok(eduroam.includes("eduroam"), "eduroam eşleşmesi yok");
assert.ok(eduroam.includes("EDUROAM_MTU: u16 = 1400"), "MTU 1400 sabiti yok");
assert.ok(eduroam.includes("current_mtu"), "MTU okuma yok");
assert.ok(eduroam.includes("restore_mtu"), "MTU geri yükleme yok");
assert.ok(eduroam.includes("ms-settings:network-wifi"), "Wi-Fi ayarları açılmıyor");
assert.ok(eduroam.includes("udp_stun_probe"), "UDP/Ses tanılaması yok");
const lib = read("src-tauri/src/lib.rs");
assert.ok(lib.includes("pub mod eduroam"), "Eduroam modülü bağlı değil");
assert.ok(lib.includes("get_eduroam_status"), "Eduroam durum komutu yok");
assert.ok(lib.includes("run_eduroam_diagnostics"), "Eduroam tanılama komutu yok");
assert.ok(lib.includes("spawn_blocking(eduroam::status)"), "SSID/MTU komutu UI'yı blokluyor");
assert.ok(lib.includes("spawn_blocking(eduroam::connect_wifi)"), "Wi-Fi bağlanma komutu UI'yı blokluyor");
assert.ok(lib.includes('"eduroam"'), "Eduroam çalışma modu doğrulanmıyor");
assert.ok(lib.includes("is_system_wide"), "Eduroam WinHTTP kapsamına alınmamış");
assert.ok(lib.includes("restore_from_backup"), "MTU çökme kurtarması yok");
const config = read("src-tauri/src/config.rs");
assert.ok(config.includes('"eduroam"'), "Config eduroam modunu normalize etmiyor");
const app = read("src/App.jsx");
assert.ok(app.includes("GraduationCap"), "Eduroam ikonu arayüzde yok");
assert.ok(app.includes("get_eduroam_status"), "Arayüz Eduroam durumunu okumuyor");
assert.ok(app.includes("run_eduroam_diagnostics"), "Arayüz ağ testini çalıştırmıyor");
assert.ok(app.includes("voiceWarning"), "Ses UDP uyarısı yok");
assert.ok(app.includes("!uiActive"), "Gizli pencerede Eduroam yoklaması durmuyor");
const i18n = read("src/i18n.js");
assert.ok(i18n.includes("Eduroam Modu"), "Türkçe Eduroam metni yok");
});
await runTest("18. Ultra-low latency: Smart DoH, TCP_NODELAY, öncelik, LTO", async () => {
const cargo = read("src-tauri/Cargo.toml");
assert.ok(cargo.includes("lto = \"fat\""), "LTO fat yok");
assert.ok(cargo.includes("codegen-units = 1"), "codegen-units=1 yok");
assert.ok(cargo.includes("panic = \"abort\""), "panic=abort yok");
assert.ok(cargo.includes("strip = true"), "strip=true yok");
const engine = read("src-tauri/src/engine.rs");
assert.ok(engine.includes("select_fastest_doh"), "Smart DoH seçici yok");
assert.ok(engine.includes("probe_median"), "3'lü medyan ölçümü yok");
assert.ok(engine.includes("ABOVE_NORMAL_PRIORITY_CLASS"), "Süreç önceliği yok");
assert.ok(engine.includes("probe_local_port"), "Yerel soket canlılık testi yok");
const pac = read("src-tauri/src/pac_server.rs");
assert.ok(pac.includes("set_nodelay(true)"), "PAC TCP_NODELAY yok");
assert.ok(pac.includes("Cache-Control: public, max-age=3600"), "PAC önbellek başlığı yok");
const lib = read("src-tauri/src/lib.rs");
assert.ok(lib.includes("transition_guard"), "Race-condition geçiş kilidi yok");
assert.ok(lib.includes("probe_local_port"), "Supervisor soket yoklaması yok");
assert.ok(lib.includes("resolve_engine_doh"), "Auto DoH çözümlemesi bağlı değil");
const app = read("src/App.jsx");
assert.ok(app.includes("slice(-149)"), "Log ring buffer 150 değil");
assert.ok(app.includes("uiActive"), "Tray gizliyken zamanlayıcı duraklatılmıyor");
assert.ok(app.includes("setInterval"), "Durum zamanlayıcısı yok");
});
await runTest("19. Sürüm 1.5.10 tutarlı", async () => {
const pkg = JSON.parse(read("package.json"));
const cargo = read("src-tauri/Cargo.toml");
const conf = JSON.parse(read("src-tauri/tauri.conf.json"));
assert.equal(pkg.version, "1.5.10");
assert.equal(conf.version, "1.5.10");
assert.match(cargo, /^version = "1\.5\.10"/m);
});
await runTest("20. Yeni logo: app-icon, public logo, favicon ve arayüz", async () => {
const pngSize = (file) => {
const buffer = fs.readFileSync(file);
assert.equal(buffer.subarray(0, 8).toString("hex"), "89504e470d0a1a0a");
return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
};
assert.ok(fs.existsSync(path.join(ROOT, "assets", "branding", "ld-fdpi-logo-source.png")));
const appIcon = pngSize(path.join(ROOT, "app-icon.png"));
assert.deepEqual(appIcon, { width: 1024, height: 1024 });
const uiLogo = pngSize(path.join(ROOT, "public", "logo.png"));
assert.deepEqual(uiLogo, { width: 512, height: 512 });
const app = read("src/App.jsx");
assert.ok(app.includes('src="/logo.png"'), "Arayüz yeni PNG logoyu kullanmıyor");
assert.ok(!app.includes("logo.svg"), "Arayüz eski SVG logoyu kullanıyor");
const html = read("index.html");
assert.ok(html.includes('href="/logo.png"'), "Favicon yeni logoyu kullanmıyor");
assert.ok(fs.statSync(path.join(ROOT, "src-tauri", "icons", "icon.ico")).size > 1000);
});
await runTest("21. Captive portal asistanı bağlı", async () => {
const captive = read("src-tauri/src/captive.rs");
assert.match(captive, /pub fn connect_without_login/);
assert.match(captive, /discover_portal/);
assert.match(captive, /valid_portal_url/);
const lib = read("src-tauri/src/lib.rs");
assert.match(lib, /pub mod captive;/);
assert.match(lib, /connect_without_login/);
const app = read("src/App.jsx");
assert.match(app, /handleCaptiveConnect/);
assert.match(app, /connect_without_login/);
const i18n = read("src/i18n.js");
assert.match(i18n, /Oturum Açmadan Bağlantı/);
assert.match(i18n, /Connect Without Login/);
});
console.log("\n==============================================================");
console.log(`SONUÇ: ${passed} başarılı, ${failed} başarısız`);
console.log("==============================================================");
if (failed > 0) process.exit(1);

35
site/add_fdpi_command.py Normal file
View file

@ -0,0 +1,35 @@
from pathlib import Path
import shutil
p = Path('/opt/kick-duel/server.js')
t = p.read_text(encoding='utf-8')
if "handleFdpi" in t:
print('FDPI command already present')
raise SystemExit(0)
needle = " handleWebsite (name) {"
handler = ''' handleFdpi (name) {
const message = `⚡ @${name}, LD FDPI: DPI bypass + AmneziaWG VPN, WFP kill-switch, DNS/IPv6 koruması. https://ttmadethat.shop/ld-fdpi`;
if (this.bot && typeof this.bot.queue === 'function') {
this.bot.queue(message).catch((err) => log('FDPI mesaji hatasi:', err.message));
} else {
this.notice(message, 'fdpi');
}
log(`FDPI linki gonderildi: ${name}`);
return true;
}
'''
if needle not in t:
raise SystemExit('handleWebsite anchor not found')
t = t.replace(needle, handler + needle, 1)
branch_needle = " if (command === 'website') {\n this.handleWebsite(name);\n return;\n }\n"
branch = branch_needle + "\n if (command === 'fdpi' || command === 'ldfdpi') {\n this.handleFdpi(name);\n return;\n }\n"
if branch_needle not in t:
raise SystemExit('website branch not found')
t = t.replace(branch_needle, branch, 1)
shutil.copy2(p, '/opt/kick-duel/server.js.bak-fdpi-command')
p.write_text(t, encoding='utf-8')
print('FDPI command added')

29
site/add_ld_fdpi_route.py Normal file
View file

@ -0,0 +1,29 @@
from pathlib import Path
import shutil
p = Path('/opt/tylorindar-safelink/main.py')
t = p.read_text(encoding='utf-8')
if 'async def ld_fdpi_page' in t:
print('route already present')
raise SystemExit(0)
needle = '@app.get("/{code}")\nasync def redirect_shortlink'
insert = '''@app.get("/ld-fdpi", include_in_schema=False)
@app.get("/ld-fdpi/", include_in_schema=False)
async def ld_fdpi_page():
page = os.path.join(static_dir, "ld-fdpi.html")
if os.path.exists(page):
return FileResponse(
page,
media_type="text/html",
headers={"Cache-Control": "no-store, max-age=0"},
)
raise HTTPException(status_code=404, detail="LD FDPI sayfası bulunamadı.")
'''
if needle not in t:
raise SystemExit('catch-all route not found')
shutil.copy2(p, '/opt/tylorindar-safelink/backups/main.py.bak-ld-fdpi-page')
t = t.replace(needle, insert + needle, 1)
p.write_text(t, encoding='utf-8')
print('route added')

10
site/fix_page_path.py Normal file
View file

@ -0,0 +1,10 @@
from pathlib import Path
p = Path('/opt/tylorindar-safelink/main.py')
t = p.read_text(encoding='utf-8')
t = t.replace(
'page = os.path.join(static_dir, "ld-fdpi.html")',
'page = os.path.join(static_dir, "downloads", "ld-fdpi.html")',
)
p.write_text(t, encoding='utf-8')
print('page path fixed')

446
site/ld-fdpi.html Normal file
View file

@ -0,0 +1,446 @@
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LD FDPI — Discord, oyun ve Almanya çıkışı | v1.7.0</title>
<meta name="description" content="LD FDPI: Discord ve oyunlarda düşük ping, Almanya çıkışı için AmneziaWG VPN. Token veya .conf yok; kur, BAĞLAN'a bas. DPI bypass, DNS sızıntı koruması, WFP kill-switch ve self-heal.">
<link rel="canonical" href="https://ttmadethat.shop/ld-fdpi">
<meta property="og:title" content="LD FDPI — Discord, oyun ve Almanya çıkışı">
<meta property="og:description" content="Kur-çalıştır Windows DPI bypass + AmneziaWG VPN. Token, .conf veya manuel istemci kurulumu yok; cihaz profili ilk bağlantıda otomatik oluşur.">
<meta property="og:type" content="website">
<meta property="og:url" content="https://ttmadethat.shop/ld-fdpi">
<meta property="og:image" content="https://ttmadethat.shop/static/downloads/ld-apps/ld-fdpi-1.7.0-logo.png?v=6d6d7fc">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="LD FDPI — Discord, oyun ve Almanya çıkışı">
<meta name="twitter:description" content="Kur-çalıştır Windows DPI bypass + AmneziaWG VPN. Token/.conf yok.">
<meta name="twitter:image" content="https://ttmadethat.shop/static/downloads/ld-apps/ld-fdpi-1.7.0-logo.png?v=6d6d7fc">
<meta name="theme-color" content="#05080b">
<link rel="icon" type="image/png" href="/static/downloads/ld-apps/ld-fdpi-1.7.0-logo.png?v=6d6d7fc">
<style>
:root {
--bg: #05080b;
--bg2: #070d12;
--panel: rgba(13, 21, 29, .82);
--panel-solid: #0c151d;
--line: rgba(126, 190, 211, .16);
--line2: rgba(126, 190, 211, .28);
--text: #e8f3f7;
--muted: #91aab7;
--cyan: #8fe3f5;
--cyan2: #57c9e8;
--green: #8dffad;
--warn: #ffd27a;
--red: #ff8f9f;
--radius: 18px;
--mono: ui-monospace, "Cascadia Code", "SFMono-Regular", Consolas, monospace;
--sans: "Segoe UI Variable Display", "Segoe UI", ui-sans-serif, system-ui, -apple-system, sans-serif;
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
margin: 0; color: var(--text); font-family: var(--sans); line-height: 1.6;
background:
radial-gradient(900px 520px at 82% -8%, rgba(143,227,245,.14), transparent 62%),
radial-gradient(800px 500px at 4% 18%, rgba(141,255,173,.08), transparent 58%),
var(--bg);
overflow-x: hidden;
}
body::before {
content: ""; position: fixed; inset: 0; pointer-events: none; z-index: -2;
background-image: linear-gradient(rgba(143,227,245,.035) 1px, transparent 1px), linear-gradient(90deg, rgba(143,227,245,.035) 1px, transparent 1px);
background-size: 54px 54px;
mask-image: linear-gradient(to bottom, #000 0%, transparent 75%);
-webkit-mask-image: linear-gradient(to bottom, #000 0%, transparent 75%);
}
.aurora { position: fixed; inset: 0; pointer-events: none; z-index: -1; overflow: hidden; }
.aurora span { position: absolute; width: 44vw; height: 44vw; border-radius: 50%; filter: blur(90px); opacity: .18; animation: drift 18s ease-in-out infinite alternate; }
.aurora span:nth-child(1) { background: #26c9e4; top: -22vw; right: -10vw; }
.aurora span:nth-child(2) { background: #1aff7a; bottom: -28vw; left: -16vw; animation-delay: -7s; opacity: .1; }
.aurora span:nth-child(3) { background: #f5a742; width: 20vw; height: 20vw; top: 40%; left: 58%; opacity: .05; animation-delay: -12s; }
@keyframes drift { from { transform: translate3d(0,0,0) scale(1); } to { transform: translate3d(-4vw, 4vw, 0) scale(1.12); } }
a { color: inherit; }
.wrap { width: min(1160px, calc(100% - 40px)); margin: 0 auto; }
.mono { font-family: var(--mono); }
.muted { color: var(--muted); }
.kicker { color: var(--cyan); font-family: var(--mono); font-size: 10px; letter-spacing: .18em; text-transform: uppercase; font-weight: 700; display: flex; align-items: center; gap: 8px; }
.kicker::before { content: ""; width: 18px; height: 1px; background: linear-gradient(90deg, var(--cyan), transparent); }
h1, h2, h3 { letter-spacing: -.035em; line-height: 1.06; }
h1 { font-size: clamp(44px, 6.8vw, 82px); margin: 18px 0 16px; font-weight: 850; }
h1 span { display: block; background: linear-gradient(100deg, #f0fbff 10%, var(--cyan) 58%, var(--green)); -webkit-background-clip: text; background-clip: text; color: transparent; }
h2 { font-size: clamp(26px, 3.4vw, 42px); margin: 6px 0 0; font-weight: 820; }
p { margin: 0; }
.nav { position: sticky; top: 0; z-index: 50; backdrop-filter: blur(18px) saturate(140%); background: rgba(5,8,11,.78); border-bottom: 1px solid var(--line); }
.nav-in { min-height: 66px; display: flex; align-items: center; justify-content: space-between; gap: 18px; }
.brand { display: flex; align-items: center; gap: 11px; text-decoration: none; font-weight: 820; }
.brand img { width: 34px; height: 34px; border-radius: 10px; border: 1px solid var(--line2); box-shadow: 0 0 24px rgba(143,227,245,.12); }
.brand small { display: block; font-family: var(--mono); font-size: 9px; color: var(--muted); letter-spacing: .16em; text-transform: uppercase; font-weight: 500; }
.nav-links { display: flex; align-items: center; gap: 4px; }
.nav-links a { text-decoration: none; font-size: 12px; color: var(--muted); padding: 8px 10px; border-radius: 8px; }
.nav-links a:hover { color: var(--text); background: rgba(143,227,245,.06); }
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; border: 1px solid transparent; border-radius: 10px; padding: 11px 16px; text-decoration: none; font-size: 12px; font-weight: 780; transition: transform .18s, filter .18s, border-color .18s, background .18s; white-space: nowrap; }
.btn-primary { background: linear-gradient(135deg, #c8f7ff, var(--cyan) 40%, #62d6a0); color: #031014; box-shadow: 0 10px 30px rgba(87,201,232,.16); }
.btn-primary:hover { transform: translateY(-1px); filter: brightness(1.06); }
.btn-ghost { border-color: var(--line2); background: rgba(10,18,24,.7); color: #dcecf2; }
.btn-ghost:hover { border-color: rgba(143,227,245,.55); background: rgba(143,227,245,.06); }
.hero { padding: 76px 0 42px; display: grid; grid-template-columns: 1.07fr .93fr; gap: 44px; align-items: center; }
.eyebrow { display: inline-flex; align-items: center; gap: 8px; border: 1px solid rgba(143,227,245,.25); background: rgba(143,227,245,.06); border-radius: 999px; padding: 6px 10px; font-family: var(--mono); font-size: 9px; letter-spacing: .12em; text-transform: uppercase; color: var(--cyan); }
.pulse { width: 6px; height: 6px; border-radius: 50%; background: var(--green); box-shadow: 0 0 0 0 rgba(141,255,173,.6); animation: pulse 2s infinite; }
@keyframes pulse { 70% { box-shadow: 0 0 0 7px rgba(141,255,173,0); } 100% { box-shadow: 0 0 0 0 rgba(141,255,173,0); } }
.lead { max-width: 620px; color: #b3c9d3; font-size: 16px; margin: 0 0 24px; }
.lead b { color: #e9f8fc; font-weight: 650; }
.actions { display: flex; flex-wrap: wrap; gap: 10px; }
.meta { display: flex; flex-wrap: wrap; gap: 7px; margin-top: 22px; }
.chip { font-family: var(--mono); font-size: 9px; color: #b7ced8; border: 1px solid var(--line); background: rgba(10,20,27,.7); padding: 5px 8px; border-radius: 6px; letter-spacing: .02em; }
.chip.live { color: var(--green); border-color: rgba(141,255,173,.28); }
.console-wrap { perspective: 1000px; }
.console {
position: relative; border: 1px solid var(--line2); border-radius: 20px; overflow: hidden;
background: linear-gradient(160deg, rgba(17,28,38,.96), rgba(7,13,18,.98));
box-shadow: 0 38px 90px rgba(0,0,0,.55), 0 0 0 1px rgba(143,227,245,.04) inset;
transform: rotateY(-4deg) rotateX(1.5deg); transition: transform .5s ease;
}
.console:hover { transform: rotateY(0) rotateX(0); }
.console-top { display: flex; align-items: center; gap: 8px; padding: 12px 14px; border-bottom: 1px solid var(--line); background: rgba(6,11,15,.7); }
.dots { display: flex; gap: 5px; }
.dots i { width: 7px; height: 7px; border-radius: 50%; background: #263b47; }
.dots i:nth-child(1) { background: #ff6b7a; } .dots i:nth-child(2) { background: #ffd166; } .dots i:nth-child(3) { background: #5cf29a; }
.console-title { font-family: var(--mono); font-size: 9px; color: #7c96a4; letter-spacing: .1em; margin-left: 4px; }
.console-body { padding: 16px; }
.shield { display: flex; align-items: center; gap: 14px; padding: 15px; border: 1px solid rgba(143,227,245,.14); border-radius: 14px; background: radial-gradient(circle at 20% 20%, rgba(143,227,245,.12), transparent 60%), #071017; }
.shield-mark { width: 54px; height: 54px; flex: 0 0 54px; display: grid; place-items: center; border-radius: 14px; background: linear-gradient(145deg, rgba(143,227,245,.16), rgba(141,255,173,.08)); border: 1px solid rgba(143,227,245,.32); color: var(--green); font-size: 25px; box-shadow: 0 0 30px rgba(143,227,245,.1); }
.shield h3 { margin: 0; font-size: 13px; }
.shield p { font-family: var(--mono); font-size: 9px; color: #8aa6b3; margin: 2px 0 0; }
.term { margin-top: 11px; border: 1px solid var(--line); border-radius: 12px; background: rgba(4,9,12,.8); padding: 11px 12px; font-family: var(--mono); font-size: 10px; color: #a9c9d5; }
.term-row { display: flex; justify-content: space-between; gap: 12px; padding: 4px 0; border-bottom: 1px dashed rgba(126,190,211,.1); }
.term-row:last-child { border-bottom: 0; }
.term-row span:first-child { color: #6d8997; }
.ok { color: var(--green); } .warn { color: var(--warn); }
.bar { display: flex; gap: 3px; margin-top: 12px; }
.bar i { height: 4px; flex: 1; border-radius: 2px; background: rgba(143,227,245,.16); }
.bar i:nth-child(-n+9) { background: linear-gradient(90deg, var(--cyan2), var(--green)); box-shadow: 0 0 8px rgba(141,255,173,.2); }
.stats { display: grid; grid-template-columns: repeat(4,1fr); gap: 1px; border: 1px solid var(--line); border-radius: 14px; overflow: hidden; background: var(--line); margin-top: 12px; }
.stat { background: rgba(7,13,18,.86); padding: 16px; }
.stat b { display: block; font-family: var(--mono); font-size: 22px; color: var(--cyan); letter-spacing: -.04em; }
.stat span { display: block; font-size: 10px; color: var(--muted); margin-top: 3px; }
section { padding: 36px 0; }
.section-head { display: flex; align-items: end; justify-content: space-between; gap: 24px; margin-bottom: 20px; }
.section-head p { max-width: 470px; color: var(--muted); font-size: 12px; }
.grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 11px; }
.card { position: relative; overflow: hidden; border: 1px solid var(--line); border-radius: 14px; padding: 18px; background: linear-gradient(160deg, rgba(14,24,32,.9), rgba(7,13,18,.92)); transition: transform .22s, border-color .22s; }
.card:hover { transform: translateY(-3px); border-color: rgba(143,227,245,.4); }
.card::after { content: ""; position: absolute; width: 150px; height: 150px; right: -70px; top: -80px; border-radius: 50%; background: rgba(143,227,245,.08); filter: blur(20px); pointer-events: none; }
.card .ico { width: 32px; height: 32px; display: grid; place-items: center; border-radius: 9px; border: 1px solid rgba(143,227,245,.2); background: rgba(143,227,245,.07); color: var(--cyan); font-size: 15px; margin-bottom: 12px; }
.card h3 { margin: 0 0 6px; font-size: 13px; font-weight: 760; }
.card p { color: #9ab2bd; font-size: 11.5px; }
.card.wide { grid-column: span 2; }
.card.hero-feature { background: linear-gradient(140deg, rgba(143,227,245,.1), rgba(141,255,173,.05) 55%, rgba(7,13,18,.9)); border-color: rgba(143,227,245,.28); }
.scenarios { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.scenario { position: relative; overflow: hidden; border: 1px solid var(--line); border-radius: 16px; padding: 22px; background: rgba(8,15,20,.84); }
.scenario::before { content: ""; position: absolute; inset: 0; pointer-events: none; background: radial-gradient(420px 200px at 100% 0%, rgba(143,227,245,.1), transparent 65%); }
.scenario.vpn::before { background: radial-gradient(420px 200px at 100% 0%, rgba(141,255,173,.1), transparent 65%); }
.scenario .label { position: relative; display: inline-flex; align-items: center; gap: 7px; font-family: var(--mono); font-size: 9px; letter-spacing: .12em; text-transform: uppercase; padding: 5px 8px; border-radius: 6px; border: 1px solid rgba(143,227,245,.26); color: var(--cyan); background: rgba(143,227,245,.06); }
.scenario.vpn .label { border-color: rgba(141,255,173,.26); color: var(--green); background: rgba(141,255,173,.05); }
.scenario h3 { position: relative; margin: 17px 0 7px; font-size: clamp(22px,2.5vw,30px); letter-spacing: -.04em; }
.scenario > p { position: relative; color: #a8bec9; font-size: 12.5px; margin: 0 0 15px; }
.scenario .use { position: relative; display: flex; flex-wrap: wrap; gap: 6px; margin-top: 15px; }
.scenario .use span { font-family: var(--mono); font-size: 9px; color: #a8c4cf; border: 1px solid var(--line); border-radius: 5px; padding: 4px 7px; background: rgba(5,11,15,.5); }
.scenario .note { position: relative; margin-top: 14px; border-top: 1px solid var(--line); padding-top: 11px; color: #7f98a5; font-size: 10.5px; }
.scenario .note b { color: #c7dde6; font-weight: 600; }
.compare { width: 100%; border-collapse: collapse; font-size: 11px; border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
.compare th, .compare td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--line); }
.compare th { font-family: var(--mono); color: #7f9aa7; font-size: 9px; letter-spacing: .1em; text-transform: uppercase; background: rgba(143,227,245,.045); }
.compare td:first-child { color: #d9ecf2; font-weight: 600; }
.compare tr:last-child td { border-bottom: 0; }
@media (max-width: 760px) { .scenarios { grid-template-columns: 1fr; } }
.split { display: grid; grid-template-columns: 1fr 1fr; gap: 11px; }
.box { border: 1px solid var(--line); border-radius: 14px; padding: 18px; background: rgba(9,16,22,.8); }
.box h3 { margin: 0 0 12px; font-size: 13px; }
.list { list-style: none; padding: 0; margin: 0; display: grid; gap: 8px; }
.list li { display: flex; gap: 9px; color: #a7bdc8; font-size: 11.5px; }
.list li::before { content: "✓"; color: var(--green); font-weight: 900; font-size: 10px; margin-top: 2px; }
.list.cross li::before { content: "×"; color: var(--red); }
.pipeline { display: grid; grid-template-columns: repeat(4, 1fr); gap: 9px; }
.pipe { position: relative; border: 1px solid var(--line); border-radius: 12px; background: rgba(8,15,20,.8); padding: 16px; }
.pipe b { display: block; font-family: var(--mono); color: var(--cyan); font-size: 10px; letter-spacing: .1em; }
.pipe h3 { font-size: 12px; margin: 6px 0 4px; }
.pipe p { font-size: 10.5px; color: var(--muted); }
.pipe:not(:last-child)::after { content: "→"; position: absolute; right: -12px; top: 50%; transform: translateY(-50%); color: var(--cyan); font-size: 14px; z-index: 2; }
.matrix { width: 100%; border-collapse: collapse; font-size: 11px; border: 1px solid var(--line); border-radius: 12px; overflow: hidden; }
.matrix th, .matrix td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--line); }
.matrix th { font-family: var(--mono); color: #7f9aa7; font-size: 9px; letter-spacing: .1em; text-transform: uppercase; background: rgba(143,227,245,.045); }
.matrix td:first-child { color: #d9ecf2; font-weight: 600; }
.matrix tr:last-child td { border-bottom: 0; }
.tag { font-family: var(--mono); font-size: 9px; border-radius: 5px; padding: 2px 6px; border: 1px solid; }
.tag.block { color: #ff9aa6; border-color: rgba(255,138,153,.26); background: rgba(255,138,153,.06); }
.tag.permit { color: #9dffb9; border-color: rgba(141,255,173,.26); background: rgba(141,255,173,.05); }
.tag.keep { color: #a8e7f8; border-color: rgba(143,227,245,.25); background: rgba(143,227,245,.05); }
.install { display: grid; grid-template-columns: .85fr 1.15fr; gap: 16px; align-items: start; }
.steps { display: grid; gap: 8px; counter-reset: s; }
.step { counter-increment: s; display: grid; grid-template-columns: 26px 1fr; gap: 10px; border: 1px solid var(--line); border-radius: 11px; padding: 12px; background: rgba(8,15,20,.78); }
.step::before { content: counter(s, decimal-leading-zero); font-family: var(--mono); font-size: 9px; color: var(--cyan); border: 1px solid rgba(143,227,245,.26); border-radius: 6px; height: 21px; display: grid; place-items: center; }
.step b { display: block; font-size: 11.5px; }
.step span { display: block; color: var(--muted); font-size: 10.5px; margin-top: 2px; }
.download-card { border: 1px solid var(--line2); border-radius: 16px; padding: 20px; background: radial-gradient(500px 220px at 90% 0%, rgba(143,227,245,.11), transparent 60%), rgba(8,15,20,.9); }
.download-card .big { font-size: 22px; font-weight: 820; letter-spacing: -.04em; }
.hash { margin-top: 10px; border: 1px solid var(--line); border-radius: 8px; background: #050b0f; padding: 8px 10px; font-family: var(--mono); font-size: 9px; color: #87a6b3; word-break: break-all; }
.notice { margin-top: 12px; border: 1px solid rgba(255,210,122,.25); background: rgba(255,210,122,.05); border-radius: 10px; padding: 11px 13px; color: #e8d3a5; font-size: 10.5px; }
details { border: 1px solid var(--line); border-radius: 11px; background: rgba(8,15,20,.78); padding: 12px 14px; }
details + details { margin-top: 7px; }
summary { cursor: pointer; font-size: 11.5px; font-weight: 700; color: #d4e5eb; list-style: none; display: flex; justify-content: space-between; gap: 10px; }
summary::-webkit-details-marker { display: none; }
summary::after { content: "+"; color: var(--cyan); font-family: var(--mono); }
details[open] summary::after { content: "−"; }
details p { color: var(--muted); font-size: 11px; margin: 9px 0 0; }
.cta { display: flex; align-items: center; justify-content: space-between; gap: 20px; border: 1px solid rgba(143,227,245,.3); border-radius: 18px; padding: 25px; background: radial-gradient(600px 240px at 10% 10%, rgba(143,227,245,.16), transparent 55%), linear-gradient(140deg, #0b1820, #07110e); box-shadow: 0 20px 60px rgba(0,0,0,.3); }
.cta h2 { font-size: 26px; margin: 0 0 4px; }
.cta p { color: #a7c0ca; font-size: 11.5px; }
footer { border-top: 1px solid var(--line); margin-top: 26px; padding: 22px 0 34px; color: #728b98; font-size: 10.5px; }
footer .wrap { display: flex; justify-content: space-between; gap: 14px; flex-wrap: wrap; }
footer a { color: #a9c4ce; text-decoration: none; }
code { font-family: var(--mono); font-size: 10px; color: #d3edf5; background: #071218; border: 1px solid var(--line); border-radius: 5px; padding: 2px 5px; }
.reveal { opacity: 1; transform: none; transition: opacity .6s ease, transform .6s ease; }
.js .reveal { opacity: 0; transform: translateY(16px); }
.js .reveal.in { opacity: 1; transform: none; }
@media (max-width: 900px) { .hero { grid-template-columns: 1fr; padding-top: 44px; } .console-wrap { order: -1; } .console { transform: none; } .grid { grid-template-columns: 1fr 1fr; } .card.wide { grid-column: span 2; } .pipeline { grid-template-columns: 1fr 1fr; } .pipe:nth-child(2)::after { display: none; } .install { grid-template-columns: 1fr; } }
@media (max-width: 640px) { .nav-links a:not(.btn) { display: none; } .grid, .stats, .split, .pipeline { grid-template-columns: 1fr 1fr; } .card.wide { grid-column: auto; } .section-head { align-items: flex-start; flex-direction: column; } .cta { flex-direction: column; align-items: flex-start; } .stats { grid-template-columns: 1fr 1fr; } .matrix { font-size: 10px; } .matrix th, .matrix td { padding: 8px; } }
@media (max-width: 430px) { .grid, .split, .pipeline { grid-template-columns: 1fr; } .stats { grid-template-columns: 1fr 1fr; } .hero { padding-top: 30px; } h1 { font-size: 42px; } }
@media (prefers-reduced-motion: reduce) { * { animation: none !important; transition: none !important; scroll-behavior: auto !important; } .reveal { opacity: 1; transform: none; } }
</style>
<script>document.documentElement.classList.add('js');</script>
</head>
<body>
<div class="aurora" aria-hidden="true"><span></span><span></span><span></span></div>
<header class="nav">
<div class="wrap nav-in">
<a class="brand" href="/">
<img src="/static/downloads/ld-apps/ld-fdpi-1.7.0-logo.png?v=6d6d7fc" alt="LD FDPI">
<span>LD FDPI<small>ttmadethat.shop / apps</small></span>
</a>
<nav class="nav-links" aria-label="Sayfa gezinmesi">
<a href="/#ldapps">← Uygulamalar</a>
<a href="#features">Özellikler</a>
<a href="#security">Güvenlik</a>
<a href="#install">Kurulum</a>
<a class="btn btn-primary" href="/static/downloads/ld-apps/LD-FDPI_1.7.0_6d6d7fc_x64-setup.exe?v=6d6d7fc" download>İndir · v1.7.0</a>
</nav>
</div>
</header>
<main class="wrap">
<section class="hero">
<div>
<div class="eyebrow"><span class="pulse"></span> Windows 10/11 · tek tık · 7 MB</div>
<h1>Discord açık.<br><span>Ping düşük.</span></h1>
<p class="lead">DPI engelini tek tıkla geç; Discord, Kick ve tarayıcı çalışsın. Oyun trafiğin doğrudan kalsın, ping'in şişmesin. İstersen Almanya çıkışına geç, farklı kataloglara bak.</p>
<div class="actions">
<a class="btn btn-primary" href="/static/downloads/ld-apps/LD-FDPI_1.7.0_6d6d7fc_x64-setup.exe?v=6d6d7fc" download>Windows için indir</a>
<a class="btn btn-ghost" href="#use-cases">Hangi mod bana uygun?</a>
</div>
<div class="meta">
<span class="chip live">v1.7.0</span>
<span class="chip">Kurulum ~1 dk</span>
<span class="chip">Reklamsız</span>
<span class="chip">SpoofDPI 0.12.2</span>
<span class="chip">AmneziaWG</span>
<span class="chip">Win 10/11 x64</span>
</div>
</div>
<div class="console-wrap">
<div class="console">
<div class="console-top"><span class="dots"><i></i><i></i><i></i></span><span class="console-title">LD-FDPI://connection</span></div>
<div class="console-body">
<div class="shield">
<div class="shield-mark">◈</div>
<div><h3>DPI bağlı</h3><p>SpoofDPI 0.12.2 · 127.0.0.1:18080</p></div>
</div>
<div class="term">
<div class="term-row"><span>mode</span><span class="ok">DPI ACTIVE</span></div>
<div class="term-row"><span>discord</span><span>TLS OK · hazır</span></div>
<div class="term-row"><span>wfp</span><span class="warn">VPN modunda devreye girer</span></div>
<div class="term-row"><span>dns</span><span class="ok">1.1.1.1 · DoH</span></div>
<div class="term-row"><span>ipv6 / stun</span><span class="ok">VPN'de bloklu</span></div>
<div class="term-row"><span>latency</span><span>1.1.1.1 · 10 ms</span></div>
</div>
<div class="bar" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i></div>
</div>
</div>
</div>
</section>
<div class="stats reveal">
<div class="stat"><b>1 dk</b><span>kurulum süresi</span></div>
<div class="stat"><b>2</b><span>mod: DPI + VPN</span></div>
<div class="stat"><b>7 MB</b><span>kurulum boyutu</span></div>
<div class="stat"><b>Win 10/11</b><span>x64 destek</span></div>
</div>
<section id="use-cases">
<div class="section-head reveal"><div><div class="kicker">Hangi mod?</div><h2>İki mod. Tek uygulama.</h2></div><p>Oyun için düşük ping, bölgesel içerik için Almanya. İkisini aynı anda açmaya çalışmazsın; uygulama seni doğru moda yönlendirir.</p></div>
<div class="scenarios">
<article class="scenario reveal">
<span class="label"><span class="pulse"></span> DPI MODU</span>
<h3>Takıl, oyna, izle.</h3>
<p>Discord, Kick ve tarayıcı açılır. Oyun istemcisi doğrudan hatta kalır; tüm trafiği VPN'e sokmadığın için ping'in artmaz.</p>
<div class="use"><span>Discord</span><span>Kick</span><span>Tarayıcı</span><span>Rekabetçi oyun</span></div>
<div class="note"><b>Kime göre:</b> “Discord açılsın, oyunuma dokunma” diyenler.</div>
</article>
<article class="scenario vpn reveal">
<span class="label"><span class="pulse"></span> AMNEZIAWG VPN</span>
<h3>Almanya'ya bağlan.</h3>
<p>Tek tıkla tam tünel. Almanya çıkışıyla bölgesel kataloglara ve yurt dışı servislere göz at; IP'n değişsin, trafiğin şifrelensin.</p>
<div class="use"><span>Almanya</span><span>Tam tünel</span><span>Bölgesel içerik</span><span>Gizlilik</span></div>
<div class="note"><b>Kime göre:</b> “Farklı katalog görmek istiyorum” diyenler. Netflix/Prime içeriği ülke ve platform kurallarına bağlıdır; garanti değil.</div>
</article>
</div>
<div class="box reveal" style="margin-top:11px">
<table class="compare">
<thead><tr><th>Karar</th><th>DPI modu</th><th>AmneziaWG VPN</th></tr></thead>
<tbody>
<tr><td>Rota</td><td>Yalnız proxy kullanan uygulamalar</td><td>Tüm cihaz trafiği</td></tr>
<tr><td>Gecikme</td><td>Doğrudan hat · düşük ek yük</td><td>Almanya'ya göre + gecikme</td></tr>
<tr><td>Kullanım</td><td>Discord, Kick, tarayıcı, günlük akış</td><td>Bölgesel katalog, yurt dışı servis, tam gizlilik</td></tr>
<tr><td>Koruma</td><td>Proxy + sentinel</td><td>Kalıcı WFP kill-switch + DNS/IPv6/STUN</td></tr>
<tr><td>En uygun</td><td>Rekabetçi oyun + düşük ping</td><td>Almanya çıkışı + tam tünel</td></tr>
</tbody>
</table>
</div>
<div class="notice reveal" style="margin-top:11px"><b>AmneziaWG nedir?</b> WireGuard tabanlı, paket imzasını gizleyen ve DPI filtrelerine karşı daha dayanıklı bir tünel protokolü. LD FDPI'da özel anahtar cihazda kalır; sunucu yalnızca açık anahtarı görür.</div>
</section>
<section id="features">
<div class="section-head reveal">
<div><div class="kicker">Neden LD FDPI?</div><h2>Tek tık. Arkana bakma.</h2></div>
<p>Kur, bağlan, işine dön. Teknik detayları merak edenler için altında anlattık.</p>
</div>
<div class="grid">
<article class="card hero-feature wide reveal"><div class="ico">◈</div><h3>Çökse bile korur.</h3><p>Kalıcı WFP filtreleri: GUI veya tünel servisi çökse bile çıkışın kapanır. <code>--restore-only</code> tek komutla temizler.</p></article>
<article class="card reveal"><div class="ico">⚡</div><h3>Tek tıkla Discord.</h3><p>SpoofDPI 0.12.2 · SNI parçalama · normal/dengeli/güçlü mod · DoH.</p></article>
<article class="card reveal"><div class="ico">🛡️</div><h3>Almanya'ya bağlan.</h3><p>AmneziaWG tam tünel, özel .conf ve cihaz başına X25519 kimlik.</p></article>
<article class="card reveal"><div class="ico">🔐</div><h3>Anahtar sende kalır.</h3><p>Özel anahtar <code>identity.dat</code> içinde DPAPI ile şifreli; düz metin key yok.</p></article>
<article class="card reveal"><div class="ico">🌐</div><h3>Sızıntı bırakmaz.</h3><p>Fiziksel DNS 53/853 engeli, IPv6 catch-all ve WebRTC STUN blokları.</p></article>
<article class="card reveal"><div class="ico">🧭</div><h3>Modları karıştırmaz.</h3><p>DPI ve VPN aynı anda açılamaz; hata olursa önceki moda döner.</p></article>
<article class="card reveal"><div class="ico">📡</div><h3>Ev ağını da bağla.</h3><p>LAN paylaşımı ve PAC; kapalıyken motor yalnızca loopback dinler.</p></article>
<article class="card reveal"><div class="ico">🎓</div><h3>Okul / oyun modu.</h3><p>Eduroam Wi-Fi için MTU/802.1X farkındalığı; WinHTTP + WinINet.</p></article>
<article class="card reveal"><div class="ico">🧪</div><h3>Sorunu gösterir.</h3><p>Proxy TLS, DNS sızıntısı, WFP ve egress IP kontrolleri tek ekranda.</p></article>
</div>
</section>
<section id="security">
<div class="section-head reveal"><div><div class="kicker">Güvenlik</div><h2>Sadece hızlı değil, sağlam.</h2></div><p>DPI modu günlük akışı açar; VPN modu tüm tüneli WFP ile mühürler. İkisi ayrı çalışır.</p></div>
<div class="pipeline reveal">
<div class="pipe"><b>01 / CONNECT</b><h3>Tünel açılır</h3><p>AmneziaWG servisi başlar, LUID doğrulanır.</p></div>
<div class="pipe"><b>02 / ARM</b><h3>WFP yüklenir</h3><p>Tek transaction: endpoint, DNS, LAN, STUN, IPv6.</p></div>
<div class="pipe"><b>03 / SEAL</b><h3>Filtreler kalır</h3><p>Persistent bayrak; GUI çökse bile kural aktif.</p></div>
<div class="pipe"><b>04 / RESTORE</b><h3>Temiz çıkış</h3><p>Disconnect veya <code>--restore-only</code> filtreleri siler.</p></div>
</div>
<div class="split" style="margin-top:11px">
<div class="box reveal">
<h3>Kural matrisi</h3>
<table class="matrix">
<thead><tr><th>Katman</th><th>Davranış</th></tr></thead>
<tbody>
<tr><td>Loopback</td><td><span class="tag permit">PERMIT</span></td></tr>
<tr><td>VPN endpoint</td><td><span class="tag permit">PERMIT · UDP</span></td></tr>
<tr><td>DHCP + LAN</td><td><span class="tag permit">PERMIT / kontrollü</span></td></tr>
<tr><td>Diğer DNS 53/853</td><td><span class="tag block">BLOCK</span></td></tr>
<tr><td>IPv6 catch-all</td><td><span class="tag block">BLOCK</span></td></tr>
<tr><td>STUN / WebRTC</td><td><span class="tag block">BLOCK</span></td></tr>
</tbody>
</table>
</div>
<div class="box reveal">
<h3>Güvenlik duruşu</h3>
<ul class="list">
<li>Sidecar SHA-256 pin; değiştirilmiş <code>spoofdpi.exe</code> çalışmaz.</li>
<li>Kabuk/PowerShell çağrısı yok; System32 yolları, sabit argümanlar.</li>
<li>Katı CSP + sıfır webview capability.</li>
<li>Atomik config ve proxy sentinel; çökme sonrası geri dönüş.</li>
<li>Kurulumda statik VPN anahtarı taşınmaz.</li>
</ul>
</div>
</div>
</section>
<section id="install">
<div class="section-head reveal"><div><div class="kicker">Kurulum</div><h2>Kur, BAĞLAN'a bas.</h2></div><p>Yönetici izni gerekir. Aktivasyon kodu yok; cihaz profili ilk bağlantıda otomatik oluşur.</p></div>
<div class="install">
<div class="steps reveal">
<div class="step"><div><b>Setup'ı çalıştır</b><span>UAC onayı ver; Windows 10/11 x64.</span></div></div>
<div class="step"><div><b>Uygulamayı aç</b><span>Masaüstü kısayolu veya Başlat menüsü.</span></div></div>
<div class="step"><div><b>VPN'i seç</b><span>VPN sekmesinde yalnızca BAĞLAN / BAĞLANTIYI KES var.</span></div></div>
<div class="step"><div><b>BAĞLAN'a bas</b><span>AmneziaWG ve cihaz profili arka planda otomatik kurulur.</span></div></div>
<div class="step"><div><b>Hazır</b><span>WFP kill-switch ve DNS/IPv6 koruması otomatik devreye girer.</span></div></div>
</div>
<div class="download-card reveal">
<div class="kicker">İndir</div>
<div class="big">LD FDPI v1.7.0</div>
<p class="muted" style="font-size:11px;margin:4px 0 14px">NSIS kurulum · Windows 10/11 x64 · yaklaşık 7.5 MB</p>
<div class="actions">
<a class="btn btn-primary" href="/static/downloads/ld-apps/LD-FDPI_1.7.0_6d6d7fc_x64-setup.exe?v=6d6d7fc" download>Setup indir</a>
<a class="btn btn-ghost" href="/static/downloads/ld-apps/LD-FDPI_1.7.0_6d6d7fc-source.zip?v=6d6d7fc" download>Kaynak ZIP</a>
<a class="btn btn-ghost" href="/static/downloads/ld-apps/readmes/ld-fdpi-v1.7.0_6d6d7fc-README.md?v=6d6d7fc" target="_blank" rel="noopener">README</a>
</div>
<div class="hash">SHA-256 · 6D6D7FC9DA84E92D53FFD9E84E38EF36A5AF0CE518F063B47F1582F88070AB09</div>
<div class="notice"><b>Not:</b> Kod imzası yoktur; SmartScreen “bilinmeyen yayıncı” uyarısı verebilir. Aktivasyon kodu gerekmez.</div>
</div>
</div>
</section>
<section>
<div class="split">
<div class="box reveal"><h3>Gereksinimler</h3><ul class="list"><li>Windows 10 22H2 / Windows 11 x64</li><li>Yönetici yetkisi (UAC)</li><li>WebView2 Runtime</li><li>İnternet + <code>ttmadethat.shop</code></li><li>Etkinleştirme kodu gerekmez</li></ul></div>
<div class="box reveal"><h3>Hangi durumda uygun değil?</h3><ul class="list cross"><li>Windows 7 / ARM64</li><li>Kurumsal politikalarla WFP kısıtlanmış makineler</li><li>Başka VPN/firewall ile aynı anda kullanım</li></ul></div>
</div>
</section>
<section>
<div class="section-head reveal"><div><div class="kicker">SSS</div><h2>Kısa cevaplar.</h2></div></div>
<details class="reveal"><summary>Oyunlarda ping düşer mi?</summary><p>DPI modu oyun trafiğini VPN'e sokmaz; bu yüzden rekabetçi oyunlarda doğrudan hattın gecikmesi korunur. VPN modunda tüm trafik Almanya üzerinden gider; oyun ping'i artabilir. Oyun için DPI modunu seç.</p></details>
<details class="reveal"><summary>Netflix / bölgesel içerik garantili mi?</summary><p>Hayır. Almanya çıkışı bölgesel katalogları görmeni sağlayabilir; ancak platformlar VPN algılayabilir, içerik lisansı ülkeye/hesaba göre değişir. Garanti vermiyoruz; platformun kullanım koşullarına uy.</p></details>
<details class="reveal"><summary>Aktivasyon kodu gerekiyor mu?</summary><p>Hayır. Cihaz kimliği ve VPN profili ilk BAĞLAN’da otomatik oluşturulur. Kod, eski sürümlerden kalan bir yöntemdir.</p></details>
<details class="reveal"><summary>VPN açıkken DPI başlatılabilir mi?</summary><p>Hayır. Mod yöneticisi iki modun aynı anda çalışmasını engeller.</p></details>
<details class="reveal"><summary>WFP kilidi interneti keserse?</summary><p>Uygulamayı yeniden aç (boot cleanup) veya <code>ld-fdpi.exe --restore-only</code> çalıştır. VPN servisi çökse bile filtreler bilerek kalır.</p></details>
<details class="reveal"><summary>Neden SmartScreen uyarıyor?</summary><p>Kurulum dosyası kod imzalı değil. “More info → Run anyway” ile devam edebilirsin.</p></details>
<details class="reveal"><summary>Hangi Windows sürümleri?</summary><p>Windows 10/11 x64. ARM64 ve Windows 7 desteklenmez.</p></details>
</section>
<section>
<div class="cta reveal">
<div><div class="kicker">Hazır mısın?</div><h2>Discord açık, ping düşük.</h2><p>Windows için indir; kur, bağlan, işine dön. İstersen Almanya çıkışına geç.</p></div>
<div class="actions"><a class="btn btn-primary" href="/static/downloads/ld-apps/LD-FDPI_1.7.0_6d6d7fc_x64-setup.exe?v=6d6d7fc" download>Setup indir</a><a class="btn btn-ghost" href="/#ldapps">Tüm uygulamalar</a></div>
</div>
</section>
</main>
<footer>
<div class="wrap"><span>© 2026 ttmadethat.shop · LD FDPI</span><span><a href="/#ldapps">Uygulamalar</a> · <a href="/">Ana sayfa</a></span></div>
</footer>
<script>
(() => {
const items = document.querySelectorAll('.reveal');
if (!('IntersectionObserver' in window)) { items.forEach((el) => el.classList.add('in')); return; }
const obs = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) { entry.target.classList.add('in'); obs.unobserve(entry.target); }
});
}, { threshold: 0.08, rootMargin: '0px 0px -40px 0px' });
items.forEach((el) => obs.observe(el));
})();
</script>
</body>
</html>

View file

@ -0,0 +1,36 @@
from pathlib import Path
p = Path('/opt/tylorindar-safelink/static/index.html')
t = p.read_text(encoding='utf-8')
css = '''
/* LD FDPI detail card */
.ld-app-card { cursor: pointer; transition: border-color .18s ease, box-shadow .18s ease; }
.ld-app-card:hover { border-color: rgba(143,227,245,.45); box-shadow: 0 16px 40px rgba(0,0,0,.28); }
.ld-app-stretch { position: absolute; inset: 0; z-index: 1; border-radius: 16px; }
.ld-app-card .ld-app-btn, .ld-app-card .ld-app-actions { position: relative; z-index: 2; }
.ld-app-btn-detail { background: rgba(143,227,245,.08); border-color: rgba(143,227,245,.28); color: #bdeff8; }
.ld-app-btn-detail:hover { background: rgba(143,227,245,.14); }
'''
if '.ld-app-stretch' not in t:
t = t.replace('</style>', css + '</style>', 1)
needle = '<article class="ld-app-card">'
if needle in t and 'class="ld-app-stretch"' not in t:
t = t.replace(
needle,
needle + '\n <a class="ld-app-stretch" href="/ld-fdpi" aria-label="LD FDPI detaylı özellikler"></a>',
1,
)
needle2 = '<span class="ld-app-updated" data-ldapp="ld-fdpi">'
if needle2 in t and 'ld-app-btn-detail' not in t:
t = t.replace(
needle2,
'<a class="ld-app-btn ld-app-btn-detail" href="/ld-fdpi">Detayları Gör →</a>' + needle2,
1,
)
p.write_text(t, encoding='utf-8')
print('card clickable/detail link added')

5767
src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

61
src-tauri/Cargo.toml Normal file
View file

@ -0,0 +1,61 @@
[package]
name = "ld-fdpi"
version = "1.7.0"
description = "LD FDPI — Zor ağlar için yerel proxy ve DPI bypass aracı (Rust, Tauri v2, SpoofDPI 0.12.2)"
authors = ["LD FDPI Team"]
license = "MIT"
repository = "https://github.com/lildosto/LD-FDPI"
edition = "2021"
[lib]
name = "ld_fdpi_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2.0.5", features = [] }
[dependencies]
tauri = { version = "2.2.0", features = ["tray-icon"] }
tauri-plugin-single-instance = "2.2.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sha2 = "0.10"
tokio = { version = "1.42", features = ["full"] }
sysinfo = "0.33"
local-ip-address = "0.6"
native-tls = "0.2"
x25519-dalek = { version = "2.0", features = ["static_secrets"] }
rand_core = { version = "0.6", features = ["std", "getrandom"] }
base64 = "0.22"
tauri-plugin-updater = "2"
[target.'cfg(windows)'.dependencies]
winreg = "0.52"
windows-sys = { version = "0.59", features = [
"Win32_Foundation",
"Win32_Networking_WinInet",
"Win32_Security_Cryptography",
"Win32_Storage_FileSystem",
"Win32_System_Memory",
"Win32_System_SystemInformation",
"Win32_System_Threading",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
"Win32_NetworkManagement_WindowsFilteringPlatform",
"Win32_NetworkManagement_IpHelper",
"Win32_NetworkManagement_Ndis",
"Win32_Networking_WinSock",
"Win32_System_Rpc",
"Win32_Security"
] }
# Maximum runtime speed / minimum size. panic=abort is safe because the panic
# hook in lib.rs restores the proxy and kills the engine before exiting.
[profile.release]
opt-level = 3
lto = "fat"
codegen-units = 1
panic = "abort"
strip = true

View file

Binary file not shown.

Binary file not shown.

32
src-tauri/build.rs Normal file
View file

@ -0,0 +1,32 @@
fn main() {
// `LD_FDPI_NO_ADMIN=1` builds an asInvoker variant for automated tests on
// machines where a UAC prompt cannot be accepted. The shipped build always
// embeds requireAdministrator.
println!("cargo:rerun-if-env-changed=LD_FDPI_NO_ADMIN");
println!("cargo:rerun-if-changed=windows-app-manifest.xml");
let manifest = include_str!("windows-app-manifest.xml");
let no_admin = std::env::var_os("LD_FDPI_NO_ADMIN").is_some();
let manifest = if no_admin {
manifest.replace("requireAdministrator", "asInvoker")
} else {
manifest.to_string()
};
// Changing this value changes the crate fingerprint, forcing a relink when
// switching between the test (asInvoker) and shipped (requireAdministrator) builds.
println!(
"cargo:rustc-env=LD_FDPI_MANIFEST_LEVEL={}",
if no_admin { "asInvoker" } else { "requireAdministrator" }
);
let windows = tauri_build::WindowsAttributes::new()
.app_manifest(manifest)
.window_icon_path("icons/icon.ico");
let attributes = tauri_build::Attributes::new().windows_attributes(windows);
if let Err(error) = tauri_build::try_build(attributes) {
eprintln!("tauri-build başarısız: {error}");
std::process::exit(1);
}
}

View file

@ -0,0 +1,11 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "LD FDPI minimum capability. No filesystem, shell, process, notification or opener permissions are exposed to the webview; all privileged work runs in Rust custom commands.",
"windows": [
"main"
],
"permissions": [
"updater:default"
]
}

BIN
src-tauri/icons/128x128.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

BIN
src-tauri/icons/32x32.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

BIN
src-tauri/icons/64x64.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<background android:drawable="@color/ic_launcher_background"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Some files were not shown because too many files have changed in this diff Show more