feat(clients): let admins set PersistentKeepalive on tunnel clients (#6377)

* feat(clients): let admins set PersistentKeepalive on tunnel clients

model.Client already carries KeepAlive, and every AmneziaWG/WireGuard client
config emitter already writes PersistentKeepalive when it is above zero -- but
nothing in the UI could set it, so it stayed 0 and the line was never emitted.

Without it a peer that goes quiet has nothing to trigger a handshake: WireGuard
only initiates when it has data to send. An idle client stays disconnected
after any interruption -- a NAT mapping timing out, a device sleeping, the
panel restarting -- until the user generates traffic themselves.

New clients default to 25, the conventional value, which also keeps the NAT
mapping open. Existing clients keep whatever they have, and 0 remains valid and
means "do not send keepalives".

* fix(clients): let an explicit 0 actually disable PersistentKeepalive

Addresses review feedback on the previous commit.

UpdateInboundClient carries a stored keepalive forward whenever the incoming
one is zero, so the settings JSON and the running peer survive a metadata-only
edit that omits the field. That was a 0 -> 0 no-op while no UI could set a
nonzero value. Now that the client form can, the carry-forward became reachable
in the other direction: a client created at the form's default of 25 could
never be returned to 0, and the hint text shipped to all 13 locales -- "0
disables it" -- described something the backend silently refused. The save even
reported success, because a settings blob that came back byte-identical skips
the transaction entirely.

The zero value cannot carry that distinction, so model.Client.KeepAlive becomes
*int: nil means the field was never sent, &0 means "send no keepalives". The
pointer survives the internal marshal in ClientService.Update, which is where an
explicit 0 was being erased by omitempty before UpdateInboundClient ever saw it.
ClientRecord.KeepAlive stays a plain int -- it is the stored column, where
"unset" has no meaning -- and the conversions bridge the two.

Two tests, both red before this change in the direction they cover: an explicit
0 must reach wg_keep_alive, and an update that omits the field must still leave
a stored 25 alone.

Also adds the output transform every other numeric field in the client form
already has, so a cleared box sends 0 rather than null.

* fix(clients): repair the keepalive pointer conversion after the main merge

Merging main brought buildAmneziaWGProxy (#6326) in beside the
Client.KeepAlive int -> *int change without reconciling the new call site,
so internal/sub stopped compiling and took every package importing it with
it. The two sides touched different lines, so git merged them without a
conflict -- the green `make verify` on 112b19a8 predates the break.

ToClient also wrapped a stored 0 in a pointer, so omitempty stopped
omitting: a VLESS client's settings JSON gained "keepAlive": 0 on the
attach and bulk-attach paths, and that JSON reaches xray-core verbatim
through GenXrayInboundConfig. wg_keep_alive cannot tell "off" from "never
set", so a stored 0 now stays nil.

Also copies the regenerated openapi.json over the docs mirror, which
nothing in CI checks, and trims two comment blocks to the two-line cap.

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
This commit is contained in:
YoungReckless4
2026-09-10 23:32:42 +03:00
committed by GitHub
parent 64b6e43e2b
commit 8f162994ef
33 changed files with 220 additions and 34 deletions
+2 -2
View File
@@ -242,7 +242,7 @@ func (l *Local) AddClient(ctx context.Context, ib *model.Inbound, client model.C
"publicKey": client.PublicKey,
"allowedIPs": client.AllowedIPs,
"preSharedKey": client.PreSharedKey,
"keepAlive": wgKeepAlive(client.KeepAlive),
"keepAlive": wgKeepAlive(client.KeepAliveSeconds()),
}
return l.AddUser(ctx, ib, user)
}
@@ -283,7 +283,7 @@ func (l *Local) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail stri
"publicKey": payload.PublicKey,
"allowedIPs": payload.AllowedIPs,
"preSharedKey": payload.PreSharedKey,
"keepAlive": wgKeepAlive(payload.KeepAlive),
"keepAlive": wgKeepAlive(payload.KeepAliveSeconds()),
}
return l.AddUser(ctx, ib, user)
}
+5 -5
View File
@@ -587,7 +587,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model
"publicKey": client.PublicKey,
"allowedIPs": client.AllowedIPs,
"preSharedKey": client.PreSharedKey,
"keepAlive": keepAliveStr(client.KeepAlive),
"keepAlive": keepAliveStr(client.KeepAliveSeconds()),
})
if err1 == nil {
logger.Debug("Client added on", rt.Name(), ":", client.Email)
@@ -734,7 +734,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
if clients[0].PreSharedKey == "" {
clients[0].PreSharedKey = old.PreSharedKey
}
if clients[0].KeepAlive == 0 {
if clients[0].KeepAlive == nil {
clients[0].KeepAlive = old.KeepAlive
}
// ForwardedPorts is AmneziaWG-only (WireGuard's own inbound never
@@ -801,8 +801,8 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
if clients[0].PreSharedKey != "" {
newMap["preSharedKey"] = clients[0].PreSharedKey
}
if clients[0].KeepAlive > 0 {
newMap["keepAlive"] = clients[0].KeepAlive
if ka := clients[0].KeepAliveSeconds(); ka > 0 {
newMap["keepAlive"] = ka
}
if oldInbound.Protocol == model.AmneziaWG && clients[0].ForwardedPorts != "" {
newMap["forwardedPorts"] = clients[0].ForwardedPorts
@@ -1014,7 +1014,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
"publicKey": clients[0].PublicKey,
"allowedIPs": clients[0].AllowedIPs,
"preSharedKey": clients[0].PreSharedKey,
"keepAlive": keepAliveStr(clients[0].KeepAlive),
"keepAlive": keepAliveStr(clients[0].KeepAliveSeconds()),
})
if err1 == nil {
logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email)
@@ -0,0 +1,102 @@
package service
import (
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func inboundKeepAlive(t *testing.T, inboundSvc *InboundService, ibId int, email string) int {
t.Helper()
ib, err := inboundSvc.GetInbound(ibId)
if err != nil {
t.Fatalf("GetInbound %d: %v", ibId, err)
}
clients, err := inboundSvc.GetClients(ib)
if err != nil {
t.Fatalf("GetClients %d: %v", ibId, err)
}
for i := range clients {
if clients[i].Email == email {
return clients[i].KeepAliveSeconds()
}
}
t.Fatalf("email %q not found on inbound %d", email, ibId)
return 0
}
// seedKeepAliveClient attaches one WireGuard client already carrying a
// PersistentKeepalive, and returns its inbound and client-record id.
func seedKeepAliveClient(t *testing.T, email string, keepAlive int) (*model.Inbound, int) {
t.Helper()
svc := &ClientService{}
seeded := model.Client{
Email: email,
SubID: "sub-" + email,
Enable: true,
AllowedIPs: []string{"10.0.0.5/32"},
KeepAlive: model.KeepAlivePtr(keepAlive),
}
ib := mkInbound(t, 51820, model.WireGuard, clientsSettings(t, []model.Client{seeded}))
if err := svc.SyncInbound(nil, ib.Id, []model.Client{seeded}); err != nil {
t.Fatalf("seed linkage: %v", err)
}
return ib, lookupClientRecord(t, email).Id
}
// Carrying forward on a zero incoming keepalive was a 0 -> 0 no-op while no UI
// could set the field; once the client form could, "0 disables it" was unreachable.
func TestUpdateCanClearKeepAliveOnAnExistingClient(t *testing.T) {
setupBulkDB(t)
inboundSvc := &InboundService{}
svc := &ClientService{}
ib, recId := seedKeepAliveClient(t, "ka@x", 25)
if got := inboundKeepAlive(t, inboundSvc, ib.Id, "ka@x"); got != 25 {
t.Fatalf("seeded keepAlive = %d, want 25", got)
}
updated := model.Client{
Email: "ka@x",
Enable: true,
AllowedIPs: []string{"10.0.0.5/32"},
KeepAlive: model.KeepAlivePtr(0),
}
if _, err := svc.Update(inboundSvc, recId, updated, 0); err != nil {
t.Fatalf("Update: %v", err)
}
if got := inboundKeepAlive(t, inboundSvc, ib.Id, "ka@x"); got != 0 {
t.Fatalf("inbound keepAlive after an explicit 0 = %d, want 0", got)
}
if got := lookupClientRecord(t, "ka@x").KeepAlive; got != 0 {
t.Fatalf("stored wg_keep_alive after an explicit 0 = %d, want 0", got)
}
}
// The other half of the contract: a payload that never mentions keepAlive (a
// metadata-only edit from the bot or the API) leaves the stored value alone.
func TestUpdateWithoutKeepAlivePreservesTheStoredValue(t *testing.T) {
setupBulkDB(t)
inboundSvc := &InboundService{}
svc := &ClientService{}
ib, recId := seedKeepAliveClient(t, "ka@x", 25)
updated := model.Client{
Email: "ka@x",
Enable: true,
AllowedIPs: []string{"10.0.0.5/32"},
}
if _, err := svc.Update(inboundSvc, recId, updated, 0); err != nil {
t.Fatalf("Update: %v", err)
}
if got := inboundKeepAlive(t, inboundSvc, ib.Id, "ka@x"); got != 25 {
t.Fatalf("inbound keepAlive after an edit that omitted it = %d, want 25", got)
}
if got := lookupClientRecord(t, "ka@x").KeepAlive; got != 25 {
t.Fatalf("stored wg_keep_alive after an edit that omitted it = %d, want 25", got)
}
}
+2 -2
View File
@@ -249,8 +249,8 @@ func defaultWireguardClients(settingsJSON string, existing, clients []model.Clie
if c.PreSharedKey != "" {
m["preSharedKey"] = c.PreSharedKey
}
if c.KeepAlive > 0 {
m["keepAlive"] = c.KeepAlive
if ka := c.KeepAliveSeconds(); ka > 0 {
m["keepAlive"] = ka
}
interfaceClients[i] = m
}
@@ -130,7 +130,7 @@ func wgPeerList(t *testing.T, settings map[string]any) []map[string]any {
func TestGetXrayConfigWireGuardPeers(t *testing.T) {
clients := []model.Client{
{Email: "alice@wg.test", Enable: true, PublicKey: "pub-alice", AllowedIPs: []string{"10.0.0.2/32"}, KeepAlive: 25},
{Email: "alice@wg.test", Enable: true, PublicKey: "pub-alice", AllowedIPs: []string{"10.0.0.2/32"}, KeepAlive: model.KeepAlivePtr(25)},
{Email: "bob@wg.test", Enable: true, PublicKey: "pub-bob", AllowedIPs: []string{"10.0.0.3/32"}},
}
seedWGInbound(t, "wg-multi", 51820, clients)
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "اتركه فارغًا للتعيين التلقائي؛ افصل بين الإدخالات بفواصل",
"amneziaWgForwardedPorts": "المنافذ المُعاد توجيهها",
"amneziaWgForwardedPortsHint": "المنافذ/النطاقات المُعاد توجيهها (DNAT) لهذا العميل، مثل 80, 443, 8000-8100. اتركها فارغة إن لم تكن مطلوبة.",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "إعدادات AmneziaWG",
"mtprotoSecret": "سر MTProto",
"mtprotoSecretHint": "سر FakeTLS الخاص بالعميل. أعد التوليد لتغييره.",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "Leave empty to auto-assign; separate entries with commas",
"amneziaWgForwardedPorts": "Forwarded Ports",
"amneziaWgForwardedPortsHint": "Ports/ranges DNAT'd to this client, e.g. 80, 443, 8000-8100. Leave empty for none.",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "AmneziaWG config",
"mtprotoSecret": "MTProto secret",
"mtprotoSecretHint": "The client's FakeTLS secret. Regenerate to rotate it.",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "Déjalo vacío para asignar automáticamente; separa las entradas con comas",
"amneziaWgForwardedPorts": "Puertos reenviados",
"amneziaWgForwardedPortsHint": "Puertos/rangos redirigidos (DNAT) a este cliente, p. ej. 80, 443, 8000-8100. Déjalo vacío si no aplica.",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "Configuración de AmneziaWG",
"mtprotoSecret": "Secreto MTProto",
"mtprotoSecretHint": "El secreto FakeTLS del cliente. Vuelve a generarlo para cambiarlo.",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "برای تخصیص خودکار خالی بگذارید؛ ورودی‌ها را با کاما جدا کنید",
"amneziaWgForwardedPorts": "پورت‌های هدایت‌شده",
"amneziaWgForwardedPortsHint": "پورت‌ها/محدوده‌های DNAT شده به این کلاینت، مثلاً 80, 443, 8000-8100. برای غیرفعال بودن خالی بگذارید.",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "پیکربندی AmneziaWG",
"mtprotoSecret": "سکرت MTProto",
"mtprotoSecretHint": "سکرت FakeTLS این کلاینت. برای تعویض، دوباره تولید کنید.",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "Biarkan kosong untuk penetapan otomatis; pisahkan entri dengan koma",
"amneziaWgForwardedPorts": "Port yang Diteruskan",
"amneziaWgForwardedPortsHint": "Port/rentang yang di-DNAT ke klien ini, mis. 80, 443, 8000-8100. Biarkan kosong jika tidak ada.",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "Konfigurasi AmneziaWG",
"mtprotoSecret": "Secret MTProto",
"mtprotoSecretHint": "Secret FakeTLS klien. Buat ulang untuk menggantinya.",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "空欄で自動割り当て。複数指定はカンマ区切り",
"amneziaWgForwardedPorts": "転送ポート",
"amneziaWgForwardedPortsHint": "このクライアントに転送するポート/範囲。例: 80, 443, 8000-8100。空欄で転送なし。",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "AmneziaWG 設定",
"mtprotoSecret": "MTProto シークレット",
"mtprotoSecretHint": "このクライアントの FakeTLS シークレット。変更するには再生成します。",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "Deixe vazio para atribuir automaticamente; separe as entradas com vírgulas",
"amneziaWgForwardedPorts": "Portas encaminhadas",
"amneziaWgForwardedPortsHint": "Portas/intervalos redirecionados (DNAT) para este cliente, ex. 80, 443, 8000-8100. Deixe vazio se não aplicável.",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "Configuração do AmneziaWG",
"mtprotoSecret": "Segredo MTProto",
"mtprotoSecretHint": "O segredo FakeTLS do cliente. Gere novamente para trocá-lo.",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "Оставьте пустым для автоназначения; разделяйте записи запятыми",
"amneziaWgForwardedPorts": "Проброс портов",
"amneziaWgForwardedPortsHint": "Порты/диапазоны, DNAT'ящиеся на этого клиента, например 80, 443, 8000-8100. Оставьте пустым, если не нужно.",
"tunnelKeepAlive": "Keepalive (секунды)",
"tunnelKeepAliveHint": "Как часто клиент шлёт keepalive-пакет. Обычное значение 25: оно держит NAT-маппинг открытым и возвращает простаивающий пир сам после любого разрыва, включая рестарт панели. 0 отключает — тогда молчащий клиент остаётся отключённым до первого своего пакета.",
"amneziaWgConfig": "Конфиг AmneziaWG",
"mtprotoSecret": "Секрет MTProto",
"mtprotoSecretHint": "Секрет FakeTLS клиента. Перегенерируйте, чтобы сменить.",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "Otomatik atama için boş bırakın; girişleri virgülle ayırın",
"amneziaWgForwardedPorts": "Yönlendirilen Portlar",
"amneziaWgForwardedPortsHint": "Bu istemciye DNAT ile yönlendirilen port/aralıklar, örn. 80, 443, 8000-8100. Yoksa boş bırakın.",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "AmneziaWG Yapılandırması",
"mtprotoSecret": "MTProto sırrı",
"mtprotoSecretHint": "İstemcinin FakeTLS sırrı. Değiştirmek için yeniden oluşturun.",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "Залиште порожнім для автопризначення; розділяйте записи комами",
"amneziaWgForwardedPorts": "Перенаправлені порти",
"amneziaWgForwardedPortsHint": "Порти/діапазони, що перенаправляються (DNAT) на цього клієнта, напр. 80, 443, 8000-8100. Залиште порожнім, якщо не потрібно.",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "Конфігурація AmneziaWG",
"mtprotoSecret": "Секрет MTProto",
"mtprotoSecretHint": "Секрет FakeTLS клієнта. Згенеруйте заново, щоб змінити.",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "Để trống để tự động gán; phân tách các mục bằng dấu phẩy",
"amneziaWgForwardedPorts": "Cổng chuyển tiếp",
"amneziaWgForwardedPortsHint": "Cổng/dải cổng được chuyển tiếp (DNAT) đến client này, vd. 80, 443, 8000-8100. Để trống nếu không cần.",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "Cấu hình AmneziaWG",
"mtprotoSecret": "Secret MTProto",
"mtprotoSecretHint": "Secret FakeTLS của client. Tạo lại để thay đổi.",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "留空则自动分配;多个条目用逗号分隔",
"amneziaWgForwardedPorts": "转发端口",
"amneziaWgForwardedPortsHint": "转发到此客户端的端口/范围,例如 80, 443, 8000-8100。留空则不转发。",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "AmneziaWG 配置",
"mtprotoSecret": "MTProto 密钥",
"mtprotoSecretHint": "该客户端的 FakeTLS 密钥。重新生成即可更换。",
+2
View File
@@ -879,6 +879,8 @@
"amneziaWgAllowedIPsHint": "留空則自動分配;多個條目用逗號分隔",
"amneziaWgForwardedPorts": "轉發連接埠",
"amneziaWgForwardedPortsHint": "轉發到此客戶端的連接埠/範圍,例如 80, 443, 8000-8100。留空則不轉發。",
"tunnelKeepAlive": "Keepalive (seconds)",
"tunnelKeepAliveHint": "How often the client sends a keepalive packet. 25 is the usual value: it holds the NAT mapping open and brings an idle peer back on its own after any drop, including a panel restart. 0 disables it — an idle client then stays disconnected until it sends traffic.",
"amneziaWgConfig": "AmneziaWG 設定",
"mtprotoSecret": "MTProto 金鑰",
"mtprotoSecretHint": "該用戶端的 FakeTLS 金鑰。重新產生即可更換。",