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
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ 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
Expand Down Expand Up @@ -310,8 +311,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 +397,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 @@ -454,8 +461,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
150 changes: 150 additions & 0 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 @@ -577,6 +588,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
157 changes: 156 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,14 @@ type ProxyServer struct {
// Persistence
store *Store

// REALITY front door. The runner is nil unless REALITY_ENABLED is set, and
// realityKeys is the key material its config was rendered from, so a
// dashboard change to the VLESS client list can be re-rendered and swapped
// in without a restart.
realityMu sync.Mutex
reality *realityRunner
realityKeys realityKeys

// Shutdown
shutdownOnce sync.Once
shutdownCh chan struct{}
Expand Down Expand Up @@ -1736,6 +1744,150 @@ func (s *ProxyServer) adminHandler() http.Handler {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
})

// ─── VLESS clients (REALITY) ──────────────────────────────────────────
//
// A UUID added here is accepted by xray within a second, and a deleted or
// disabled one stops working just as fast. Management that only took
// effect on restart would be a trap.

mux.HandleFunc("/api/vless-clients", func(w http.ResponseWriter, r *http.Request) {
if s.store == nil {
http.Error(w, "database not available", http.StatusServiceUnavailable)
return
}

switch r.Method {
case http.MethodGet:
clients, err := s.store.ListVlessClients()
if err != nil {
http.Error(w, "list failed: "+err.Error(), http.StatusInternalServerError)
return
}
s.realityMu.Lock()
enabled := s.reality != nil
s.realityMu.Unlock()
s.configMu.RLock()
pinned := len(s.cfg.RealityClientIDs) > 0
s.configMu.RUnlock()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{
"clients": clients,
"reality_enabled": enabled,
"managed_by_config": pinned,
})

case http.MethodPost:
if err := s.requireRealityManager(w); err != nil {
return
}
var req struct {
UUID string `json:"uuid"`
Label string `json:"label"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil {
http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest)
return
}
s.configMu.RLock()
xrayBin := s.cfg.RealityXrayBin
s.configMu.RUnlock()

uuid := strings.TrimSpace(req.UUID)
if uuid == "" {
generated, err := generateVlessUUID(xrayBin)
if err != nil {
http.Error(w, "could not generate a uuid: "+err.Error(), http.StatusInternalServerError)
return
}
uuid = generated
}
client, err := s.store.CreateVlessClient(uuid, req.Label)
if err != nil {
http.Error(w, "create failed: "+err.Error(), http.StatusBadRequest)
return
}
if err := s.applyVlessClients(); err != nil {
// The row is saved, so removing it here keeps the database and
// the running xray telling the same story.
s.store.DeleteVlessClient(client.ID)
http.Error(w, "xray rejected the change, nothing was applied: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(client)

default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
})

mux.HandleFunc("/api/vless-clients/", func(w http.ResponseWriter, r *http.Request) {
if s.store == nil {
http.Error(w, "database not available", http.StatusServiceUnavailable)
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/vless-clients/"), "/")
if len(parts) == 0 || parts[0] == "" {
http.Error(w, "client ID required", http.StatusBadRequest)
return
}
id := parseInt64(parts[0])

switch {
case r.Method == http.MethodDelete && len(parts) == 1:
if err := s.requireRealityManager(w); err != nil {
return
}
client, err := s.store.GetVlessClient(id)
if err != nil {
http.Error(w, "client not found", http.StatusNotFound)
return
}
if err := s.store.DeleteVlessClient(id); err != nil {
http.Error(w, "delete failed: "+err.Error(), http.StatusInternalServerError)
return
}
if err := s.applyVlessClients(); err != nil {
// Put the row back: xray never stopped accepting it, so the
// database must not claim otherwise.
if _, rerr := s.store.CreateVlessClient(client.UUID, client.Label); rerr != nil {
s.logger.Error("could not restore a refused vless client", "uuid", client.UUID, "error", rerr)
}
http.Error(w, "xray rejected the change, nothing was applied: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "deleted"})

case r.Method == http.MethodPut && len(parts) == 1:
if err := s.requireRealityManager(w); err != nil {
return
}
var req struct {
Label *string `json:"label"`
Enabled *bool `json:"enabled"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil {
http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest)
return
}
if err := s.store.UpdateVlessClient(id, req.Label, req.Enabled); err != nil {
http.Error(w, "update failed: "+err.Error(), http.StatusInternalServerError)
return
}
if err := s.applyVlessClients(); err != nil {
http.Error(w, "xray rejected the change, nothing was applied: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "updated"})

default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
})

// GET /api/tiers - list available tiers
mux.HandleFunc("/api/tiers", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
Expand Down Expand Up @@ -2079,12 +2231,15 @@ func runServer(logger *slog.Logger, configFile string) {
// rather than leaving a front door that never came up.
var reality *realityRunner
if cfg.RealityEnabled {
runner, err := startRealityForServer(cfg, dbCfg, store, logger)
runner, keys, err := startRealityForServer(cfg, dbCfg, store, logger)
if err != nil {
logger.Error("failed to start REALITY", "error", err)
os.Exit(1)
}
reality = runner
// Handed to the server so the dashboard can add and revoke VLESS
// clients without a restart.
server.reality, server.realityKeys = runner, keys
}

// Periodic stats persistence (every 60 seconds)
Expand Down
Loading
Loading