### Install Amnezia VPN Panel with Docker Compose
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/README.md
Clones the repository, sets up the environment, and starts the panel using Docker Compose. Includes steps for both V2 and V1 of Docker Compose and database health checks.
```bash
git clone https://github.com/infosave2007/amneziavpnphp.git
cd amneziavpnphp
cp .env.example .env
# For Docker Compose V2 (recommended)
docker compose up -d
docker compose exec web composer install
# Wait until DB is healthy (initial SQL migration files are applied automatically by MySQL entrypoint)
until [ "$(docker inspect -f '{{.State.Health.Status}}' amnezia-panel-db 2>/dev/null)" = "healthy" ]; do
sleep 2
done
# Or for older Docker Compose V1
docker-compose up -d
docker-compose exec web composer install
until [ "$(docker inspect -f '{{.State.Health.Status}}' amnezia-panel-db 2>/dev/null)" = "healthy" ]; do
sleep 2
done
# Manual migration mode (existing installations / updates only)
set -a; source .env; set +a
for f in migrations/*.sql; do
docker compose exec -T db mysql -u"$DB_USERNAME" -p"$DB_PASSWORD" "$DB_DATABASE" < "$f" || true
done
# For Docker Compose V1 manual migration mode:
# for f in migrations/*.sql; do
# docker-compose exec -T db mysql -u"$DB_USERNAME" -p"$DB_PASSWORD" "$DB_DATABASE" < "$f" || true
# done
```
--------------------------------
### Docker Compose Full Stack Setup for Amnezia VPN Panel
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
This script clones the repository, configures environment variables for the database and admin credentials, and starts the Docker Compose stack. It includes steps for installing composer dependencies, waiting for the database to be healthy, and accessing the panel.
```bash
# Clone and configure
git clone https://github.com/infosave2007/amneziavpnphp.git
cd amneziavpnphp
cp .env.example .env
# Edit .env with secure credentials
cat > .env << 'EOF'
DB_HOST=db
DB_PORT=3306
DB_DATABASE=amnezia_panel
DB_USERNAME=amnezia
DB_PASSWORD=change_this_password
ADMIN_EMAIL=admin@yourdomain.com
ADMIN_PASSWORD=change_this_admin_password
JWT_SECRET=change_this_to_a_random_64_char_string
EOF
# Start stack
docker compose up -d
docker compose exec web composer install
# Wait for DB health check
until [ "$(docker inspect -f '{{.State.Health.Status}}' amnezia-panel-db 2>/dev/null)" = "healthy" ]; do
sleep 2
done
# Access the panel
open http://localhost:8082
# Default login: $ADMIN_EMAIL / $ADMIN_PASSWORD
# View logs
docker compose logs -f web
docker compose exec web tail -f /var/log/cron.log
docker compose exec web tail -f /var/log/metrics_collector.log
# Apply new migrations after update
git pull origin main
for f in migrations/*.sql; do
docker compose exec -T db mysql -u"$DB_USERNAME" -p"$DB_PASSWORD" "$DB_DATABASE" < "$f" || true
done
docker compose restart
```
--------------------------------
### Install Protocol API
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/README.md
Installs a new protocol onto a specified server.
```http
POST /api/servers/{id}/protocols/install - Install protocol
```
--------------------------------
### Install Protocol on Server
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
Install a specified VPN protocol onto a given server.
```APIDOC
## Install Protocol on Server
### Description
Install a specified VPN protocol onto a given server.
### Method
POST
### Endpoint
/api/servers/{server_id}/protocols/install
### Parameters
#### Path Parameters
- **server_id** (integer) - Required - The ID of the server to install the protocol on.
#### Headers
- **Authorization** (string) - Required - Bearer token for authentication.
- **Content-Type** (string) - Required - Set to 'application/json'.
#### Request Body
- **protocol_id** (integer) - Required - The ID of the protocol to install.
### Request Example
```bash
curl -X POST http://localhost:8082/api/servers/1/protocols/install \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"protocol_id":11}'
```
```
--------------------------------
### List Protocols Installed on Server via API
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
This GET request returns a list of protocols that are currently installed on a specific server. It's useful for verifying installations or understanding the available protocols for a given server.
```bash
curl -s http://localhost:8082/api/servers/1/protocols \
-H "Authorization: Bearer $TOKEN"
```
--------------------------------
### POST /api/servers/{id}/protocols/install
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Installs a specified protocol onto a given server. This allows the server to support VPN connections using the newly installed protocol.
```APIDOC
## POST /api/servers/{id}/protocols/install
### Description
Installs a specific VPN protocol onto a designated server. This enables the server to host VPN connections using the chosen protocol.
### Method
POST
### Endpoint
`/api/servers/{id}/protocols/install`
### Parameters
#### Path Parameters
- **id** (int) - Required - The ID of the server to install the protocol on.
#### Request Body
- **protocol_id** (int) - Required - The ID of the protocol to install.
### Request Example
```bash
curl -s -X POST http://localhost:8082/api/servers/1/protocols/install \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"protocol_id": 11}'
```
```
--------------------------------
### Define GET and POST Routes
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Example of defining routes for GET and POST requests using the `Router` class. Parameters can be captured from the URL.
```php
Router::get('/path/{param}', function($params) {
// Handler logic
echo $params['param'];
});
Router::post('/form', function() {
// Handle POST
$data = $_POST['field'];
});
```
--------------------------------
### Install Protocol on Server
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
Install a specific protocol on a server. Requires JWT authentication and the protocol ID.
```bash
curl -X POST http://localhost:8082/api/servers/1/protocols/install \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"protocol_id":11}'
```
--------------------------------
### Install Composer
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Installs Composer globally. This script downloads the installer and moves it to a system-wide location.
```bash
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
```
--------------------------------
### Database Connection and Query
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Demonstrates how to get a PDO database connection using the `DB` singleton and execute a prepared statement.
```php
$pdo = DB::conn();
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$id]);
$user = $stmt->fetch();
```
--------------------------------
### Running PHPUnit Tests
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Instructions on how to install PHPUnit as a development dependency and run tests from the command line.
```bash
composer require --dev phpunit/phpunit
./vendor/bin/phpunit tests/
```
--------------------------------
### POST /api/servers/create
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Deploys a new VPN server by registering a remote host via SSH credentials and installing the selected VPN protocol.
```APIDOC
## POST /api/servers/create
### Description
Deploys a new VPN server by registering a remote host via SSH credentials and installing the selected VPN protocol.
### Method
POST
### Endpoint
/api/servers/create
### Parameters
#### Request Body
- **name** (string) - Required - A name for the new VPN server.
- **host** (string) - Required - The hostname or IP address of the remote server.
- **port** (integer) - Required - The SSH port for the remote server (usually 22).
- **username** (string) - Required - The SSH username for the remote server.
- **password** (string) - Optional - The SSH password for authentication. Use `ssh_key` if provided.
- **ssh_key** (string) - Optional - The SSH private key for authentication. Use `password` if provided.
- **install_protocol** (string) - Required - The identifier for the VPN protocol to install (e.g., 'amnezia-wg-advanced', 'xray-vless').
### Request Example
```bash
# Deploy with password authentication
curl -s -X POST http://localhost:8082/api/servers/create \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "US East - AmneziaWG",
"host": "203.0.113.10",
"port": 22,
"username": "root",
"password": "s3cur3p@ss",
"install_protocol": "amnezia-wg-advanced"
}'
# Deploy with SSH key authentication
curl -s -X POST http://localhost:8082/api/servers/create \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "EU Frankfurt - XRay VLESS",
"host": "198.51.100.42",
"port": 22,
"username": "ubuntu",
"ssh_key": "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC...\n-----END OPENSSH PRIVATE KEY-----",
"install_protocol": "xray-vless"
}'
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the server creation request was successful.
- **server** (object) - An object containing details of the newly created server.
- **id** (integer) - The unique identifier for the server.
- **status** (string) - The current status of the server (e.g., 'active').
- ... (other server details)
#### Response Example
```json
{ "success": true, "server": { "id": 3, "status": "active", ... } }
```
```
--------------------------------
### Python Example: Create Client and Save QR Code
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
Demonstrates how to use the AmneziaVPN API with Python to create a client and save its QR code to a file.
```APIDOC
## Python Example: Create Client and Save QR Code
### Description
This example demonstrates how to authenticate with the API, create a new VPN client, and then save the generated QR code to a PNG image file using Python.
### Language
Python
### Code Example
```python
import requests
import base64
from io import BytesIO
from PIL import Image
# Get token
response = requests.post('http://localhost:8082/api/auth/token',
data={'email': 'admin@amnez.ia', 'password': 'admin123'})
token = response.json()['token']
headers = {'Authorization': f'Bearer {token}'}
# Create client
client_data = {
'server_id': 1,
'name': 'My Phone'
}
response = requests.post('http://localhost:8082/api/clients/create',
json=client_data, headers=headers)
result = response.json()
qr_code_data_uri = result['client']['qr_code']
# Save QR code as image
qr_base64 = qr_code_data_uri.split(',')[1]
qr_bytes = base64.b64decode(qr_base64)
image = Image.open(BytesIO(qr_bytes))
image.save('qr_code.png')
print(f"Client created: {result['client']['name']}")
print(f"QR code saved to qr_code.png")
```
```
--------------------------------
### VpnServer::create() and VpnServer::deploy()
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Use these PHP methods to create a server record with initial status and then deploy the server, which includes installing Docker if necessary, creating a container, and generating keys.
```APIDOC
## VpnServer::create()
### Description
Creates a server record in the system with an initial status of 'deploying'. This method is used to set up the server's basic information before deployment.
### Method
`VpnServer::create(array $attributes)`
### Parameters
- **user_id** (int) - Required - The ID of the user associated with the server.
- **name** (string) - Required - The name of the server.
- **host** (string) - Required - The hostname or IP address of the server.
- **port** (int) - Required - The SSH port for connecting to the server.
- **username** (string) - Required - The username for SSH authentication.
- **password** (string) - Optional - The password for SSH authentication. Alternatively, `ssh_key` can be used.
- **ssh_key** (string) - Optional - The SSH private key for authentication. Use instead of `password`.
- **install_protocol** (string) - Required - The protocol to be installed on the server (e.g., 'amnezia-wg-advanced').
- **vpn_subnet** (string) - Required - The subnet for the VPN clients (e.g., '10.8.1.0/24').
### Returns
- **serverId** (int) - The ID of the newly created server record.
## VpnServer::deploy()
### Description
Deploys the server, which involves installing Docker if it's not present, creating the VPN container, and generating necessary cryptographic keys. This method is called on a `VpnServer` instance.
### Method
`VpnServer->deploy(): array`
### Returns
- **success** (bool) - Indicates if the deployment was successful.
- **vpn_port** (int) - The port on which the VPN is active.
- **public_key** (string) - The public key generated for the VPN server.
### Example
```php
$serverId = VpnServer::create([
'user_id' => 1,
'name' => 'Singapore AWG',
'host' => '203.0.113.99',
'port' => 22,
'username' => 'root',
'password' => 'mypassword',
'install_protocol' => 'amnezia-wg-advanced',
'vpn_subnet' => '10.8.1.0/24',
]);
$server = new VpnServer($serverId);
try {
$result = $server->deploy();
echo "Server active on port " . $result['vpn_port'];
} catch (Exception $e) {
echo "Deployment failed: " . $e->getMessage();
}
```
```
--------------------------------
### GET /api/protocols/active
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Lists all protocols that are currently installed and available for creating new VPN clients. This endpoint is JWT-friendly.
```APIDOC
## GET /api/protocols/active
### Description
Retrieves a list of all available VPN protocols that can be used for client creation. The response includes the protocol ID, slug, and name, which are useful for subsequent API calls.
### Method
GET
### Endpoint
`/api/protocols/active`
### Parameters
None
### Request Example
```bash
curl -s http://localhost:8082/api/protocols/active \
-H "Authorization: Bearer $TOKEN"
```
### Response
#### Success Response (200)
- **success** (bool) - Indicates if the request was successful.
- **protocols** (array) - A list of available protocols, each with:
- **id** (int) - The unique identifier for the protocol.
- **slug** (string) - A URL-friendly identifier for the protocol.
- **name** (string) - The human-readable name of the protocol.
#### Response Example
```json
{
"success": true,
"protocols": [
{"id": 1, "slug": "amnezia-wg-advanced", "name": "AmneziaWG Advanced"},
{"id": 11, "slug": "awg2", "name": "AmneziaWG 2.0"},
{"id": 12, "slug": "mtproxy", "name": "MTProxy (Telegram)"}
]
}
```
```
--------------------------------
### Run Local Development Server
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Starts a PHP development server on `localhost:8000`. Access the panel via `http://localhost:8000`.
```bash
cd public
php -S localhost:8000
```
--------------------------------
### Create and Deploy VPN Server using PHP
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Use VpnServer::create() to provision a new server record and VpnServer::deploy() to install necessary software and configure the VPN. Ensure correct credentials and protocol settings are provided. The deploy method can throw exceptions on failure.
```php
1,
'name' => 'Singapore AWG',
'host' => '203.0.113.99',
'port' => 22,
'username' => 'root',
'password' => 'mypassword', // or use 'ssh_key' => '...'
'install_protocol' => 'amnezia-wg-advanced',
'vpn_subnet' => '10.8.1.0/24',
]);
// Deploy (installs Docker if needed, creates container, generates keys)
$server = new VpnServer($serverId);
try {
$result = $server->deploy();
// $result = ['success' => true, 'vpn_port' => 51820, 'public_key' => 'ABC123...']
echo "Server active on port " . $result['vpn_port'];
} catch (Exception $e) {
echo "Deployment failed: " . $e->getMessage();
}
// Execute arbitrary command on the remote server
$output = $server->executeCommand('docker ps --format "table {{.Names}} {{.Status}}"');
echo $output;
// List servers for a specific user
$servers = VpnServer::listByUser(1);
foreach ($servers as $s) {
echo "{$s['name']} ({$s['host']}) - {$s['status']}\n";
}
```
--------------------------------
### Install MySQL 8.0 on Ubuntu/Debian
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Installs MySQL server 8.0. Requires sudo privileges.
```bash
sudo apt install mysql-server-8.0
```
--------------------------------
### PHPUnit Unit Test Example
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
An example of a basic unit test for the `VpnServer` class using PHPUnit, demonstrating a test for the `create` method.
```php
// tests/VpnServerTest.php
use PHPUnitramework estcase;
class VpnServerTest extends TestCase
{
public function testCreate()
{
$serverId = VpnServer::create(1, 'Test', '192.168.1.1', 22, 'root', 'pass');
$this->assertIsInt($serverId);
$this->assertGreaterThan(0, $serverId);
}
}
```
--------------------------------
### Install Docker Engine on Ubuntu
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/README.md
Installs Docker Engine, CLI, containerd, and Docker Compose plugin on an Ubuntu system. Ensures Docker is enabled and running.
```bash
apt-get update -y
apt-get install -y ca-certificates curl gnupg lsb-release
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --batch --yes --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg
. /etc/os-release
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu ${VERSION_CODENAME} stable" > /etc/apt/sources.list.d/docker.list
apt-get update -y
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
systemctl enable --now docker
```
--------------------------------
### Install MySQL 8.0 on macOS
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Installs MySQL 8.0 using Homebrew. Ensure Homebrew is installed.
```bash
brew install mysql@8.0
```
--------------------------------
### Create Client with QR Code
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
Create a new VPN client and generate a QR code for easy connection setup.
```APIDOC
## Create Client with QR Code
### Description
Create a new VPN client and generate a QR code for easy connection setup.
### Method
POST
### Endpoint
/api/clients/create
### Parameters
#### Headers
- **Authorization** (string) - Required - Bearer token for authentication.
- **Content-Type** (string) - Required - Set to 'application/json'.
#### Request Body
- **server_id** (integer) - Required - The ID of the server to associate the client with.
- **name** (string) - Required - The name for the new client.
### Request Example
```bash
TOKEN="your-jwt-token"
curl -X POST http://localhost:8082/api/clients/create \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"server_id": 1,
"name": "My Phone"
}'
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the operation was successful.
- **client** (object) - Details of the created client, including configuration and QR code.
- **id** (integer) - The unique identifier for the client.
- **name** (string) - The name of the client.
- **server_id** (integer) - The ID of the server the client is connected to.
- **client_ip** (string) - The IP address assigned to the client.
- **status** (string) - The current status of the client (e.g., 'active').
- **created_at** (string) - The timestamp when the client was created.
- **config** (string) - The client configuration details.
- **qr_code** (string) - A data URI for the client's QR code.
#### Response Example
```json
{
"success": true,
"client": {
"id": 1,
"name": "My Phone",
"server_id": 1,
"client_ip": "10.8.1.1",
"status": "active",
"created_at": "2025-11-07 12:00:00",
"config": "[Interface]\nPrivateKey = ...\n...",
"qr_code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
}
}
```
**Note**: The `qr_code` field contains a data URI that can be used directly in HTML:
```html
```
```
--------------------------------
### Install Protocol on Server via API
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Use this POST request to install a specific protocol onto a given server. The request requires the server ID and the protocol ID, which can be obtained from the '/api/protocols/active' endpoint.
```bash
curl -s -X POST http://localhost:8082/api/servers/1/protocols/install \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"protocol_id": 11}'
```
--------------------------------
### Python Example: Create Client and Save QR Code
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
A Python script demonstrating how to authenticate, create a client, and save the generated QR code to a file. Requires the 'requests', 'Pillow', and 'base64' libraries.
```python
import requests
import base64
from io import BytesIO
from PIL import Image
# Get token
response = requests.post('http://localhost:8082/api/auth/token',
data={'email': 'admin@amnez.ia', 'password': 'admin123'})
token = response.json()['token']
headers = {'Authorization': f'Bearer {token}'}
# Create client
client_data = {
'server_id': 1,
'name': 'My Phone'
}
response = requests.post('http://localhost:8082/api/clients/create',
json=client_data, headers=headers)
result = response.json()
qr_code_data_uri = result['client']['qr_code']
# Save QR code as image
qr_base64 = qr_code_data_uri.split(',')[1]
qr_bytes = base64.b64decode(qr_base64)
image = Image.open(BytesIO(qr_bytes))
image.save('qr_code.png')
print(f"Client created: {result['client']['name']}")
print(f"QR code saved to qr_code.png")
```
--------------------------------
### Start Docker Development Environment
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Launches the development environment using Docker Compose. Access the panel at `http://localhost:8082`.
```bash
docker compose up -d
```
--------------------------------
### Clone Repository and Install Dependencies
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Clones the Amnezia Web Panel repository and installs project dependencies using Composer.
```bash
git clone
cd amnezia-web-panel
composer install
```
--------------------------------
### Install PHP 8.2+ on Ubuntu/Debian
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Installs PHP 8.2 and necessary extensions for development. Ensure you have sudo privileges.
```bash
sudo apt install php8.2 php8.2-cli php8.2-mysql php8.2-gd php8.2-curl php8.2-mbstring
```
--------------------------------
### Twig Templating Syntax Example
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Provides examples of Twig syntax for comments, variables, control structures (if/for), and filters.
```twig
{# Comments #}
{# Variables #}
{{ variable }}
{{ object.property }}
{{ array[0] }}
{# Control structures #}
{% if condition %}
Content
{% endif %}
{% for item in items %}
{{ item.name }}
{% endfor %}
{# Filters #}
{{ text|upper }}
{{ html|raw }} {# Careful with XSS! #}
```
--------------------------------
### Get Full Client Details with Live Stats via API
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
This GET request provides comprehensive details for a specific client, including its configuration, QR code, and real-time statistics such as data sent/received, total usage, and online status.
```bash
curl -s http://localhost:8082/api/clients/7/details \
-H "Authorization: Bearer $TOKEN"
```
--------------------------------
### Install PHP 8.2+ on macOS
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Installs PHP 8.2 using Homebrew. Ensure Homebrew is installed.
```bash
brew install php@8.2
```
--------------------------------
### Environment Variables Configuration
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Example of setting up environment variables for production using a `.env.production` file and loading them into PHP using Dotenv.
```env
DB_HOST=db
DB_NAME=amnezia_panel
DB_USER=amnezia
DB_PASS=strong_random_password_here
JWT_SECRET=another_strong_random_secret_here
ADMIN_EMAIL=admin@yourdomain.com
```
--------------------------------
### Authentication Methods
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Provides examples for user authentication, including login, retrieving the current user, checking admin status, logging out, and using authentication middleware.
```php
// Login
Auth::login($email, $password);
// Get current user
$user = Auth::user();
// Check admin
if (Auth::isAdmin()) {
// Admin logic
}
// Logout
Auth::logout();
// Middleware
requireAuth(); // In route handler
```
--------------------------------
### SQL Code Style Example
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Illustrates SQL code style guidelines, emphasizing uppercase keywords for statements and the consistent use of prepared statements for security.
```sql
-- Use uppercase keywords
SELECT id, name, created_at
FROM vpn_servers
WHERE status = 'active'
ORDER BY created_at DESC;
-- Prepared statements always
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
```
--------------------------------
### POST /api/clients/create
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Creates a new VPN client configuration. This includes generating necessary cryptographic keys, creating a protocol-specific configuration, and returning the client details along with a QR code for easy setup.
```APIDOC
## POST /api/clients/create
### Description
Generates a new VPN client configuration. This process involves creating cryptographic keys on the server, setting up the client configuration based on the server's default or a specified protocol, and providing the configuration details, including a QR code.
### Method
POST
### Endpoint
`/api/clients/create`
### Parameters
#### Request Body
- **server_id** (int) - Required - The ID of the server to associate the client with.
- **name** (string) - Required - The name for the new VPN client (e.g., 'Alice-Phone').
- **protocol_id** (int) - Optional - The ID of the protocol to use for this client. If not provided, the server's default protocol is used.
- **expires_in_days** (int) - Optional - The number of days until the client configuration expires.
### Request Example
```bash
# Create a basic client
curl -s -X POST http://localhost:8082/api/clients/create \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{ "server_id": 1, "name": "Alice-Phone" }'
# Create with expiration and traffic limit
curl -s -X POST http://localhost:8082/api/clients/create \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{ "server_id": 1, "name": "Bob-Laptop", "protocol_id": 11, "expires_in_days": 30 }'
```
### Response
#### Success Response (200)
- **success** (bool) - Indicates if the client creation was successful.
- **client** (object) - Contains the details of the newly created client:
- **id** (int) - The unique identifier for the client.
- **name** (string) - The name of the client.
- **client_ip** (string) - The IP address assigned to the client within the VPN.
- **status** (string) - The current status of the client (e.g., 'active').
- **config** (string) - The client configuration details, often in a format like WireGuard config.
- **qr_code** (string) - A base64 encoded data URL for the QR code representing the client configuration.
#### Response Example
```json
{
"success": true,
"client": {
"id": 7,
"name": "Bob-Laptop",
"client_ip": "10.8.1.3",
"status": "active",
"config": "[Interface]\nPrivateKey = ...\n\n[Peer]\n...",
"qr_code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
}
}
```
```
--------------------------------
### List Server Protocols API
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/README.md
Lists the protocols currently installed on a specific server.
```http
GET /api/servers/{id}/protocols - List installed protocols on server
```
--------------------------------
### JavaScript Code Style Example (ES6+)
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Showcases modern JavaScript (ES6+) practices, including async/await for fetching data and adding event listeners.
```javascript
// Use modern ES6+
const fetchData = async () => {
try {
const response = await fetch('/api/servers');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
};
// Event listeners
document.getElementById('btn').addEventListener('click', () => {
fetchData();
});
```
--------------------------------
### Input Validation Examples
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Shows essential input validation techniques for email format, integer casting, and string length constraints.
```php
// Email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new Exception('Invalid email');
}
// Integer
$id = (int)$_GET['id'];
// String length
if (strlen($name) < 3 || strlen($name) > 50) {
throw new Exception('Invalid name length');
}
```
--------------------------------
### Get Client Details with Stats, Config and QR
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
Retrieve comprehensive details for a client, including statistics, configuration, and QR code. Requires JWT authentication.
```bash
curl -X GET http://localhost:8082/api/clients/1/details \
-H "Authorization: Bearer $TOKEN"
```
```json
{
"success": true,
"client": {
"id": 1,
"name": "My Phone",
"server_id": 1,
"client_ip": "10.8.1.1",
"status": "active",
"created_at": "2025-11-07 12:00:00",
"stats": {
"sent": "1.23 GB",
"received": "456.78 MB",
"total": "1.68 GB",
"last_seen": "Online",
"is_online": true
},
"bytes_sent": 1320000000,
"bytes_received": 478800000,
"last_handshake": "2025-11-07 12:30:00",
"config": "[Interface]\nPrivateKey = ...\n...",
"qr_code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
}
}
```
--------------------------------
### PHP Code Style Example (PSR-12)
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
Demonstrates adherence to PSR-12 coding standards for PHP, including namespaces, classes, properties, constructors, and methods.
```php
property = $param;
}
public function method(int $arg): bool
{
if ($arg > 0) {
return true;
}
return false;
}
}
```
--------------------------------
### Get Client Details with Stats, Config and QR
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
Retrieve comprehensive details for a specific client, including usage statistics, configuration, and QR code.
```APIDOC
## Get Client Details with Stats, Config and QR
### Description
Retrieve comprehensive details for a specific client, including usage statistics, configuration, and QR code.
### Method
GET
### Endpoint
/api/clients/{client_id}/details
### Parameters
#### Path Parameters
- **client_id** (integer) - Required - The ID of the client.
#### Headers
- **Authorization** (string) - Required - Bearer token for authentication.
### Request Example
```bash
curl -X GET http://localhost:8082/api/clients/1/details \
-H "Authorization: Bearer $TOKEN"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the operation was successful.
- **client** (object) - Detailed information about the client.
- **id** (integer) - The unique identifier for the client.
- **name** (string) - The name of the client.
- **server_id** (integer) - The ID of the server the client is connected to.
- **client_ip** (string) - The IP address assigned to the client.
- **status** (string) - The current status of the client (e.g., 'active').
- **created_at** (string) - The timestamp when the client was created.
- **stats** (object) - Usage statistics for the client.
- **sent** (string) - Total data sent by the client.
- **received** (string) - Total data received by the client.
- **total** (string) - Total data used by the client.
- **last_seen** (string) - The last time the client was seen online.
- **is_online** (boolean) - Indicates if the client is currently online.
- **bytes_sent** (integer) - Total bytes sent by the client.
- **bytes_received** (integer) - Total bytes received by the client.
- **last_handshake** (string) - The timestamp of the last successful handshake.
- **config** (string) - The client configuration details.
- **qr_code** (string) - A data URI for the client's QR code.
#### Response Example
```json
{
"success": true,
"client": {
"id": 1,
"name": "My Phone",
"server_id": 1,
"client_ip": "10.8.1.1",
"status": "active",
"created_at": "2025-11-07 12:00:00",
"stats": {
"sent": "1.23 GB",
"received": "456.78 MB",
"total": "1.68 GB",
"last_seen": "Online",
"is_online": true
},
"bytes_sent": 1320000000,
"bytes_received": 478800000,
"last_handshake": "2025-11-07 12:30:00",
"config": "[Interface]\nPrivateKey = ...\n...",
"qr_code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
}
}
```
```
--------------------------------
### List Active Protocols via API
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
This cURL command retrieves a list of all protocols available for client creation on the panel. The response includes protocol IDs, slugs, and names, which are necessary for subsequent API calls like installing protocols or creating clients.
```bash
curl -s http://localhost:8082/api/protocols/active \
-H "Authorization: Bearer $TOKEN"
```
--------------------------------
### GET /api/servers/{id}/protocols
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Lists all VPN protocols that are currently installed on a specific server.
```APIDOC
## GET /api/servers/{id}/protocols
### Description
Retrieves a list of all VPN protocols that have been installed and are active on a particular server.
### Method
GET
### Endpoint
`/api/servers/{id}/protocols`
### Parameters
#### Path Parameters
- **id** (int) - Required - The ID of the server whose installed protocols are to be listed.
### Request Example
```bash
curl -s http://localhost:8082/api/servers/1/protocols \
-H "Authorization: Bearer $TOKEN"
```
```
--------------------------------
### Create Server
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
Add a new VPN server to the system.
```APIDOC
## Create Server
### Description
Add a new VPN server to the system.
### Method
POST
### Endpoint
/api/servers/create
### Parameters
#### Headers
- **Authorization** (string) - Required - Bearer token for authentication.
- **Content-Type** (string) - Required - Set to 'application/json'.
#### Request Body
- **name** (string) - Required - The name of the server.
- **host** (string) - Required - The hostname or IP address of the server.
- **port** (integer) - Required - The port number for connecting to the server (e.g., SSH port).
- **username** (string) - Required - The username for connecting to the server.
- **password** (string) - Required - The password for connecting to the server.
### Request Example
```bash
curl -X POST http://localhost:8082/api/servers/create \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "US Server",
"host": "192.168.1.100",
"port": 22,
"username": "root",
"password": "your-password"
}'
```
```
--------------------------------
### Import wg-easy Backup with cURL
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Import client configurations from a wg-easy JSON backup file into a specified server. The panel type and backup file path must be provided.
```bash
curl -s -X POST http://localhost:8082/api/servers/1/import \
-H "Authorization: Bearer $TOKEN" \
-F "panel_type=wg-easy" \
-F "backup_file=@/path/to/wg-easy-backup.json"
```
--------------------------------
### Import 3x-ui Backup with cURL
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Import client configurations from a 3x-ui JSON backup file into a specified server. Ensure the correct panel type and file path are used.
```bash
curl -s -X POST http://localhost:8082/api/servers/1/import \
-H "Authorization: Bearer $TOKEN" \
-F "panel_type=3x-ui" \
-F "backup_file=@/path/to/3x-ui-backup.json"
```
--------------------------------
### Create Client with QR Code
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
Create a new client for a server and generate a QR code for configuration. Requires JWT authentication.
```bash
TOKEN="your-jwt-token"
curl -X POST http://localhost:8082/api/clients/create \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"server_id": 1,
"name": "My Phone"
}'
```
```json
{
"success": true,
"client": {
"id": 1,
"name": "My Phone",
"server_id": 1,
"client_ip": "10.8.1.1",
"status": "active",
"created_at": "2025-11-07 12:00:00",
"config": "[Interface]\nPrivateKey = ...\n...",
"qr_code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
}
}
```
```html
```
--------------------------------
### Example Feature Commit Message
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/DEVELOPER.md
An example of a Git commit message following the specified format for a new feature, including a detailed body and closing a related issue.
```git
feat: add server statistics dashboard
- Added stats collection via SSH
- Created stats API endpoint
- Built statistics template
- Updated navigation
Closes #123
```
--------------------------------
### Python: Create Client and Save QR Code
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Creates a new VPN client, retrieves its QR code, decodes it from base64, and saves it as a PNG image. Requires the 'requests', 'Pillow', and 'base64' libraries.
```python
import requests, base64
from io import BytesIO
from PIL import Image
session = requests.Session()
token = session.post('http://localhost:8082/api/auth/token',
data={'email': 'admin@amnez.ia', 'password': 'admin123'}).json()['token']
headers = {'Authorization': f'Bearer {token}'}
client = session.post('http://localhost:8082/api/clients/create',
json={'server_id': 1, 'name': 'Python-Client'}, headers=headers).json()['client']
qr_b64 = client['qr_code'].split(',')[1]
Image.open(BytesIO(base64.b64decode(qr_b64))).save('vpn_qr.png')
print(f"Client IP: {client['client_ip']}, QR saved to vpn_qr.png")
```
--------------------------------
### GET /api/servers
Source: https://context7.com/infosave2007/amneziavpnphp/llms.txt
Lists all registered VPN servers.
```APIDOC
## GET /api/servers
### Description
Lists all registered VPN servers.
### Method
GET
### Endpoint
/api/servers
### Request Example
```bash
curl -s http://localhost:8082/api/servers \
-H "Authorization: Bearer $TOKEN"
```
```
--------------------------------
### Get Server Clients
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
Retrieve a list of clients connected to a specific server.
```APIDOC
## Get Server Clients
### Description
Retrieve a list of clients connected to a specific server.
### Method
GET
### Endpoint
/api/servers/{server_id}/clients
### Parameters
#### Path Parameters
- **server_id** (integer) - Required - The ID of the server.
#### Headers
- **Authorization** (string) - Required - Bearer token for authentication.
### Request Example
```bash
curl -X GET http://localhost:8082/api/servers/1/clients \
-H "Authorization: Bearer $TOKEN"
```
```
--------------------------------
### Create Server
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
Add a new server to the AmneziaVPN system. Requires JWT authentication and server details.
```bash
curl -X POST http://localhost:8082/api/servers/create \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "US Server",
"host": "192.168.1.100",
"port": 22,
"username": "root",
"password": "your-password"
}'
```
--------------------------------
### Get Overlimit Clients API
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/README.md
Retrieves a list of clients that have exceeded their traffic limits.
```http
GET /api/clients/overlimit - Get clients over traffic limit
```
--------------------------------
### Get Client QR Code
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/API_EXAMPLES.md
Retrieve the QR code for a specific VPN client.
```APIDOC
## Get Client QR Code
### Description
Retrieve the QR code for a specific VPN client.
### Method
GET
### Endpoint
/api/clients/{client_id}/qr
### Parameters
#### Path Parameters
- **client_id** (integer) - Required - The ID of the client.
#### Headers
- **Authorization** (string) - Required - Bearer token for authentication.
### Request Example
```bash
curl -X GET http://localhost:8082/api/clients/1/qr \
-H "Authorization: Bearer $TOKEN"
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the operation was successful.
- **qr_code** (string) - A data URI for the client's QR code.
- **client_name** (string) - The name of the client.
#### Response Example
```json
{
"success": true,
"qr_code": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
"client_name": "My Phone"
}
```
```
--------------------------------
### Get Server Import History API
Source: https://github.com/infosave2007/amneziavpnphp/blob/master/README.md
Retrieves the history of client import operations for a specific server.
```http
GET /api/servers/{id}/imports - Get import history for server
```