# VPN Shield (VaultLine) — Windows Conversion Guide

> **Target audience:** Developers who are new to Flutter desktop and/or WireGuard native integration on Windows.
> Every command is shown in full. Every download link is provided. Nothing is assumed.

---

## Table of Contents

1. [Overview](#1-overview)
2. [Prerequisites & Downloads](#2-prerequisites--downloads)
3. [Phase 1 — Install Development Tools](#3-phase-1--install-development-tools)
4. [Phase 2 — Generate the Windows Platform](#4-phase-2--generate-the-windows-platform)
5. [Phase 3 — Obtain WireGuard Libraries](#5-phase-3--obtain-wireguard-libraries)
6. [Phase 4 — Implement the Native C++ Bridge](#6-phase-4--implement-the-native-c-bridge)
7. [Phase 5 — Configure Admin Privileges](#7-phase-5--configure-admin-privileges)
8. [Phase 6 — Build & Test](#8-phase-6--build--test)
9. [Phase 7 — Package for Distribution](#9-phase-7--package-for-distribution)
10. [Troubleshooting](#10-troubleshooting)
11. [Architecture Reference](#11-architecture-reference)

---

## 1. Overview

### What this guide covers
VPN Shield is a Flutter desktop application that connects to a backend API (`https://vpnendpoints.abacusai.app`) to manage VPN sessions. The Flutter/Dart code is **fully implemented** and ready to run. What's missing is the **Windows platform directory** and the **native C++ code** that bridges Flutter's `MethodChannel` to the WireGuard tunnel library (`tunnel.dll`).

### What you'll accomplish
- ✅ Set up a complete Windows Flutter desktop development environment
- ✅ Generate the `windows/` platform directory for the project
- ✅ Write C++ code that handles three MethodChannel calls: `establishTunnel`, `tearDownTunnel`, `getTunnelStats`
- ✅ Configure the app to run with Administrator privileges (required by WireGuard)
- ✅ Build and test the application

### How the MethodChannel bridge works
```
┌─────────────────────────┐        ┌──────────────────────────────┐
│   Flutter / Dart Side    │        │      Windows Native (C++)     │
│                          │        │                              │
│  VpnService              │        │  flutter_window.cpp          │
│  ├── _establishTunnel()──┼──MC───►│  ├── HandleMethodCall()     │
│  ├── _tearDownTunnel()───┼──MC───►│  │   ├── establishTunnel    │
│  └── getTunnelStats()────┼──MC───►│  │   ├── tearDownTunnel     │
│                          │        │  │   └── getTunnelStats     │
│  Channel name:           │        │  │                          │
│  com.primio.vpnshield/   │        │  └── Calls tunnel.dll       │
│           wireguard      │        │      (WireGuard library)    │
└─────────────────────────┘        └──────────────────────────────┘
     MC = MethodChannel
```

---

## 2. Prerequisites & Downloads

### Required Software

| Software | Version | Download Link | Why You Need It |
|---|---|---|---|
| **Flutter SDK** | 3.27+ (Stable) | [https://docs.flutter.dev/get-started/install/windows/desktop](https://docs.flutter.dev/get-started/install/windows/desktop) | The Flutter framework and `flutter` CLI tool |
| **Visual Studio 2022** | Community (free) | [https://visualstudio.microsoft.com/downloads/](https://visualstudio.microsoft.com/downloads/) | C++ compiler and Windows SDK needed to build Flutter Windows apps |
| **Git for Windows** | Latest | [https://git-scm.com/download/win](https://git-scm.com/download/win) | Version control; also required by Flutter SDK |
| **WireGuard for Windows** | Latest | [https://www.wireguard.com/install/](https://www.wireguard.com/install/) | Provides `tunnel.dll` — the native library that creates VPN tunnels |
| **WireGuard Windows Source** | Latest | [https://git.zx2c4.com/wireguard-windows](https://git.zx2c4.com/wireguard-windows) | Reference for `tunnel.dll` API (headers and types) |

### Visual Studio 2022 Workload Requirements
When installing Visual Studio, you **must** select these workloads in the installer:

> 📸 *In the Visual Studio Installer, look for the "Workloads" tab*

- ☑️ **"Desktop development with C++"** — this installs MSVC compiler, CMake, and Windows SDK
- Within that workload, ensure these individual components are checked:
  - ☑️ MSVC v143 (or latest) C++ build tools
  - ☑️ Windows 10/11 SDK (10.0.22621.0 or later)
  - ☑️ C++ CMake tools for Windows

### System Requirements
- **OS:** Windows 10 version 1903+ or Windows 11
- **Disk:** ~10 GB free (Flutter SDK + Visual Studio + project)
- **RAM:** 8 GB minimum, 16 GB recommended
- **Admin access:** Required for WireGuard tunnel operations

---

## 3. Phase 1 — Install Development Tools

### Step 1.1 — Install Git

1. Download from [https://git-scm.com/download/win](https://git-scm.com/download/win)
2. Run the installer with default settings
3. **Verify:**
   ```powershell
   git --version
   # Expected: git version 2.x.x
   ```

### Step 1.2 — Install Flutter SDK

1. Download the Flutter SDK zip from [https://docs.flutter.dev/get-started/install/windows/desktop](https://docs.flutter.dev/get-started/install/windows/desktop)
2. Extract to a permanent location, e.g., `C:\flutter`

   > ⚠️ **WARNING:** Do NOT extract Flutter to a path with spaces (e.g., `C:\Program Files`) or special characters. This causes build failures.

3. Add Flutter to your PATH:
   ```powershell
   # Open PowerShell as Administrator and run:
   [Environment]::SetEnvironmentVariable("Path", $env:Path + ";C:\flutter\bin", "User")
   ```
4. Close and reopen your terminal
5. **Verify:**
   ```powershell
   flutter --version
   # Expected: Flutter 3.27.x (or newer), Dart 3.7.x
   ```

### Step 1.3 — Install Visual Studio 2022

1. Download from [https://visualstudio.microsoft.com/downloads/](https://visualstudio.microsoft.com/downloads/)
2. Choose **Community** edition (free)
3. In the installer, select:
   - ☑️ **Desktop development with C++**
4. Click Install and wait (this takes 5-15 minutes)
5. **Verify:**
   ```powershell
   # After installation, run:
   flutter doctor
   ```
   You should see:
   ```
   [✓] Flutter (Channel stable, 3.x.x)
   [✓] Windows Version (Installed version of Windows is version 10 or higher)
   [✓] Visual Studio - develop Windows apps (Visual Studio Community 2022)
   ```

### Step 1.4 — Install WireGuard

1. Download from [https://www.wireguard.com/install/](https://www.wireguard.com/install/) → click "Download Windows Installer"
2. Run the installer with default settings
3. After installation, note the install path (usually `C:\Program Files\WireGuard`)
4. **Verify:**
   ```powershell
   # Check that tunnel.dll exists:
   dir "C:\Program Files\WireGuard\tunnel.dll"
   ```

### Step 1.5 — Run Flutter Doctor (Full Check)

```powershell
flutter doctor -v
```

> 📸 *You should see green checkmarks [✓] for Flutter, Windows Version, and Visual Studio*

**All four checkmarks must be green before proceeding:**
```
[✓] Flutter
[✓] Windows Version
[✓] Visual Studio
[✓] Connected device (windows)
```

If you see `[✗]` or `[!]` for Visual Studio, make sure the "Desktop development with C++" workload is installed.

---

## 4. Phase 2 — Generate the Windows Platform

### Why this step is needed
The project was originally developed without a `windows/` directory. Flutter needs platform-specific runner code to build for Windows. The `flutter create` command generates this.

### Step 2.1 — Navigate to the project

```powershell
cd C:\path\to\vpnshield_project
```

### Step 2.2 — Enable Windows desktop support

```powershell
flutter config --enable-windows-desktop
```

### Step 2.3 — Generate the Windows directory

```powershell
flutter create --platforms=windows .
```

> 📸 *This creates a `windows/` directory with the runner code, CMakeLists.txt, and resource files*

**What gets created:**
```
windows/
├── CMakeLists.txt              # Top-level build config
├── flutter/
│   ├── CMakeLists.txt          # Flutter engine config
│   └── generated_plugins.cmake # Auto-generated plugin list
└── runner/
    ├── CMakeLists.txt          # Runner build config (WE MODIFY THIS)
    ├── flutter_window.cpp      # Window setup (WE MODIFY THIS)
    ├── flutter_window.h        # Window header (WE MODIFY THIS)
    ├── main.cpp                # Entry point
    ├── resource.h              # Resource IDs
    ├── resources/
    │   └── app_icon.ico        # Application icon
    ├── runner.exe.manifest     # App manifest (WE MODIFY THIS)
    ├── Runner.rc               # Resource script
    ├── utils.cpp               # Utility functions
    └── win32_window.cpp        # Win32 window wrapper
```

### Step 2.4 — Verify the generation worked

```powershell
flutter build windows --debug
```

This should compile and produce an executable. If it builds successfully, the foundation is ready.

> ⚠️ **Expected:** The app will build and run but WireGuard tunnels won't work yet — the `MissingPluginException` catch blocks in `vpn_service.dart` will handle this gracefully. The app will still connect to the API and show the UI.

### Step 2.5 — Test the basic build

```powershell
flutter run -d windows
```

> 📸 *The VPN Shield login screen should appear. You can log in and browse the UI — VPN connections will be "virtual" (API-only, no real tunnel) until we add the native code.*

---

## 5. Phase 3 — Obtain WireGuard Libraries

### Why tunnel.dll?
WireGuard's Windows implementation provides a shared library (`tunnel.dll`) that handles all the low-level networking: creating TUN adapters, configuring routes, encrypting packets. Our C++ code will call into this DLL.

### Step 3.1 — Locate tunnel.dll

After installing WireGuard for Windows, the DLL is at:
```
C:\Program Files\WireGuard\tunnel.dll
```

### Step 3.2 — Copy to your project

```powershell
# Create a directory for native libraries
mkdir windows\runner\libs

# Copy the DLL
copy "C:\Program Files\WireGuard\tunnel.dll" windows\runner\libs\
```

### Step 3.3 — Ensure the DLL is bundled with the build

Edit `windows/runner/CMakeLists.txt` and add this near the end of the file (before the final closing statements):

```cmake
# --- WireGuard tunnel.dll ---
# Copy tunnel.dll to the output directory so the app can load it at runtime.
add_custom_command(TARGET ${BINARY_NAME} POST_BUILD
  COMMAND ${CMAKE_COMMAND} -E copy_if_different
    "${CMAKE_CURRENT_SOURCE_DIR}/libs/tunnel.dll"
    "$<TARGET_FILE_DIR:${BINARY_NAME}>/tunnel.dll"
  COMMENT "Copying tunnel.dll to build output"
)
```

> **WHY:** Without this, the built `.exe` won't find `tunnel.dll` and WireGuard calls will fail at runtime.

---

## 6. Phase 4 — Implement the Native C++ Bridge

This is the core of the conversion. We need to modify two files and optionally add a helper.

### Understanding the three methods

The Flutter app calls these three methods over the `com.primio.vpnshield/wireguard` channel:

| Method | Parameters | What it does |
|---|---|---|
| `establishTunnel` | `privateKey`, `publicKey`, `endpoint`, `allowedIps`, `dns` | Creates a WireGuard tunnel with the given config |
| `tearDownTunnel` | *(none)* | Destroys the active tunnel |
| `getTunnelStats` | *(none)* | Returns `{bytesUp: int, bytesDown: int}` |

### Step 4.1 — Modify `windows/runner/flutter_window.h`

Add the MethodChannel member variable to the `FlutterWindow` class. See `/home/ubuntu/windows_implementation/flutter_window.h` for the complete corrected file.

Key addition:
```cpp
#include <flutter/method_channel.h>
#include <flutter/standard_method_codec.h>

// Inside the FlutterWindow class:
private:
  // MethodChannel for communicating with Flutter VPN service
  std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>> wireguard_channel_;
```

### Step 4.2 — Modify `windows/runner/flutter_window.cpp`

This is where the MethodChannel handler lives. See `/home/ubuntu/windows_implementation/flutter_window.cpp` for the complete corrected file with full inline comments.

The handler:
1. Registers the `com.primio.vpnshield/wireguard` channel on the Flutter engine's binary messenger
2. Dispatches incoming method calls to the appropriate handler function
3. Calls WireGuard's `tunnel.dll` functions to manage the VPN tunnel
4. Returns results (or errors) back to Flutter

### Step 4.3 — Update CMakeLists.txt for linking

In `windows/runner/CMakeLists.txt`, ensure the WireGuard library is linked:

```cmake
# After the target_link_libraries line, add:
target_link_libraries(${BINARY_NAME} PRIVATE
  flutter
  flutter_wrapper_app
  # tunnel.dll is loaded dynamically at runtime, no static linking needed
)
```

> **NOTE:** We use `LoadLibrary` / `GetProcAddress` to dynamically load `tunnel.dll` at runtime rather than statically linking. This way the app can start even if the DLL is missing — it will just log an error when tunnel operations are attempted.

---

## 7. Phase 5 — Configure Admin Privileges

### Why admin privileges are needed
WireGuard creates virtual network adapters and modifies routing tables. On Windows, these operations require **Administrator** (elevated) privileges. Without elevation, tunnel creation will fail with "Access Denied".

### Step 5.1 — Update the application manifest

Edit `windows/runner/runner.exe.manifest`:

Find this section:
```xml
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
```

Replace with:
```xml
<requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
```

> ⚠️ **SAFETY WARNING:** Setting `requireAdministrator` means Windows will show a UAC (User Account Control) prompt every time the app starts. This is normal and expected for VPN software. Users should click "Yes" to allow it.

> ⚠️ **DEVELOPMENT NOTE:** During development, you must run your IDE (VS Code, Android Studio) as Administrator, or the `flutter run` command won't be able to launch the app. Right-click your IDE → "Run as administrator".

See `/home/ubuntu/windows_implementation/runner.exe.manifest` for the complete corrected manifest file.

### Step 5.2 — Verify admin prompt works

```powershell
# Build the app
flutter build windows --release

# Navigate to the output
cd build\windows\x64\runner\Release

# Double-click vpnshield.exe
# You should see a UAC prompt asking for admin permission
```

> 📸 *A Windows UAC dialog should appear asking "Do you want to allow this app to make changes to your device?"*

---

## 8. Phase 6 — Build & Test

### Step 6.1 — Clean build

```powershell
flutter clean
flutter pub get
flutter build windows --debug
```

### Step 6.2 — Run with debug output

```powershell
# Run from an elevated (Admin) PowerShell:
flutter run -d windows --verbose
```

### Step 6.3 — Test the full flow

1. **Login test:** Enter credentials → should authenticate with the backend API
2. **Server list test:** After login, the server list should populate from the API
3. **Connect test:** Select a server → tap Connect → should:
   - Call POST `/sessions/connect` (check debug console for response)
   - Call `establishTunnel` via MethodChannel → native code creates WireGuard tunnel
   - Connection status should change to "Connected"
   - Stats should start updating (bytes up/down)
4. **Disconnect test:** Tap Disconnect → should:
   - Call POST `/sessions/disconnect`
   - Call `tearDownTunnel` via MethodChannel → native code destroys tunnel
   - Status should return to "Disconnected"

### Step 6.4 — Verify tunnel is active

While connected, open a new PowerShell window and run:
```powershell
# Check if WireGuard interface exists
Get-NetAdapter | Where-Object { $_.InterfaceDescription -like "*WireGuard*" }

# Check your IP has changed (should show VPN IP)
Invoke-WebRequest -Uri "https://api.ipify.org" -UseBasicParsing
```

### Step 6.5 — Check for common issues

```powershell
# Check Flutter debug console for errors like:
# - "tunnel.dll not found" → DLL not copied to build output
# - "Access Denied" → App not running with admin privileges
# - "MissingPluginException" → MethodChannel not registered (check channel name)
# - "Connection refused" → API endpoint unreachable
```

---

## 9. Phase 7 — Package for Distribution

### Step 9.1 — Release build

```powershell
flutter build windows --release
```

Output is in: `build\windows\x64\runner\Release\`

### Step 9.2 — Verify all files are present

```
Release/
├── vpnshield.exe          # Main executable
├── flutter_windows.dll    # Flutter engine
├── tunnel.dll             # WireGuard library (MUST be here)
├── data/                  # Flutter assets and ICU data
│   ├── flutter_assets/
│   └── icudtl.dat
└── *.dll                  # Other runtime DLLs
```

### Step 9.3 — Create an installer (optional)

For distribution, consider using [Inno Setup](https://jrsoftware.org/isinfo.php) (free):

```iss
; Basic Inno Setup script
[Setup]
AppName=VPN Shield
AppVersion=1.0.0
DefaultDirName={autopf}\VPN Shield
PrivilegesRequired=admin
OutputBaseFilename=VPNShield_Setup

[Files]
Source: "build\windows\x64\runner\Release\*"; DestDir: "{app}"; Flags: recursesubdirs

[Icons]
Name: "{autoprograms}\VPN Shield"; Filename: "{app}\vpnshield.exe"
Name: "{autodesktop}\VPN Shield"; Filename: "{app}\vpnshield.exe"
```

---

## 10. Troubleshooting

### 🔴 "flutter doctor" shows [✗] for Visual Studio

**Cause:** The "Desktop development with C++" workload is not installed.

**Fix:**
1. Open Visual Studio Installer
2. Click "Modify" on Visual Studio 2022
3. Check "Desktop development with C++"
4. Click "Modify" to install

---

### 🔴 "flutter create --platforms=windows ." fails

**Cause:** Windows desktop support not enabled.

**Fix:**
```powershell
flutter config --enable-windows-desktop
flutter create --platforms=windows .
```

---

### 🔴 Build error: "CMake Error: could not find CMAKE_CXX_COMPILER"

**Cause:** MSVC compiler not found. Visual Studio C++ tools not installed or not in PATH.

**Fix:**
1. Ensure "Desktop development with C++" is installed in Visual Studio
2. Run the build from a "Developer PowerShell for VS 2022" terminal
3. Or run: `flutter clean` then rebuild

---

### 🔴 App crashes with "tunnel.dll not found"

**Cause:** The DLL wasn't copied to the build output directory.

**Fix:**
1. Check that `windows/runner/libs/tunnel.dll` exists
2. Check that the `add_custom_command` in CMakeLists.txt is correct
3. Run `flutter clean && flutter build windows`
4. Manually verify: `dir build\windows\x64\runner\Release\tunnel.dll`

---

### 🔴 "Access Denied" when creating tunnel

**Cause:** App is not running with Administrator privileges.

**Fix:**
1. Check `runner.exe.manifest` has `level="requireAdministrator"`
2. If running via `flutter run`, launch your terminal as Administrator
3. Right-click the .exe → "Run as administrator"

---

### 🔴 MissingPluginException for 'establishTunnel'

**Cause:** The MethodChannel is not registered on the native side.

**Fix:**
1. Verify the channel name in `flutter_window.cpp` is exactly: `com.primio.vpnshield/wireguard`
2. Verify the `SetMethodCallHandler` is called in `OnCreate()` after `FlutterWindow::OnCreate()`
3. Clean and rebuild: `flutter clean && flutter run -d windows`

---

### 🔴 App builds but tunnel doesn't actually work

**Cause:** `tunnel.dll` API calls might be failing silently.

**Fix:**
1. Check the debug console for error messages from the native code
2. Ensure WireGuard is installed on the system
3. Ensure the config parameters (privateKey, endpoint, etc.) are valid
4. Try creating a tunnel manually with the WireGuard GUI to verify your system supports it
5. Check Windows Event Viewer → Application logs for WireGuard errors

---

### 🔴 "The application was unable to start correctly (0xc000007b)"

**Cause:** Architecture mismatch — 32-bit DLL with 64-bit app or vice versa.

**Fix:**
1. Ensure you're using the 64-bit `tunnel.dll` (should be the default from WireGuard installer)
2. Flutter builds 64-bit by default on Windows
3. If in doubt: `dumpbin /headers tunnel.dll | findstr machine` should show `x64`

---

### 🔴 Google Fonts fail to load / blank text

**Cause:** Network-dependent font loading. Possible on first run or in restricted network environments.

**Fix:** This is a known Flutter issue. The `google_fonts` package caches fonts after first download. Ensure the machine has internet access on first run, or bundle fonts locally.

---

### 🟡 Settings toggles don't persist

**This is expected behavior.** The Settings screen (auto-connect, kill switch, launch at startup, minimize to tray) contains UI-only placeholders. They are documented as intentional in the project design document (`PRIMIO.md`). Persistence can be added later using `shared_preferences` or `flutter_secure_storage`.

---

## 11. Architecture Reference

### MethodChannel Contract

```
Channel name: com.primio.vpnshield/wireguard

┌─────────────────────────────────────────────────────────────────┐
│ Method: establishTunnel                                         │
│ Direction: Flutter → Native                                     │
│ Arguments (Map):                                                │
│   - privateKey  (String) : WireGuard private key (base64)       │
│   - publicKey   (String) : Server's public key (base64)         │
│   - endpoint    (String) : Server address "host:port"           │
│   - allowedIps  (String) : Allowed IP ranges "0.0.0.0/0"       │
│   - dns         (String) : DNS server "1.1.1.1"                │
│ Returns: void (success) or FlutterError                         │
├─────────────────────────────────────────────────────────────────┤
│ Method: tearDownTunnel                                          │
│ Direction: Flutter → Native                                     │
│ Arguments: none                                                 │
│ Returns: void (success) or FlutterError                         │
├─────────────────────────────────────────────────────────────────┤
│ Method: getTunnelStats                                          │
│ Direction: Flutter → Native                                     │
│ Arguments: none                                                 │
│ Returns: Map { bytesUp: int, bytesDown: int }                   │
└─────────────────────────────────────────────────────────────────┘
```

### App Data Flow

```
User taps Connect
       │
       ▼
VpnProvider.connect()
       │
       ▼
VpnService.connectToServer(serverId)
       │
       ├── SessionRepository.connect() ──► POST /sessions/connect ──► VpnConfig
       │
       └── _establishTunnel(config) ──► MethodChannel ──► Native C++ ──► tunnel.dll
              │
              ▼
       Provider state → connected
       Start stats polling (1s duration, 3s byte stats)
```

### Key File Locations (After Conversion)

| File | Purpose |
|---|---|
| `lib/services/vpn_service.dart` | Flutter-side MethodChannel calls (DO NOT MODIFY) |
| `windows/runner/flutter_window.cpp` | Native MethodChannel handler (MODIFIED) |
| `windows/runner/flutter_window.h` | Header with channel member (MODIFIED) |
| `windows/runner/runner.exe.manifest` | Admin privilege declaration (MODIFIED) |
| `windows/runner/CMakeLists.txt` | Build config with tunnel.dll copy (MODIFIED) |
| `windows/runner/libs/tunnel.dll` | WireGuard native library (ADDED) |

---

*Guide version 1.0 — Last updated: May 2026*
*For the VPN Shield (VaultLine) project — `com.primio.vpnshield`*
