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
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,23 @@ 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.

### Billing a client to a user of its own

By default every REALITY session arrives on the service's shared SOCKS
credentials, so no tier, limit or counter applies to it. The **Meter it** button
on a client creates a SOCKS user for that client alone and routes its sessions
there through an xray rule keyed on the client's email. From then on its traffic
is metered, limited and counted like anyone else's, and the user shows up in the
user list where its tier can be changed like any other.

The credentials xray needs are **derived**, not stored: a per-install secret
produces them on every render, so only the hash sits in the users table and no
readable password is kept anywhere.

One cost to know about: each linked client adds an outbound and a routing rule to
the xray config, so a very large number of clients makes that config big. A few
hundred is fine; beyond that, this wants rethinking rather than growing.

`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 @@ -681,7 +698,7 @@ at `/prometheus` with `basic_auth` configured.
| DELETE | `/api/mtproto-secrets/:id` | Revoke a phone, effective immediately |
| 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 |
| PUT | `/api/vless-clients/:id` | Relabel, enable/disable, or bill a client to a SOCKS user of its own |
| 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 |
Expand Down
102 changes: 101 additions & 1 deletion database.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package main

import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/hex"
"fmt"
Expand Down Expand Up @@ -132,6 +134,15 @@ func (s *Store) migrate() error {
enabled INTEGER NOT NULL DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`,
// The SOCKS user a REALITY client's traffic is billed to. Empty means the
// client falls back to the shared credentials, which is how every client
// behaved before this existed.
`CREATE TABLE IF NOT EXISTS vless_links (
client_id INTEGER PRIMARY KEY,
username TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (client_id) REFERENCES vless_clients(id) ON DELETE CASCADE
)`,
// MTProto secrets for the Telegram front door. The stored value is the
// shareable form, dd followed by 32 hex characters, so it can be pasted
// into a phone without editing.
Expand Down Expand Up @@ -163,6 +174,92 @@ func (s *Store) migrate() error {
return nil
}

// ─── REALITY client links ───────────────────────────────────────────────────

const dbVlessLinkSecret = "vless_link_secret"

// EnsureVlessLinkSecret returns this install's link secret, generating it the
// first time it is asked for.
//
// It exists so a REALITY client's proxy password can be put in an xray config
// without storing a readable password anywhere: the value is derived from this
// secret, and only its hash is kept in the users table.
func (s *Store) EnsureVlessLinkSecret() ([]byte, error) {
if saved := s.LoadConfig()[dbVlessLinkSecret]; saved != "" {
if secret, err := hex.DecodeString(saved); err == nil && len(secret) == 32 {
return secret, nil
}
}

secret := make([]byte, 32)
if _, err := rand.Read(secret); err != nil {
return nil, err
}
if err := s.SaveConfig(dbVlessLinkSecret, hex.EncodeToString(secret)); err != nil {
return nil, err
}
return secret, nil
}

// VlessLinkCredentials derives the SOCKS username and password for a linked
// REALITY client. Both are a function of this install's link secret and the
// client id, so xray's config can carry them and the database can keep only the
// password's hash.
func VlessLinkCredentials(secret []byte, clientID int64) (username, password string) {
mac := hmac.New(sha256.New, secret)
fmt.Fprintf(mac, "vless:%d", clientID)
return fmt.Sprintf("xr%d", clientID), hex.EncodeToString(mac.Sum(nil))
}

// VlessLink says which SOCKS user a REALITY client's traffic belongs to.
type VlessLink struct {
ClientID int64 `json:"client_id"`
Username string `json:"username"`
}

func (s *Store) LinkVlessClient(clientID int64, username string) error {
s.mu.Lock()
defer s.mu.Unlock()

_, err := s.db.Exec(
`INSERT INTO vless_links (client_id, username) VALUES (?, ?)
ON CONFLICT(client_id) DO UPDATE SET username=excluded.username`,
clientID, username)
return err
}

func (s *Store) UnlinkVlessClient(clientID int64) error {
s.mu.Lock()
defer s.mu.Unlock()

_, err := s.db.Exec("DELETE FROM vless_links WHERE client_id=?", clientID)
return err
}

// ListVlessLinks is keyed by client id, so the renderer can look a client up
// without scanning.
func (s *Store) ListVlessLinks() (map[int64]string, error) {
s.mu.Lock()
defer s.mu.Unlock()

rows, err := s.db.Query("SELECT client_id, username FROM vless_links")
if err != nil {
return nil, err
}
defer rows.Close()

out := map[int64]string{}
for rows.Next() {
var id int64
var username string
if err := rows.Scan(&id, &username); err != nil {
return nil, err
}
out[id] = username
}
return out, rows.Err()
}

// ─── Config persistence ────────────────────────────────────────────────────

func (s *Store) LoadConfig() map[string]string {
Expand Down Expand Up @@ -530,7 +627,7 @@ func (s *Store) ListUsers() ([]User, error) {
}
defer rows.Close()

var users []User
users := []User{}
for rows.Next() {
var u User
var enabled int
Expand Down Expand Up @@ -643,6 +740,9 @@ type VlessClient struct {
Label string `json:"label"`
Enabled bool `json:"enabled"`
CreatedAt string `json:"created_at"`
// Linked is the SOCKS user this client's traffic is billed to, empty when
// it falls through on the shared credentials.
Linked string `json:"linked,omitempty"`
}

// IsUUID reports whether s looks like a UUID xray would accept. Deliberately
Expand Down
25 changes: 25 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -1859,6 +1859,14 @@ func (s *ProxyServer) adminHandler() http.Handler {
s.realityMu.Lock()
enabled := s.reality != nil
s.realityMu.Unlock()
if links, lerr := s.store.ListVlessLinks(); lerr == nil && len(links) > 0 {
for i := range clients {
if name, ok := links[clients[i].ID]; ok {
linked := name
clients[i].Linked = linked
}
}
}
s.configMu.RLock()
pinned := len(s.cfg.RealityClientIDs) > 0
s.configMu.RUnlock()
Expand Down Expand Up @@ -1960,11 +1968,28 @@ func (s *ProxyServer) adminHandler() http.Handler {
var req struct {
Label *string `json:"label"`
Enabled *bool `json:"enabled"`
// Link bills this client's traffic to a SOCKS user of its own, so
// its tier, limits and accounting apply. False unlinks.
Link *bool `json:"link"`
Tier *string `json:"tier"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil {
http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest)
return
}
if req.Link != nil {
if err := s.linkVlessClient(id, *req.Link, req.Tier); err != nil {
http.Error(w, "link failed: "+err.Error(), http.StatusBadRequest)
return
}
if *req.Link {
if links, lerr := s.store.ListVlessLinks(); lerr == nil {
if name, ok := links[id]; ok {
w.Header().Set("X-Linked-User", name)
}
}
}
}
if err := s.store.UpdateVlessClient(id, req.Label, req.Enabled); err != nil {
http.Error(w, "update failed: "+err.Error(), http.StatusInternalServerError)
return
Expand Down
Loading
Loading