Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 33 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ Deploys on any PaaS, including the ones that expose only a single HTTP endpoint.
- **Single-Port Multiplexing** - SOCKS5, TLS, dashboards and the tunnel share one port, so it runs on Render/Koyeb/Heroku/Northflank where raw TCP never reaches the app
- **WebSocket Tunnel** - Carries SOCKS5 over an HTTP upgrade for platforms whose edge terminates TLS; ships with a matching client
- **REALITY** - Xray front door that presents a real website's certificate to an active prober; sessions still land in the SOCKS5 pipeline
- **VLESS Client Management** - Add, disable and revoke REALITY UUIDs from the dashboard; xray is reloaded in place, no restart
- **Client Mode** - Same binary exposes a local SOCKS5 port that relays through the tunnel
- **User Management** - Create, update, delete users with tier-based limits
- **Tier System** - Free, Basic, Pro, and Unlimited tiers with connection/data/bandwidth limits
- **Rate Limiting** - Token-bucket rate limiting with configurable RPS
- **Hashed Passwords** - PBKDF2-HMAC-SHA256 in the database; a stolen file is not a list of credentials
- **Message Padding** - Optional uniform-size framing so a 2-byte SOCKS5 reply is indistinguishable from bulk traffic
- **Security Headers** - CSP, XSS protection, frame options, and more
- **Admin Dashboard** - Full management UI with charts and user CRUD
Expand Down Expand Up @@ -310,8 +312,14 @@ other REALITY-capable client can import the same parameters instead:
| Fingerprint | `chrome` |
| Flow | none |

Give each device its own UUID (`xray uuid`, then list them in
`REALITY_CLIENT_IDS`) so one can be revoked without disturbing the others.
Give each device its own UUID so one can be revoked without disturbing the
others. The dashboard's **REALITY Clients** panel is the usual way: add a client,
and the UUID reaches xray immediately. Revoking one takes effect within a second
and needs no restart.

Setting `REALITY_CLIENT_IDS` still works, and pins the list from configuration:
while it is set the panel says so and refuses changes rather than accepting edits
that would quietly do nothing.

`REALITY_BIND` defaults to `0.0.0.0:443`, which is IPv4 only. On an IPv6-only
host set it to `[::]:443`.
Expand Down Expand Up @@ -390,7 +398,7 @@ Edit `config.json` or use environment variables (env vars override config file):
| `REALITY_SERVER_NAMES` | dest host | SNI values to impersonate, comma separated |
| `REALITY_PRIVATE_KEY` | generated | REALITY private key. Generated once and reused from the database when empty; `xray x25519` prints a pair |
| `REALITY_SHORT_IDS` | generated | Short ids, comma separated. Up to 16 hex characters; rotating locks out existing clients |
| `REALITY_CLIENT_IDS` | generated | VLESS UUIDs, comma separated, one per device. `xray uuid` prints one |
| `REALITY_CLIENT_IDS` | generated | VLESS UUIDs, comma separated. Pins the list and disables panel management |
| `REALITY_PUBLIC_HOST` | empty | This host's IP or domain, written into the generated client config so it is usable as-is |
| `XRAY_BIN` | xray | Path to the xray binary |
| `REALITY_CLIENT_FILE` | reality-client.json | Where the generated client config is written |
Expand Down Expand Up @@ -441,8 +449,8 @@ Client flags: `-url` (required; `https://` is accepted and mapped to `wss://`, a
# Take a backup. Works while the server is running.
socks5-proxy backup -out socks5-20261017.tar.gz

# Encrypt it. A backup contains every user password and, with REALITY enabled,
# the private key -- so encryption is worth the passphrase.
# Encrypt it. A backup holds password hashes and, with REALITY enabled, the
# private key -- so encryption is worth the passphrase.
socks5-proxy backup -out socks5-20261017.tar.gz -passphrase 'a good passphrase'

# Look inside without restoring anything.
Expand All @@ -454,8 +462,9 @@ socks5-proxy restore -in socks5-20261017.tar.gz

The archive holds `socks5.db`, `config.json` and, when REALITY is enabled,
`reality-client.json`. **Restoring the same archive keeps every REALITY client
working**, because the keypair travels with it; restoring an older or different
one invalidates every client you have imported.
working**, because the keypair travels with it and the managed VLESS UUIDs live
in the database; restoring an older or different one invalidates every client you
have imported.

`restore` refuses to run while the server is up, because replacing a database
that another process still has open is how SQLite ends up cleaning up the wrong
Expand Down Expand Up @@ -518,9 +527,19 @@ go test -run TestRealityEndToEnd -v ./... # needs xray on PATH
on shutdown. Its own log lines are relayed into this server's log.
- `whitelist` and `blacklist` apply to the SOCKS5 port, the HTTP proxy
(`CONNECT` and forward) and the tunnel alike.
- A backup contains every user password in the clear, plus the REALITY private
key when it is enabled. Use `-passphrase` for anything that leaves the machine,
and keep the passphrase somewhere other than the backup directory.
- User passwords are stored as **PBKDF2-HMAC-SHA256 hashes** (600k iterations,
per-user salt), never as text, so a database file or a backup does not hand
over working credentials. Accounts created before hashing existed keep
working: their password is verified against the old value and the row is
rewritten on the next successful login, so an install upgrades itself one
account at a time with no migration to run.
- `PROXY_USER`/`PROXY_PASS` and `ADMIN_USER`/`ADMIN_PASS` come from the
environment or config file and stay as they are — there is nothing in the
database to hash, and the file is already a secret you control.
- A backup contains password **hashes**, not passwords, plus the REALITY private
key when it is enabled. The key is the reason to use `-passphrase` for
anything that leaves the machine; keep the passphrase somewhere other than the
backup directory.
- `/health` is the only endpoint reachable without admin credentials, and it
returns `{"status":"ok"}` with no uptime or version: on a public port it is
the one thing a scanner can read, so it says nothing. `/metrics`,
Expand Down Expand Up @@ -592,6 +611,10 @@ at `/prometheus` with `basic_auth` configured.
| PUT | `/api/users/:id` | Update user |
| DELETE | `/api/users/:id` | Delete user |
| POST | `/api/users/:id/reset` | Reset a user's data usage |
| GET | `/api/vless-clients` | REALITY client UUIDs, and whether they can be managed |
| POST | `/api/vless-clients` | Add a client; the UUID is generated if omitted |
| PUT | `/api/vless-clients/:id` | Relabel, or enable/disable, a client |
| DELETE | `/api/vless-clients/:id` | Revoke a client, effective immediately |
| GET | `/api/top-destinations?n=10` | Most-visited destinations |
| GET | `/api/history/stats?n=60` | Historical connection/byte counters |
| GET | `/api/history/destinations` | Destination history |
Expand Down
177 changes: 175 additions & 2 deletions database.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"log/slog"
"os"
"path/filepath"
"strings"
"sync"
"time"

Expand Down Expand Up @@ -121,6 +122,16 @@ func (s *Store) migrate() error {
)`,
`CREATE INDEX IF NOT EXISTS idx_user_connections_user ON user_connections(user_id)`,
`CREATE INDEX IF NOT EXISTS idx_user_connections_time ON user_connections(connected_at)`,
// VLESS client UUIDs for the REALITY front door. One row per client, so
// a revoked id is a deleted or disabled row rather than an edit of a
// comma-joined string, and the dashboard has a name to show for each.
`CREATE TABLE IF NOT EXISTS vless_clients (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uuid TEXT UNIQUE NOT NULL,
label TEXT NOT NULL DEFAULT '',
enabled INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`,
}

for _, q := range queries {
Expand Down Expand Up @@ -405,6 +416,14 @@ func (s *Store) CreateUser(username, password, tier string) (*User, error) {
return nil, fmt.Errorf("unknown tier: %s", tier)
}

// Hash before the row exists, so no code path can write a plaintext
// password by accident. The caller keeps the plaintext it passed in and is
// the one that may show it once.
hashed, err := HashPassword(password)
if err != nil {
return nil, err
}

var expiry *string
if t.DaysExpiry > 0 {
e := time.Now().AddDate(0, 0, t.DaysExpiry).Format("2006-01-02 15:04:05")
Expand All @@ -417,7 +436,7 @@ func (s *Store) CreateUser(username, password, tier string) (*User, error) {
result, err := s.db.Exec(
`INSERT INTO users (username, password_hash, tier, max_connections, bandwidth_mbps, data_limit_bytes, expiry)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
username, password, tier, t.MaxConnections, t.BandwidthMbps, t.DataLimitBytes, expiry,
username, hashed, tier, t.MaxConnections, t.BandwidthMbps, t.DataLimitBytes, expiry,
)
if err != nil {
return nil, fmt.Errorf("insert user: %w", err)
Expand Down Expand Up @@ -526,7 +545,11 @@ func (s *Store) UpdateUser(id int64, tier *string, password *string, enabled *bo
}
}
if password != nil {
_, err := s.db.Exec("UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?", *password, id)
hashed, err := HashPassword(*password)
if err != nil {
return err
}
_, err = s.db.Exec("UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?", hashed, id)
if err != nil {
return err
}
Expand Down Expand Up @@ -569,6 +592,17 @@ func (s *Store) DeleteUser(id int64) error {
return tx.Commit()
}

// UpgradeUserPassword rewrites a row that still holds a pre-hashing password.
// It is called after a successful login, so an install cleans itself up one
// account at a time instead of needing a migration over every credential.
func (s *Store) UpgradeUserPassword(id int64, hash string) error {
s.mu.Lock()
defer s.mu.Unlock()

_, err := s.db.Exec("UPDATE users SET password_hash=?, updated_at=CURRENT_TIMESTAMP WHERE id=?", hash, id)
return err
}

func (s *Store) ResetUserData(id int64) error {
s.mu.Lock()
defer s.mu.Unlock()
Expand All @@ -577,6 +611,145 @@ func (s *Store) ResetUserData(id int64) error {
return err
}

// ─── VLESS clients ─────────────────────────────────────────────────────────
//
// The UUIDs xray accepts on the REALITY inbound. Only enabled rows reach the
// rendered config, so disabling one revokes it without deleting the record.

type VlessClient struct {
ID int64 `json:"id"`
UUID string `json:"uuid"`
Label string `json:"label"`
Enabled bool `json:"enabled"`
CreatedAt string `json:"created_at"`
}

// IsUUID reports whether s looks like a UUID xray would accept. Deliberately
// shape-only: this is the trust boundary between an operator typing into the
// dashboard and the xray config, so the check is cheap and never guesses.
func IsUUID(s string) bool {
if len(s) != 36 {
return false
}
for i, c := range s {
switch i {
case 8, 13, 18, 23:
if c != '-' {
return false
}
default:
if !strings.ContainsRune("0123456789abcdefABCDEF", c) {
return false
}
}
}
return true
}

func (s *Store) CreateVlessClient(uuid, label string) (*VlessClient, error) {
uuid = strings.TrimSpace(uuid)
if !IsUUID(uuid) {
return nil, fmt.Errorf("%q is not a UUID", uuid)
}
s.mu.Lock()
res, err := s.db.Exec("INSERT INTO vless_clients (uuid, label) VALUES (?, ?)", uuid, label)
if err != nil {
s.mu.Unlock()
return nil, err
}
id, err := res.LastInsertId()
s.mu.Unlock()
if err != nil {
return nil, err
}
// Read the row back rather than echoing the arguments: created_at is a
// database default, and a response that shows it empty is worse than one
// that shows the truth.
return s.GetVlessClient(id)
}

func (s *Store) ListVlessClients() ([]VlessClient, error) {
s.mu.Lock()
defer s.mu.Unlock()

rows, err := s.db.Query("SELECT id, uuid, label, enabled, created_at FROM vless_clients ORDER BY id")
if err != nil {
return nil, err
}
defer rows.Close()

out := []VlessClient{}
for rows.Next() {
var c VlessClient
var enabled int
if err := rows.Scan(&c.ID, &c.UUID, &c.Label, &enabled, &c.CreatedAt); err != nil {
return nil, err
}
c.Enabled = enabled != 0
out = append(out, c)
}
return out, rows.Err()
}

// EnabledVlessClientUUIDs is what the xray config is rendered from.
func (s *Store) EnabledVlessClientUUIDs() ([]string, error) {
clients, err := s.ListVlessClients()
if err != nil {
return nil, err
}
out := make([]string, 0, len(clients))
for _, c := range clients {
if c.Enabled {
out = append(out, c.UUID)
}
}
return out, nil
}

func (s *Store) GetVlessClient(id int64) (*VlessClient, error) {
s.mu.Lock()
defer s.mu.Unlock()

var c VlessClient
var enabled int
err := s.db.QueryRow("SELECT id, uuid, label, enabled, created_at FROM vless_clients WHERE id=?", id).
Scan(&c.ID, &c.UUID, &c.Label, &enabled, &c.CreatedAt)
if err != nil {
return nil, err
}
c.Enabled = enabled != 0
return &c, nil
}

func (s *Store) UpdateVlessClient(id int64, label *string, enabled *bool) error {
s.mu.Lock()
defer s.mu.Unlock()

if label != nil {
if _, err := s.db.Exec("UPDATE vless_clients SET label=? WHERE id=?", *label, id); err != nil {
return err
}
}
if enabled != nil {
value := 0
if *enabled {
value = 1
}
if _, err := s.db.Exec("UPDATE vless_clients SET enabled=? WHERE id=?", value, id); err != nil {
return err
}
}
return nil
}

func (s *Store) DeleteVlessClient(id int64) error {
s.mu.Lock()
defer s.mu.Unlock()

_, err := s.db.Exec("DELETE FROM vless_clients WHERE id=?", id)
return err
}

// ─── Connection Tracking ───────────────────────────────────────────────────

func (s *Store) TrackConnectionStart(userID int64, target string) (int64, error) {
Expand Down
Loading
Loading