From 05f7aa94bbe15af6ef1e2d36144978c0d7e20f66 Mon Sep 17 00:00:00 2001 From: GlobalTechInfo Date: Sat, 17 Oct 2026 18:30:27 +0500 Subject: [PATCH] Manage VLESS client UUIDs from the dashboard Until now the REALITY client list was a comma-joined config value, so revoking a UUID meant editing configuration and restarting the service. A management screen that only takes effect on restart is a trap, so this makes the change real. The list lives in a vless_clients table, one row per client. Precedence is unchanged in spirit: REALITY_CLIENT_IDS still pins the list from configuration and now says so, because accepting edits that quietly do nothing is worse than refusing them. An id left behind by the old comma-joined value is adopted into the table on first run rather than dropped -- otherwise the first dashboard change would revoke a client that is still in the field. Making it live meant teaching the xray supervisor to re-point itself. The reload carries a config that has already passed `xray run --test`, so an invalid change is refused and the running front door keeps serving; the supervisor is the only thing that stops and starts the child, and it answers once the new child is actually accepting connections. Measured live: an add applies in 0.08s. Two refusals worth having. Removing the last client is rejected, because xray with no clients is a front door that rejects everyone and an operator should have to mean it. And a refused change restores the row rather than dropping it, so the database never claims something xray does not do. Verified live against xray on a real port: a UUID added through the API served traffic immediately, the same client failed the moment it was revoked, the untouched client kept working, and xray's own log named the refusal (proxy/vless/encoding: rejected). Covered end to end in tests too, including the case the race detector caught on the way: s.cfg is written under configMu while being read here. --- README.md | 18 +- database.go | 150 ++++++++++++++ main.go | 157 ++++++++++++++- reality.go | 348 +++++++++++++++++++++++++++----- reality_test.go | 14 +- vless_test.go | 526 ++++++++++++++++++++++++++++++++++++++++++++++++ web/index.html | 144 +++++++++++++ 7 files changed, 1300 insertions(+), 57 deletions(-) create mode 100644 vless_test.go diff --git a/README.md b/README.md index 65bf066..2d45693 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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`. @@ -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 | @@ -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 diff --git a/database.go b/database.go index 8129ffa..ec18546 100644 --- a/database.go +++ b/database.go @@ -8,6 +8,7 @@ import ( "log/slog" "os" "path/filepath" + "strings" "sync" "time" @@ -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 { @@ -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) { diff --git a/main.go b/main.go index 08b4d25..36f7f73 100644 --- a/main.go +++ b/main.go @@ -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{} @@ -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 { @@ -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) diff --git a/reality.go b/reality.go index 7ef496d..ff590f0 100644 --- a/reality.go +++ b/reality.go @@ -10,6 +10,7 @@ import ( "fmt" "log/slog" "net" + "net/http" "os" "os/exec" "path/filepath" @@ -445,12 +446,22 @@ func resolveRealityKeys(cfg Config, persisted map[string]string, store *Store, l keys.ShortID = hex.EncodeToString(raw) } + // Client UUIDs, in precedence order: + // + // 1. REALITY_CLIENT_IDS. Configuration pinning always wins, which is the + // same promise the rest of the environment handling makes. + // 2. The vless_clients table, which the dashboard manages. + // 3. The legacy comma-joined config value, adopted into the table on first + // run so an upgrade does not revoke anyone's UUID. + // 4. A generated one, which becomes a table row so it survives a restart. keys.ClientIDs = nonEmpty(cfg.RealityClientIDs) - if len(keys.ClientIDs) == 0 && persisted[dbRealityClientIDs] != "" { - keys.ClientIDs = splitList(persisted[dbRealityClientIDs]) + if len(keys.ClientIDs) == 0 && store != nil { + keys.ClientIDs, _ = store.EnabledVlessClientUUIDs() + if len(keys.ClientIDs) == 0 && persisted[dbRealityClientIDs] != "" { + keys.ClientIDs = adoptLegacyClientIDs(store, splitList(persisted[dbRealityClientIDs]), logger) + } } - generatedIDs := len(keys.ClientIDs) == 0 - if generatedIDs { + if len(keys.ClientIDs) == 0 { out, err := runXray(bin, "uuid") if err != nil { return keys, err @@ -461,6 +472,13 @@ func resolveRealityKeys(cfg Config, persisted map[string]string, store *Store, l if len(keys.ClientIDs) == 0 { return keys, errors.New("xray uuid returned no id") } + if store != nil { + // A UUID that changes on every restart would silently break every + // saved client profile, so the generated one is stored. + if _, err := store.CreateVlessClient(keys.ClientIDs[0], "generated"); err != nil { + logger.Warn("could not store the generated VLESS id; it will change on restart", "error", err) + } + } } if keys.ServerName = firstNonEmpty(cfg.RealityServerNames...); keys.ServerName == "" { @@ -478,14 +496,32 @@ func resolveRealityKeys(cfg Config, persisted map[string]string, store *Store, l if generatedShortID { saveRealitySetting(store, logger, dbRealityShortID, keys.ShortID) } - if generatedIDs { - saveRealitySetting(store, logger, dbRealityClientIDs, strings.Join(keys.ClientIDs, ",")) - } } return keys, nil } +// adoptLegacyClientIDs moves an id list from the old comma-joined config value +// into the table. Without this, the first dashboard change would drop the ids +// that upgrade brought with it, because the table would then shadow the config. +func adoptLegacyClientIDs(store *Store, ids []string, logger *slog.Logger) []string { + for _, id := range ids { + if !IsUUID(id) { + continue + } + if _, err := store.CreateVlessClient(id, "migrated"); err != nil { + logger.Warn("could not migrate a REALITY client id; it will be dropped from the managed list", "error", err) + continue + } + } + kept, err := store.EnabledVlessClientUUIDs() + if err != nil { + logger.Warn("could not read the migrated VLESS ids", "error", err) + return nil + } + return kept +} + func saveRealitySetting(store *Store, logger *slog.Logger, key, value string) { if err := store.SaveConfig(key, value); err != nil { // Non-fatal: the value is still in use this run, it just will not @@ -566,73 +602,100 @@ func pruneStaleRealityConfigs(maxAge time.Duration) { // realityRunner owns the xray child process. type realityRunner struct { - bin string - cfgFile string - logger *slog.Logger + bin string + logger *slog.Logger + host string + port int mu sync.Mutex + cfgFile string // owned by supervise() once running; read under mu elsewhere cmd *exec.Cmd stopped bool + reload chan realityReload stop chan struct{} exited chan struct{} } +// realityReload asks the supervisor to swap in a new, already validated config +// file. The supervisor replies on done; a nil error means xray is running on the +// new file. +type realityReload struct { + cfgFile string + done chan error +} + // startReality validates the rendered config before serving, so a broken setup // fails loudly at startup instead of leaving a silent dead front door. func startReality(cfg Config, k realityKeys, logger *slog.Logger) (*realityRunner, error) { - data, err := renderRealityServerConfig(cfg, k) + bin := cfg.RealityXrayBin + if bin == "" { + bin = "xray" + } + cfgFile, err := renderValidatedServerConfig(bin, cfg, k) if err != nil { return nil, err } + pruneStaleRealityConfigs(24 * time.Hour) + + r := &realityRunner{ + bin: bin, + cfgFile: cfgFile, + logger: logger, + reload: make(chan realityReload, 1), + stop: make(chan struct{}), + exited: make(chan struct{}), + } + if host, port, err := splitHostPort(cfg.RealityBind); err == nil { + r.host, r.port = host, port + } + go r.supervise() + + r.waitReady() + return r, nil +} + +// renderValidatedServerConfig writes the config to a private temp file and asks +// xray to parse it. A config that does not validate is deleted and reported, so +// a bad change never takes a working front door down. +func renderValidatedServerConfig(bin string, cfg Config, k realityKeys) (string, error) { + data, err := renderRealityServerConfig(cfg, k) + if err != nil { + return "", err + } + file, err := os.CreateTemp("", "xray-reality-*.json") if err != nil { - return nil, fmt.Errorf("write xray config: %w", err) + return "", fmt.Errorf("write xray config: %w", err) } cfgFile := file.Name() if _, err := file.Write(data); err != nil { file.Close() os.Remove(cfgFile) - return nil, fmt.Errorf("write xray config: %w", err) + return "", fmt.Errorf("write xray config: %w", err) } file.Close() // CreateTemp already opens 0600, which matters: the file holds the REALITY // private key and the proxy credentials. - bin := cfg.RealityXrayBin - if bin == "" { - bin = "xray" - } if _, err := runXray(bin, "run", "-c", cfgFile, "--test"); err != nil { // runXray already carries xray's own complaint, which is the part worth // reading ("failed to listen...", "invalid private key", and so on). os.Remove(cfgFile) - return nil, err - } - - pruneStaleRealityConfigs(24 * time.Hour) - - r := &realityRunner{ - bin: bin, - cfgFile: cfgFile, - logger: logger, - stop: make(chan struct{}), - exited: make(chan struct{}), + return "", err } - go r.supervise() - - if host, port, err := splitHostPort(cfg.RealityBind); err == nil { - r.waitReady(host, port, 10*time.Second) - } - return r, nil + return cfgFile, nil } // waitReady logs whether the REALITY port started answering. A failure here is // not fatal: xray may still be retrying, and its own log carries the reason. -func (r *realityRunner) waitReady(host string, port int, timeout time.Duration) { - target := net.JoinHostPort(host, strconv.Itoa(port)) - deadline := time.Now().Add(timeout) +func (r *realityRunner) waitReady() { + if r.host == "" { + return + } + target := net.JoinHostPort(r.host, strconv.Itoa(r.port)) + deadline := time.Now().Add(10 * time.Second) for time.Now().Before(deadline) { conn, err := net.DialTimeout("tcp", target, 300*time.Millisecond) if err == nil { @@ -646,9 +709,19 @@ func (r *realityRunner) waitReady(host string, port int, timeout time.Duration) // supervise keeps xray alive. Without this a single crash would silently remove // the front door while every dashboard still reported a healthy proxy. +// +// It is also the only place the child is started, stopped and re-pointed, which +// is what makes a config swap safe: the new file is validated by the caller +// before it is ever offered here, and this goroutine does the stop-then-start +// with nothing else touching the process. func (r *realityRunner) supervise() { defer close(r.exited) + // A reload waiting for its new child to come up. It is answered once the + // child is running, so the dashboard's reply means "xray is serving the new + // list", not "xray was asked to". + var answered *realityReload + delay := 5 * time.Second for { if r.isStopped() { @@ -656,25 +729,60 @@ func (r *realityRunner) supervise() { } w := &xrayLogWriter{logger: r.logger} - cmd := exec.Command(r.bin, "run", "-c", r.cfgFile) + cmd := exec.Command(r.bin, "run", "-c", r.configFile()) cmd.Stdout, cmd.Stderr = w, w if err := cmd.Start(); err != nil { r.logger.Error("reality: cannot start xray", "error", err) + if answered != nil { + answered.done <- fmt.Errorf("xray did not start: %w", err) + answered = nil + } } else { r.setCmd(cmd) - waitErr := cmd.Wait() - r.setCmd(nil) - if r.isStopped() { + if answered != nil { + r.waitReady() + answered.done <- nil + answered = nil + } + // Wait runs in its own goroutine so the loop can still act on a + // reload or a stop while the child is running. + exited := make(chan error, 1) + go func() { exited <- cmd.Wait() }() + + select { + case waitErr := <-exited: + r.setCmd(nil) + if r.isStopped() { + return + } + r.logger.Error("reality: xray exited, restarting", "error", waitErr) + case req := <-r.reload: + r.logger.Info("reality: reloading client list") + r.stopChild(exited) + r.swapConfig(req.cfgFile) + answered = &req + // A deliberate reload is not a crash: start the new child at + // once instead of serving the backoff first. + continue + case <-r.stop: + r.setCmd(nil) + r.stopChild(exited) return } - r.logger.Error("reality: xray exited, restarting", "error", waitErr) } select { case <-time.After(delay): case <-r.stop: return + case req := <-r.reload: + // No child is running here, so the reply waits for the next + // successful start. Claiming it is applied now would be a lie the + // dashboard would show as "live". + r.swapConfig(req.cfgFile) + answered = &req + continue } if delay < time.Minute { delay *= 2 @@ -685,6 +793,42 @@ func (r *realityRunner) supervise() { } } +// stopChild ends the running child and waits for the process to actually be +// gone, so the port is free before its replacement starts. +func (r *realityRunner) stopChild(exited chan error) { + r.mu.Lock() + cmd := r.cmd + r.mu.Unlock() + + if cmd == nil || cmd.Process == nil { + return + } + _ = cmd.Process.Signal(syscall.SIGTERM) + select { + case <-exited: + case <-time.After(5 * time.Second): + _ = cmd.Process.Kill() + <-exited + } +} + +// swapConfig installs a new config file and deletes the one it replaces. +func (r *realityRunner) swapConfig(next string) { + r.mu.Lock() + old := r.cfgFile + r.cfgFile = next + r.mu.Unlock() + if old != "" && old != next { + _ = os.Remove(old) + } +} + +func (r *realityRunner) configFile() string { + r.mu.Lock() + defer r.mu.Unlock() + return r.cfgFile +} + func (r *realityRunner) setCmd(cmd *exec.Cmd) { r.mu.Lock() r.cmd = cmd @@ -697,6 +841,34 @@ func (r *realityRunner) isStopped() bool { return r.stopped } +// Reload renders a new config and swaps it in. The config is validated by xray +// first, so an invalid change is refused and the running front door keeps +// serving; the previous file is removed only once the new one is accepted. +func (r *realityRunner) Reload(cfg Config, k realityKeys) error { + bin := cfg.RealityXrayBin + if bin == "" { + bin = r.bin + } + next, err := renderValidatedServerConfig(bin, cfg, k) + if err != nil { + return err + } + + req := realityReload{cfgFile: next, done: make(chan error, 1)} + select { + case r.reload <- req: + case <-time.After(10 * time.Second): + _ = os.Remove(next) + return errors.New("xray supervisor is not responding") + } + select { + case err := <-req.done: + return err + case <-time.After(15 * time.Second): + return errors.New("timed out waiting for xray to reload") + } +} + // Stop asks xray to exit, then removes the config holding the private key. func (r *realityRunner) Stop() { r.mu.Lock() @@ -722,23 +894,23 @@ func (r *realityRunner) Stop() { _ = cmd.Process.Kill() } } - _ = os.Remove(r.cfgFile) + _ = os.Remove(r.configFile()) } // ─── Wiring ───────────────────────────────────────────────────────────────── // startRealityForServer resolves keys, starts the child and writes the client // config operators copy to their own devices. -func startRealityForServer(cfg Config, persisted map[string]string, store *Store, logger *slog.Logger) (*realityRunner, error) { +func startRealityForServer(cfg Config, persisted map[string]string, store *Store, logger *slog.Logger) (*realityRunner, realityKeys, error) { if _, err := exec.LookPath(orDefault(cfg.RealityXrayBin, "xray")); err != nil { if _, statErr := os.Stat(orDefault(cfg.RealityXrayBin, "xray")); statErr != nil { - return nil, fmt.Errorf("reality_enabled is set but the xray binary is missing: set XRAY_BIN or install it (Docker images ship it at /usr/local/bin/xray)") + return nil, realityKeys{}, fmt.Errorf("reality_enabled is set but the xray binary is missing: set XRAY_BIN or install it (Docker images ship it at /usr/local/bin/xray)") } } keys, err := resolveRealityKeys(cfg, persisted, store, logger) if err != nil { - return nil, err + return nil, keys, err } if _, port, err := splitHostPort(cfg.RealityBind); err == nil && port == cfg.SinglePort && cfg.SinglePort != 0 { @@ -747,7 +919,7 @@ func startRealityForServer(cfg Config, persisted map[string]string, store *Store runner, err := startReality(cfg, keys, logger) if err != nil { - return nil, err + return nil, keys, err } address := cfg.RealityPublicHost @@ -777,7 +949,87 @@ func startRealityForServer(cfg Config, persisted map[string]string, store *Store "public_key", keys.PublicKey, "short_id", keys.ShortID, "client_id", strings.Join(keys.ClientIDs, ",")) - return runner, nil + return runner, keys, nil +} + +// ─── Live client-list management ─────────────────────────────────────────── + +// generateVlessUUID asks xray for an id, which is the same generator that +// produced the first one. It runs a subprocess because the binary is already a +// dependency of this feature and rolling our own UUID would be one more thing +// to get wrong. +func generateVlessUUID(bin string) (string, error) { + out, err := runXray(orDefault(bin, "xray"), "uuid") + if err != nil { + return "", err + } + fields := strings.Fields(out) + if len(fields) == 0 || !IsUUID(fields[0]) { + return "", fmt.Errorf("xray uuid returned %q", strings.TrimSpace(out)) + } + return fields[0], nil +} + +// realityManager returns the runner and keys when the dashboard is allowed to +// change the client list. +func (s *ProxyServer) realityManager() (*realityRunner, realityKeys, error) { + s.realityMu.Lock() + defer s.realityMu.Unlock() + + if s.reality == nil { + return nil, realityKeys{}, errors.New("REALITY is not enabled, so there is no xray client list to manage") + } + // REALITY_CLIENT_IDS pins the list from configuration, which outranks the + // database everywhere else in this program. Editing the table would then + // look like it worked and change nothing. + s.configMu.RLock() + pinned := len(s.cfg.RealityClientIDs) > 0 + s.configMu.RUnlock() + if pinned { + return nil, realityKeys{}, errors.New("REALITY_CLIENT_IDS is set, which pins the client list; unset it to manage clients here") + } + return s.reality, s.realityKeys, nil +} + +// requireRealityManager is the handler-side guard for the mutating routes. +func (s *ProxyServer) requireRealityManager(w http.ResponseWriter) error { + if _, _, err := s.realityManager(); err != nil { + http.Error(w, err.Error(), http.StatusConflict) + return err + } + return nil +} + +// applyVlessClients re-renders the xray config from the enabled rows and swaps +// it into the running child. The config is validated before xray is restarted, +// so a rejected change leaves the front door serving what it was serving. +func (s *ProxyServer) applyVlessClients() error { + runner, keys, err := s.realityManager() + if err != nil { + return err + } + s.realityMu.Lock() + keys.ClientIDs, err = s.store.EnabledVlessClientUUIDs() + s.realityMu.Unlock() + if err != nil { + return err + } + if len(keys.ClientIDs) == 0 { + return errors.New("this would leave xray with no clients, so the front door would refuse every connection; add one first") + } + + s.configMu.RLock() + cfg := s.cfg + s.configMu.RUnlock() + + if err := runner.Reload(cfg, keys); err != nil { + return err + } + s.realityMu.Lock() + s.realityKeys = keys + s.realityMu.Unlock() + s.logger.Info("reality client list applied", "clients", len(keys.ClientIDs)) + return nil } func orDefault(v, fallback string) string { diff --git a/reality_test.go b/reality_test.go index 506a50d..a77dce5 100644 --- a/reality_test.go +++ b/reality_test.go @@ -336,8 +336,13 @@ func TestResolveRealityKeysPersistsGeneratedValues(t *testing.T) { if saved[dbRealityShortID] != keys.ShortID { t.Errorf("short id not persisted: %v", saved) } - if saved[dbRealityClientIDs] != strings.Join(keys.ClientIDs, ",") { - t.Errorf("client ids not persisted: %v", saved) + // The uuid belongs in the managed table now, not in a comma-joined string. + clients, err := store.ListVlessClients() + if err != nil { + t.Fatalf("list clients: %v", err) + } + if len(clients) != 1 || clients[0].UUID != keys.ClientIDs[0] || !clients[0].Enabled { + t.Fatalf("generated uuid not stored as a managed client: %+v", clients) } // A restart must reuse the persisted pair rather than rotate it. @@ -348,6 +353,9 @@ func TestResolveRealityKeysPersistsGeneratedValues(t *testing.T) { if again.PrivateKey != keys.PrivateKey || again.ShortID != keys.ShortID { t.Errorf("restart rotated the key material: %q/%q", again.PrivateKey, again.ShortID) } + if len(again.ClientIDs) != 1 || again.ClientIDs[0] != keys.ClientIDs[0] { + t.Errorf("restart rotated the client id: %v, want %v", again.ClientIDs, keys.ClientIDs) + } } func TestResolveRealityKeysPrefersOperatorValues(t *testing.T) { @@ -383,7 +391,7 @@ func TestRealityRefusesWithoutXrayBinary(t *testing.T) { cfg.RealityEnabled = true cfg.RealityXrayBin = filepath.Join(t.TempDir(), "definitely-not-here") - _, err := startRealityForServer(cfg, nil, nil, slog.New(slog.NewTextHandler(io.Discard, nil))) + _, _, err := startRealityForServer(cfg, nil, nil, slog.New(slog.NewTextHandler(io.Discard, nil))) if err == nil { t.Fatal("starting REALITY without the xray binary should fail") } diff --git a/vless_test.go b/vless_test.go new file mode 100644 index 0000000..ebd4f02 --- /dev/null +++ b/vless_test.go @@ -0,0 +1,526 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// ─── Store ────────────────────────────────────────────────────────────────── + +func TestVlessClientCRUD(t *testing.T) { + store := newTestStore(t) + + const uuid = "0cd94710-7290-40da-857d-5f5a7670cd62" + client, err := store.CreateVlessClient(uuid, "alice's phone") + if err != nil { + t.Fatalf("create: %v", err) + } + if !client.Enabled || client.Label != "alice's phone" { + t.Errorf("created client = %+v, want enabled with its label", client) + } + + // The same UUID twice is an error, not a second row: two rows would make + // revocation ambiguous. + if _, err := store.CreateVlessClient(uuid, "impostor"); err == nil { + t.Error("the same uuid was accepted twice") + } + + if _, err := store.CreateVlessClient("not-a-uuid", ""); err == nil { + t.Error("a non-uuid was accepted") + } + + clients, err := store.ListVlessClients() + if err != nil || len(clients) != 1 { + t.Fatalf("list = %+v, %v", clients, err) + } + + disabled := false + if err := store.UpdateVlessClient(client.ID, nil, &disabled); err != nil { + t.Fatalf("disable: %v", err) + } + uuids, err := store.EnabledVlessClientUUIDs() + if err != nil { + t.Fatalf("enabled uuids: %v", err) + } + if len(uuids) != 0 { + t.Errorf("a disabled client is still offered to xray: %v", uuids) + } + + // A label-only edit must not silently re-enable it. + if err := store.UpdateVlessClient(client.ID, stringPtr("renamed"), nil); err != nil { + t.Fatalf("relabel: %v", err) + } + clients, _ = store.ListVlessClients() + if clients[0].Label != "renamed" || clients[0].Enabled { + t.Errorf("relabel changed more than the label: %+v", clients[0]) + } + + if err := store.DeleteVlessClient(client.ID); err != nil { + t.Fatalf("delete: %v", err) + } + if clients, _ := store.ListVlessClients(); len(clients) != 0 { + t.Errorf("delete left rows behind: %+v", clients) + } +} + +func stringPtr(v string) *string { return &v } + +// ─── Where the client list comes from ─────────────────────────────────────── + +func TestResolveRealityKeysUsesManagedClients(t *testing.T) { + bin := fakeXray(t, "private", "public") + store := newTestStore(t) + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + + cfg := DefaultConfig() + cfg.RealityXrayBin = bin + + // An id left behind by an earlier version, in the old comma-joined value. + // Upgrading must adopt it, not drop it: the table would otherwise shadow + // the config and revoke a client that is still in the field. + const legacyID = "11111111-2222-3333-4444-555555555555" + persisted := map[string]string{dbRealityClientIDs: legacyID} + + keys, err := resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve: %v", err) + } + if len(keys.ClientIDs) != 1 || keys.ClientIDs[0] != legacyID { + t.Fatalf("client ids = %v, want the legacy id adopted", keys.ClientIDs) + } + clients, _ := store.ListVlessClients() + if len(clients) != 1 || clients[0].Label != "migrated" { + t.Fatalf("legacy id was not adopted into the table: %+v", clients) + } + + // Adding a managed client adds to the list. The adopted id stays: upgrading + // and then adding someone must not quietly revoke the client that was + // already in the field. + const managedID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" + if _, err := store.CreateVlessClient(managedID, "new phone"); err != nil { + t.Fatalf("create managed: %v", err) + } + keys, err = resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve again: %v", err) + } + if len(keys.ClientIDs) != 2 { + t.Errorf("client ids = %v, want the adopted and the new client", keys.ClientIDs) + } + found := false + for _, id := range keys.ClientIDs { + if id == managedID { + found = true + } + } + if !found { + t.Errorf("the new client is missing from %v", keys.ClientIDs) + } + + // Disabling one leaves the other alone. + all, _ := store.ListVlessClients() + for _, c := range all { + if c.UUID == managedID { + off := false + if err := store.UpdateVlessClient(c.ID, nil, &off); err != nil { + t.Fatalf("disable: %v", err) + } + } + } + keys, err = resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve with one disabled: %v", err) + } + if len(keys.ClientIDs) != 1 || keys.ClientIDs[0] != legacyID { + t.Errorf("client ids = %v, want only the still-enabled one", keys.ClientIDs) + } + + // Configuration still outranks the table, as it does everywhere else. + cfg.RealityClientIDs = []string{legacyID} + keys, err = resolveRealityKeys(cfg, persisted, store, log) + if err != nil { + t.Fatalf("resolve with config: %v", err) + } + if len(keys.ClientIDs) != 1 || keys.ClientIDs[0] != legacyID { + t.Errorf("client ids = %v, want the configured id to win", keys.ClientIDs) + } +} + +// ─── The API ──────────────────────────────────────────────────────────────── + +// adminRequest drives the admin mux the way the dashboard does. +func adminRequest(t *testing.T, s *ProxyServer, method, path string, body string) *httptest.ResponseRecorder { + t.Helper() + var reader io.Reader + if body != "" { + reader = strings.NewReader(body) + } + req := httptest.NewRequest(method, path, reader) + req.RemoteAddr = "127.0.0.1:5000" + rec := httptest.NewRecorder() + s.adminHandler().ServeHTTP(rec, req) + return rec +} + +func TestVlessClientAPIRequiresReality(t *testing.T) { + cfg := DefaultConfig() + cfg.AdminPort = freePort(t) + cfg.AuthEnabled = false + s := NewProxyServer(cfg) + s.store = newTestStore(t) + + // Listing works without xray, so the dashboard can say why it is empty. + rec := adminRequest(t, s, http.MethodGet, "/api/vless-clients", "") + if rec.Code != http.StatusOK { + t.Fatalf("GET with REALITY off = %d, want 200: %s", rec.Code, rec.Body) + } + var listing struct { + Clients []VlessClient `json:"clients"` + RealityEnabled bool `json:"reality_enabled"` + ManagedByConfig bool `json:"managed_by_config"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &listing); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if listing.RealityEnabled { + t.Error("reality_enabled should be false when REALITY is off") + } + + // Mutating is refused rather than accepted-and-ignored. + for _, tc := range []struct{ method, path, body string }{ + {http.MethodPost, "/api/vless-clients", `{"label":"x"}`}, + {http.MethodPut, "/api/vless-clients/1", `{"enabled":false}`}, + {http.MethodDelete, "/api/vless-clients/1", ""}, + } { + rec := adminRequest(t, s, tc.method, tc.path, tc.body) + if rec.Code != http.StatusConflict { + t.Errorf("%s %s with REALITY off = %d, want 409: %s", tc.method, tc.path, rec.Code, rec.Body) + } + } +} + +func TestVlessClientAPIRejectsPinnedListAndLastRemoval(t *testing.T) { + bin := requireXray(t) + store := newTestStore(t) + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + + cfg := DefaultConfig() + cfg.RealityXrayBin = bin + cfg.RealityBind = fmt.Sprintf("127.0.0.1:%d", freePort(t)) + keys, err := resolveRealityKeys(cfg, nil, store, log) + if err != nil { + t.Fatalf("resolve: %v", err) + } + runner, err := startReality(cfg, keys, log) + if err != nil { + t.Fatalf("start reality: %v", err) + } + defer runner.Stop() + + s := NewProxyServer(cfg) + s.store = store + s.reality, s.realityKeys = runner, keys + + // resolveRealityKeys generated and stored one client, which is now the only + // one there is. + clients, err := store.ListVlessClients() + if err != nil || len(clients) != 1 { + t.Fatalf("expected exactly the generated client: %+v, %v", clients, err) + } + created := clients[0] + + // Removing the last client would leave xray with nobody to serve, which + // looks like a successful edit and breaks every client on the planet. + rec := adminRequest(t, s, http.MethodDelete, fmt.Sprintf("/api/vless-clients/%d", created.ID), "") + if rec.Code != http.StatusInternalServerError { + t.Fatalf("removing the last client = %d, want an error: %s", rec.Code, rec.Body) + } + if !strings.Contains(rec.Body.String(), "no clients") { + t.Errorf("error %q should explain that no client would be left", rec.Body) + } + if clients, _ := store.ListVlessClients(); len(clients) != 1 { + t.Fatalf("a refused removal still deleted the row: %+v", clients) + } + + // A pinned list is refused instead of silently doing nothing. + s.configMu.Lock() + s.cfg.RealityClientIDs = []string{keys.ClientIDs[0]} + s.configMu.Unlock() + rec = adminRequest(t, s, http.MethodPost, "/api/vless-clients", `{"label":"ignored"}`) + if rec.Code != http.StatusConflict { + t.Fatalf("POST with a pinned list = %d, want 409: %s", rec.Code, rec.Body) + } + if !strings.Contains(rec.Body.String(), "REALITY_CLIENT_IDS") { + t.Errorf("error %q should name the variable pinning the list", rec.Body) + } +} + +// ─── End to end ───────────────────────────────────────────────────────────── + +// TestRealityClientRevocationTakesEffect runs the whole loop: a UUID is revoked +// from the database, and a REALITY client still configured with it must stop +// working without the proxy being restarted. A management screen that does not +// revoke anything is worse than no management screen. +func TestRealityClientRevocationTakesEffect(t *testing.T) { + bin := requireXray(t) + store := newTestStore(t) + log := slog.New(slog.NewTextHandler(io.Discard, nil)) + + // An origin the client will actually reach. + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, "revocation-e2e-ok") + })) + defer origin.Close() + + proxyCfg := DefaultConfig() + proxyCfg.AuthEnabled = false + proxyCfg.AdminEnabled = false + proxyCfg.SecurityHeadersEnabled = false + proxyCfg.RateLimitEnabled = false + proxyCfg.ProxyPort = freePort(t) + + realityPort := freePort(t) + cfg := proxyCfg + cfg.RealityXrayBin = bin + cfg.RealityEnabled = true + cfg.RealityBind = fmt.Sprintf("127.0.0.1:%d", realityPort) + cfg.RealityPublicHost = "127.0.0.1" + + // One config for the server and the runner: the reload re-renders from + // server.cfg, exactly as runServer does. + server := NewProxyServer(cfg) + ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", proxyCfg.ProxyPort)) + if err != nil { + t.Fatalf("listen socks: %v", err) + } + defer ln.Close() + go func() { + for { + conn, aerr := ln.Accept() + if aerr != nil { + return + } + go server.handleClient(conn, "") + } + }() + + const revokedID = "0cd94710-7290-40da-857d-5f5a7670cd62" + const keptID = "0cd94710-7290-40da-857d-5f5a7670cd63" + for _, id := range []string{revokedID, keptID} { + if _, err := store.CreateVlessClient(id, "test client"); err != nil { + t.Fatalf("seed client %s: %v", id, err) + } + } + + keys, err := resolveRealityKeys(cfg, nil, store, log) + if err != nil { + t.Fatalf("resolve keys: %v", err) + } + if len(keys.ClientIDs) != 2 { + t.Fatalf("client ids = %v, want both managed clients", keys.ClientIDs) + } + + runner, err := startReality(cfg, keys, log) + if err != nil { + t.Fatalf("start reality: %v", err) + } + defer runner.Stop() + + server.store = store + server.reality, server.realityKeys = runner, keys + + // A REALITY client whose config still carries the id about to be revoked. + staleClient := startRealityTestClient(t, bin, cfg, keys, revokedID, freePort(t)) + liveClient := startRealityTestClient(t, bin, cfg, keys, keptID, freePort(t)) + + fetch := func(clientPort int) error { + u, err := url.Parse(fmt.Sprintf("socks5://127.0.0.1:%d", clientPort)) + if err != nil { + return err + } + httpClient := &http.Client{ + Transport: &http.Transport{Proxy: http.ProxyURL(u)}, + Timeout: 25 * time.Second, + } + resp, err := httpClient.Get(origin.URL) + if err != nil { + return err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return err + } + if string(body) != "revocation-e2e-ok" { + return fmt.Errorf("body = %q", body) + } + return nil + } + + // Both work before the change. + if err := fetch(staleClient); err != nil { + t.Fatalf("the client that is about to be revoked should work now: %v", err) + } + if err := fetch(liveClient); err != nil { + t.Fatalf("the client that stays should work now: %v", err) + } + + // Revoke through the same path the dashboard uses. + rec := adminRequest(t, server, http.MethodDelete, fmt.Sprintf("/api/vless-clients/%d", idOfUUID(t, store, revokedID)), "") + if rec.Code != http.StatusOK { + t.Fatalf("revoke = %d: %s", rec.Code, rec.Body) + } + + // No restart, no waiting: the revoked UUID must already be refused. + if err := fetch(staleClient); err == nil { + t.Error("a revoked uuid still works; the dashboard change did not reach xray") + } + // The other client is untouched. + if err := fetch(liveClient); err != nil { + t.Errorf("revoking one client broke another: %v", err) + } +} + +// startRealityTestClient runs a second xray as the client and returns the port +// of its local SOCKS5 inbound. +func startRealityTestClient(t *testing.T, bin string, cfg Config, keys realityKeys, uuid string, clientPort int) int { + t.Helper() + + clientKeys := keys + clientKeys.ClientIDs = []string{uuid} + data, err := renderRealityClientConfig(cfg.RealityPublicHost, portOf(t, cfg.RealityBind), "127.0.0.1", clientPort, clientKeys) + if err != nil { + t.Fatalf("render client: %v", err) + } + file := filepath.Join(t.TempDir(), "client.json") + if err := os.WriteFile(file, data, 0o600); err != nil { + t.Fatalf("write client config: %v", err) + } + + cmd := exec.Command(bin, "run", "-c", file) + // The client's own log is the only place a refusal shows up, and a silent + // skip here would look like a flaky proxy rather than a rejected UUID. + cmd.Stdout, cmd.Stderr = &testWriter{t: t, tag: "client"}, &testWriter{t: t, tag: "client"} + if err := cmd.Start(); err != nil { + t.Fatalf("start client xray: %v", err) + } + t.Cleanup(func() { + cmd.Process.Kill() + cmd.Wait() + }) + + deadline := time.Now().Add(15 * time.Second) + for { + conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", clientPort), 200*time.Millisecond) + if err == nil { + conn.Close() + return clientPort + } + if time.Now().After(deadline) { + t.Fatalf("client socks port %d never opened: %v", clientPort, err) + } + time.Sleep(100 * time.Millisecond) + } +} + +// testWriter routes a subprocess log into the test output. +type testWriter struct { + t *testing.T + tag string + buf string +} + +func (w *testWriter) Write(p []byte) (int, error) { + w.buf += string(p) + for { + i := strings.IndexByte(w.buf, '\n') + if i < 0 { + break + } + w.t.Logf("[%s] %s", w.tag, w.buf[:i]) + w.buf = w.buf[i+1:] + } + return len(p), nil +} + +func portOf(t *testing.T, addr string) int { + t.Helper() + _, port, err := splitHostPort(addr) + if err != nil { + t.Fatalf("split %q: %v", addr, err) + } + return port +} + +func idOfUUID(t *testing.T, store *Store, uuid string) int64 { + t.Helper() + clients, err := store.ListVlessClients() + if err != nil { + t.Fatalf("list clients: %v", err) + } + for _, c := range clients { + if c.UUID == uuid { + return c.ID + } + } + t.Fatalf("no managed client with uuid %s", uuid) + return 0 +} + +// The dashboard is one HTML file with inline script, so the cheapest honest +// check is that the panel is wired to the endpoints this build serves. +func TestDashboardVlessPanelWiring(t *testing.T) { + data, err := os.ReadFile("web/index.html") + if err != nil { + t.Fatalf("read dashboard: %v", err) + } + html := string(data) + + for _, id := range []string{"vless-body", "v-label", "v-uuid", "vless-msg"} { + if !strings.Contains(html, `id="`+id+`"`) { + t.Errorf("dashboard has no element with id %q", id) + } + } + for _, fn := range []string{"loadVlessClients", "createVlessClient", "toggleVlessClient", "deleteVlessClient"} { + if !strings.Contains(html, "function "+fn+"(") { + t.Errorf("dashboard has no %s function", fn) + } + } + if !strings.Contains(html, "/api/vless-clients") { + t.Error("dashboard never talks to /api/vless-clients") + } + // Defined is not wired: the list has to load on startup. + if !strings.Contains(html, "\nloadVlessClients();") { + t.Error("loadVlessClients() is not called on startup") + } + + cfg := DefaultConfig() + cfg.AuthEnabled = false + s := NewProxyServer(cfg) + s.store = newTestStore(t) + rec := adminRequest(t, s, http.MethodGet, "/api/vless-clients", "") + if rec.Code != http.StatusOK { + t.Fatalf("GET /api/vless-clients = %d", rec.Code) + } + var listing struct { + Clients []VlessClient `json:"clients"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &listing); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if listing.Clients == nil { + t.Error("clients must serialise as [], not null, so the panel can loop over it") + } +} diff --git a/web/index.html b/web/index.html index 2b983d3..eb1018c 100644 --- a/web/index.html +++ b/web/index.html @@ -155,6 +155,7 @@ .theme-toggle:hover{color:var(--accent);border-color:var(--accent);box-shadow:0 0 10px var(--shadow)} .theme-toggle:focus-visible{outline:2px solid var(--accent);outline-offset:2px} .actions{display:flex;gap:5px;flex-wrap:wrap} + .uuid{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:12px} .form-box{background:var(--bg-elevated);border:1px solid var(--border);box-shadow:0 1px 2px var(--shadow);border-radius:12px;padding:20px;position:relative;overflow:hidden} .form-box::before{content:'';position:absolute;top:0;left:0;right:0;height:2px;background:linear-gradient(90deg,transparent,var(--accent),transparent)} .form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:15px} @@ -259,6 +260,46 @@

User Management

+
+

REALITY Clients (VLESS UUIDs)

+
+
+

+ Each UUID is one client allowed through the REALITY front door. Changes are + applied to xray immediately: a deleted or disabled UUID stops working + within a second, with no restart. +

+
+
+ + +
+
+ + +
+
+ +
+ +
+ + + + + + + + + + + + + +
IDLabelUUIDStatusActions
Loading...
+
+
+

Settings

@@ -537,10 +578,113 @@

Settings

}catch(e){msg.textContent='Network error: '+e.message;msg.className='msg msg-err';msg.style.display='block'} } +function el(tag,text){var e=document.createElement(tag);if(text!==undefined)e.textContent=text;return e} + +async function loadVlessClients(){ + var msg=document.getElementById('vless-msg'); + var tbody=document.getElementById('vless-body'); + try{ + var r=await fetch('/api/vless-clients',{credentials:'same-origin'}); + var data=await r.json(); + if(!data.reality_enabled){ + tbody.innerHTML=''; + var row=el('tr'),cell=el('td',''); + cell.colSpan=5; + cell.style.color='#555'; + cell.textContent='REALITY is not enabled, so there is no client list to manage.'; + row.appendChild(cell);tbody.appendChild(row); + document.querySelector('#v-label').disabled=true; + document.querySelector('#v-uuid').disabled=true; + return; + } + if(data.managed_by_config){ + msg.textContent='REALITY_CLIENT_IDS is set, which pins the list. Unset it to manage clients here.'; + msg.className='msg msg-err';msg.style.display='block'; + } + tbody.innerHTML=''; + if(!data.clients||data.clients.length===0){ + var empty=el('tr'),ecell=el('td','No clients. Add one above.'); + ecell.colSpan=5;ecell.style.color='#555'; + empty.appendChild(ecell);tbody.appendChild(empty); + return; + } + for(var i=0;i