diff --git a/internal/database/model/model.go b/internal/database/model/model.go index 13b112216..ebc39449b 100644 --- a/internal/database/model/model.go +++ b/internal/database/model/model.go @@ -599,11 +599,16 @@ func StripVlessInboundEncryption(settings string) (string, bool) { if settings == "" { return settings, false } - var parsed map[string]any - if err := json.Unmarshal([]byte(settings), &parsed); err != nil { + // Looking for the key at the top level first skips the client list instead of decoding it. + var top map[string]json.RawMessage + if err := json.Unmarshal([]byte(settings), &top); err != nil { return settings, false } - if _, has := parsed["encryption"]; !has { + if _, has := top["encryption"]; !has { + return settings, false + } + var parsed map[string]any + if err := json.Unmarshal([]byte(settings), &parsed); err != nil { return settings, false } delete(parsed, "encryption") diff --git a/internal/database/model/model_test.go b/internal/database/model/model_test.go index 614775a5a..8175729c8 100644 --- a/internal/database/model/model_test.go +++ b/internal/database/model/model_test.go @@ -294,3 +294,40 @@ func TestNormalizeClientHostRuleIds(t *testing.T) { }) } } + +// The panel keeps encryption beside decryption only to build share links; the +// core's inbound takes decryption alone, and settings without the key pass as stored. +func TestGenXrayInboundConfigDropsVlessEncryption(t *testing.T) { + tests := []struct { + name, settings, want string + }{ + { + name: "encryption set", + settings: `{"encryption":"none","decryption":"none","clients":[{"id":"u","email":"a@x"}]}`, + want: "{\n \"clients\": [\n {\n \"email\": \"a@x\",\n \"id\": \"u\"\n }\n ],\n \"decryption\": \"none\"\n}", + }, + { + name: "encryption null", + settings: `{"encryption":null,"clients":[]}`, + want: "{\n \"clients\": []\n}", + }, + { + name: "no encryption", + settings: `{"decryption":"none", "clients":[]}`, + want: `{"decryption":"none", "clients":[]}`, + }, + { + name: "not an object", + settings: `{"encryption":`, + want: `{"encryption":`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + in := Inbound{Protocol: VLESS, Port: 443, Settings: tt.settings} + if got := string(in.GenXrayInboundConfig().Settings); got != tt.want { + t.Fatalf("core settings = %s\nwant %s", got, tt.want) + } + }) + } +} diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 69c9323fd..3646889e0 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -558,14 +558,7 @@ func clientWithInboundFlow(c model.Client, ib *model.Inbound) model.Client { } func shadowsocksMethodFromSettings(settings string) string { - if settings == "" { - return "" - } - var m map[string]any - if err := json.Unmarshal([]byte(settings), &m); err != nil { - return "" - } - method, _ := m["method"].(string) + method, _ := settingsField(settings, "method").(string) return method } @@ -635,13 +628,14 @@ func normalizeShadowsocksClientKeys(settings string) (string, bool) { if shadowsocksKeyBytes(method) == 0 { return settings, false } - var m map[string]any - if err := json.Unmarshal([]byte(settings), &m); err != nil { - return settings, false - } - clients, ok := m["clients"].([]any) - if !ok { - return settings, false + return rewriteSettingsClients(settings, func(clients []any) bool { + return regenerateMismatchedShadowsocksKeys(method, clients) + }) +} + +func regenerateMismatchedShadowsocksKeys(method string, clients []any) bool { + if shadowsocksKeyBytes(method) == 0 { + return false } changed := false for i := range clients { @@ -653,18 +647,9 @@ func normalizeShadowsocksClientKeys(settings string) (string, bool) { continue } c["password"] = randomShadowsocksClientKey(method) - clients[i] = c changed = true } - if !changed { - return settings, false - } - m["clients"] = clients - bs, err := json.MarshalIndent(m, "", " ") - if err != nil { - return settings, false - } - return string(bs), true + return changed } func applyShadowsocksClientMethod(clients []any, settings map[string]any) { diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 2faf2144b..d871cb49e 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -1991,26 +1991,16 @@ func (s *InboundService) SetInboundEnable(id int, enable bool) (bool, error) { return needRestart, nil } -func (s *InboundService) validateUpdatedInboundClients(inbound, existing *model.Inbound) error { - clients, err := s.GetClients(inbound) - if err != nil { - return err - } +// existing holds the stored clients, or none across a protocol switch. +func validateUpdatedInboundClients(protocol model.Protocol, clients, existing []model.Client) error { if err := validateClientsRenewal(clients); err != nil { return err } - var existingClients []model.Client - if inbound.Protocol == existing.Protocol { - existingClients, err = s.GetClients(existing) - if err != nil { - return err - } - } - if err := validateClientsKeepAliveAgainstExisting(inbound.Protocol, clients, existingClients); err != nil { + if err := validateClientsKeepAliveAgainstExisting(protocol, clients, existing); err != nil { return err } for _, client := range clients { - switch inbound.Protocol { + switch protocol { case model.Hysteria: if client.Auth == "" { return common.NewError("empty client ID") @@ -2035,7 +2025,7 @@ func (s *InboundService) validateUpdatedInboundClients(inbound, existing *model. } } } - return validateTuicClientEmails(inbound.Protocol, clients) + return validateTuicClientEmails(protocol, clients) } func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, bool, error) { @@ -2141,14 +2131,37 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, } running := *stored oldInbound = stored + storedFields, storedOK := settingsObject(stored.Settings) + fields, fieldsOK := settingsObject(inbound.Settings) + // encoded: inbound.Settings is fields' own encoding, so the steps below + // re-encode only what they change. + encoded := false // The form posts back the clients and enable it loaded; both have their // own endpoints, so only a master's push may change them here. if !s.FromNodeSync { - inbound.Settings = keepStoredClients(inbound.Settings, stored.Settings) + if storedOK && fieldsOK && fields != nil && keepStoredClients(fields, storedFields) { + kept, err := encodeSettings(fields) + if err != nil { + return err + } + inbound.Settings, encoded = kept, true + } inbound.Enable = stored.Enable } + newClients, err := ParseInboundSettingsClients(inbound.Settings) + if err != nil { + return err + } + storedClients, err := ParseInboundSettingsClients(stored.Settings) + if err != nil { + return err + } // On the clients actually saved: a protocol switch keeps the stored ones. - if err := s.validateUpdatedInboundClients(inbound, stored); err != nil { + var sameProtocolClients []model.Client + if inbound.Protocol == stored.Protocol { + sameProtocolClients = storedClients + } + if err := validateUpdatedInboundClients(inbound.Protocol, newClients, sameProtocolClients); err != nil { return err } if err := validateVlessManagedFallbacks(tx, inbound); err != nil { @@ -2161,91 +2174,44 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, if conflict != nil { return common.NewError(conflict.String()) } - if err := s.updateClientTraffics(tx, oldInbound, inbound); err != nil { + if err := s.updateClientTraffics(tx, inbound.Id, storedClients, newClients); err != nil { return err } if err := database.SyncHostsFromExternalProxy(tx, inbound.Id, running.StreamSettings, inbound.StreamSettings); err != nil { return err } - // Ensure created_at and updated_at exist in inbound.Settings clients - { - var oldSettings map[string]any - _ = json.Unmarshal([]byte(oldInbound.Settings), &oldSettings) - emailToCreated := map[string]int64{} - emailToUpdated := map[string]int64{} - if oldSettings != nil { - if oc, ok := oldSettings["clients"].([]any); ok { - for _, it := range oc { - if m, ok2 := it.(map[string]any); ok2 { - if email, ok3 := m["email"].(string); ok3 { - switch v := m["created_at"].(type) { - case float64: - emailToCreated[email] = int64(v) - case int64: - emailToCreated[email] = v - } - switch v := m["updated_at"].(type) { - case float64: - emailToUpdated[email] = int64(v) - case int64: - emailToUpdated[email] = v - } - } - } - } - } - } - var newSettings map[string]any - if err2 := json.Unmarshal([]byte(inbound.Settings), &newSettings); err2 == nil && newSettings != nil { - now := time.Now().Unix() * 1000 - if nSlice, ok := newSettings["clients"].([]any); ok { - for i := range nSlice { - if m, ok2 := nSlice[i].(map[string]any); ok2 { - email, _ := m["email"].(string) - if _, ok3 := m["created_at"]; !ok3 { - if v, ok4 := emailToCreated[email]; ok4 && v > 0 { - m["created_at"] = v - } else { - m["created_at"] = now - } - } - // Preserve client's updated_at if present; do not bump on parent inbound update - if _, hasUpdated := m["updated_at"]; !hasUpdated { - if v, ok4 := emailToUpdated[email]; ok4 && v > 0 { - m["updated_at"] = v - } - } - nSlice[i] = m - } - } - newSettings["clients"] = nSlice - if bs, err3 := json.MarshalIndent(newSettings, "", " "); err3 == nil { - inbound.Settings = string(bs) - } - } - } - } + if clients, ok := fields["clients"].([]any); ok { + // After a form save both lists are the same objects: nothing may read + // storedFields once the steps below start writing. + storedList, _ := storedFields["clients"].([]any) + changed := stampClientTimestamps(clients, storedList, time.Now().Unix()*1000) - // A Shadowsocks-2022 method change resizes the key, but existing client PSKs - // keep their old length and would be rejected by xray. Regenerate mismatched - // client keys so the inbound stays connectable. - if normalized, changed := normalizeShadowsocksClientKeys(inbound.Settings); changed { - inbound.Settings = normalized - logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)") - } - - // Re-gate Vision flow now that the new stream/encryption is known: if this - // VLESS inbound just became flow-eligible (e.g. vlessenc was enabled on an - // XHTTP inbound), restore Vision for clients whose intended flow is Vision - // but was stripped while the inbound was ineligible. - if !inbound.DisableFlow { - if restored, changed := s.restoreVisionFlowForEligibleInbound(tx, inbound.Settings, inbound.StreamSettings, inbound.Protocol); changed { - inbound.Settings = restored + // A Shadowsocks-2022 method change resizes the key, but existing client PSKs + // keep their old length and would be rejected by xray. + method, _ := fields["method"].(string) + if regenerateMismatchedShadowsocksKeys(method, clients) { + changed = true + logger.Warning("Shadowsocks inbound", inbound.Id, "method change resized keys; regenerated mismatched client PSK(s)") } - } else { - if stripped, changed := stripClientFlows(inbound.Settings); changed { - inbound.Settings = stripped + + // Re-gate Vision now that the new stream/encryption is known. inbound.Settings + // still names the saved top-level keys: the steps above edit clients only. + if !inbound.DisableFlow { + if inboundCanEnableTlsFlow(string(inbound.Protocol), inbound.StreamSettings, inbound.Settings) && s.restoreVisionFlow(tx, clients) { + changed = true + } + } else if clearClientFlows(clients) { + changed = true + } + + if changed || !encoded { + if inbound.Settings, err = encodeSettings(fields); err != nil { + return err + } + if newClients, err = ParseInboundSettingsClients(inbound.Settings); err != nil { + return err + } } } @@ -2381,10 +2347,6 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, needRestart = true } } - newClients, gcErr := s.GetClients(oldInbound) - if gcErr != nil { - return gcErr - } if err := s.clientService.SyncInbound(tx, oldInbound.Id, newClients); err != nil { return err } @@ -2479,11 +2441,6 @@ func (s *InboundService) buildInboundForNodePush(tx *gorm.DB, inbound *model.Inb if err := validateVlessManagedFallbacks(tx, &built); err != nil { return nil, err } - settings := map[string]any{} - if err := json.Unmarshal([]byte(built.Settings), &settings); err != nil { - return nil, err - } - if !inboundCanHostFallbacks(&built) { return &built, nil } @@ -2494,6 +2451,10 @@ func (s *InboundService) buildInboundForNodePush(tx *gorm.DB, inbound *model.Inb if len(fallbacks) == 0 { return &built, nil } + settings := map[string]any{} + if err := json.Unmarshal([]byte(built.Settings), &settings); err != nil { + return nil, err + } generic := make([]any, 0, len(fallbacks)) for _, f := range fallbacks { generic = append(generic, f) @@ -2583,8 +2544,13 @@ func (s *InboundService) stripDisabledClients(tx *gorm.DB, inbound *model.Inboun finalClients = append(finalClients, c) } settings["clients"] = finalClients - if inbound.Protocol == model.Shadowsocks { + switch inbound.Protocol { + case model.Shadowsocks: xray.LockShadowsocks2022(settings) + case model.VLESS: + // The core config never carries it. Dropped while decoded, the config + // generator need not decode and re-encode every client to drop it itself. + delete(settings, "encryption") } modifiedSettings, err := json.MarshalIndent(settings, "", " ") @@ -2601,16 +2567,7 @@ func (s *InboundService) stripDisabledClients(tx *gorm.DB, inbound *model.Inboun // emails. Uses sets for O(N) lookup — the previous nested-loop implementation // was O(N²) and degraded into multi-second pauses on inbounds with thousands // of clients (toggling, saving, or deleting any such inbound felt frozen). -func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inbound, newInbound *model.Inbound) error { - oldClients, err := s.GetClients(oldInbound) - if err != nil { - return err - } - newClients, err := s.GetClients(newInbound) - if err != nil { - return err - } - +func (s *InboundService) updateClientTraffics(tx *gorm.DB, inboundId int, oldClients, newClients []model.Client) error { // Email is the unique key for ClientTraffic rows. Clients without an // email have no stats row to sync — skip them on both sides instead of // risking a unique-constraint hit or accidental delete of an unrelated row. @@ -2639,7 +2596,7 @@ func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inb if _, kept := newEmails[email]; kept { continue } - stillUsed, err := s.emailUsedByOtherInbounds(tx, email, oldInbound.Id) + stillUsed, err := s.emailUsedByOtherInbounds(tx, email, inboundId) if err != nil { return err } @@ -2667,7 +2624,7 @@ func (s *InboundService) updateClientTraffics(tx *gorm.DB, oldInbound *model.Inb keptClients[email] = &newClients[i] continue } - if err := s.AddClientStat(tx, oldInbound.Id, &newClients[i]); err != nil { + if err := s.AddClientStat(tx, inboundId, &newClients[i]); err != nil { return err } } diff --git a/internal/web/service/inbound_flow_restore.go b/internal/web/service/inbound_flow_restore.go index bf96561c1..c4a801ab6 100644 --- a/internal/web/service/inbound_flow_restore.go +++ b/internal/web/service/inbound_flow_restore.go @@ -1,8 +1,6 @@ package service import ( - "encoding/json" - "github.com/mhsanaei/3x-ui/v3/internal/database/model" "gorm.io/gorm" @@ -33,14 +31,12 @@ func (s *InboundService) restoreVisionFlowForEligibleInbound(tx *gorm.DB, settin if !inboundCanEnableTlsFlow(string(protocol), streamSettings, settings) { return settings, false } - var parsed map[string]any - if err := json.Unmarshal([]byte(settings), &parsed); err != nil { - return settings, false - } - clients, ok := parsed["clients"].([]any) - if !ok || len(clients) == 0 { - return settings, false - } + return rewriteSettingsClients(settings, func(clients []any) bool { + return s.restoreVisionFlow(tx, clients) + }) +} + +func (s *InboundService) restoreVisionFlow(tx *gorm.DB, clients []any) bool { // Collect empty-flow clients, then resolve their intended flow in one query. emails := make([]string, 0, len(clients)) for i := range clients { @@ -56,11 +52,11 @@ func (s *InboundService) restoreVisionFlowForEligibleInbound(tx *gorm.DB, settin } } if len(emails) == 0 { - return settings, false + return false } intended, err := s.clientService.EffectiveFlowsByEmails(tx, emails) if err != nil { - return settings, false + return false } changed := false for i := range clients { @@ -76,28 +72,16 @@ func (s *InboundService) restoreVisionFlowForEligibleInbound(tx *gorm.DB, settin continue } cm["flow"] = visionFlow - clients[i] = cm changed = true } - if !changed { - return settings, false - } - out, err := json.MarshalIndent(parsed, "", " ") - if err != nil { - return settings, false - } - return string(out), true + return changed } func stripClientFlows(settings string) (string, bool) { - var parsed map[string]any - if err := json.Unmarshal([]byte(settings), &parsed); err != nil { - return settings, false - } - clients, ok := parsed["clients"].([]any) - if !ok || len(clients) == 0 { - return settings, false - } + return rewriteSettingsClients(settings, clearClientFlows) +} + +func clearClientFlows(clients []any) bool { changed := false for i := range clients { cm, ok := clients[i].(map[string]any) @@ -106,16 +90,8 @@ func stripClientFlows(settings string) (string, bool) { } if flow, _ := cm["flow"].(string); flow != "" { cm["flow"] = "" - clients[i] = cm changed = true } } - if !changed { - return settings, false - } - out, err := json.MarshalIndent(parsed, "", " ") - if err != nil { - return settings, false - } - return string(out), true + return changed } diff --git a/internal/web/service/inbound_settings_clients.go b/internal/web/service/inbound_settings_clients.go index 7522e3cb4..0f5390f26 100644 --- a/internal/web/service/inbound_settings_clients.go +++ b/internal/web/service/inbound_settings_clients.go @@ -32,6 +32,51 @@ func ParseInboundSettingsClients(settings string) ([]model.Client, error) { return clients, nil } +// settingsField reads one top-level settings key. The client list beside it is skipped +// rather than decoded, so reading a cipher or a network costs no per-client allocation. +func settingsField(settings, key string) any { + var top map[string]json.RawMessage + if json.Unmarshal([]byte(settings), &top) != nil { + return nil + } + var value any + _ = json.Unmarshal(top[key], &value) + return value +} + +// settingsObject decodes a settings blob; ok is false when it is not valid JSON +// for an object, and a JSON null decodes to a nil map. +func settingsObject(settings string) (map[string]any, bool) { + var fields map[string]any + if json.Unmarshal([]byte(settings), &fields) != nil { + return nil, false + } + return fields, true +} + +func encodeSettings(fields map[string]any) (string, error) { + out, err := json.MarshalIndent(fields, "", " ") + return string(out), err +} + +// rewriteSettingsClients runs edit over the decoded client objects and re-encodes the +// settings only when edit reports a change. +func rewriteSettingsClients(settings string, edit func(clients []any) bool) (string, bool) { + var parsed map[string]any + if err := json.Unmarshal([]byte(settings), &parsed); err != nil { + return settings, false + } + clients, ok := parsed["clients"].([]any) + if !ok || !edit(clients) { + return settings, false + } + out, err := json.MarshalIndent(parsed, "", " ") + if err != nil { + return settings, false + } + return string(out), true +} + // settingsEntriesToClients decodes the wire entries a caller has already // stamped, so a delta carries the persisted created_at / updated_at / subId // rather than the pre-stamp values the request was parsed into. diff --git a/internal/web/service/inbound_settings_commit.go b/internal/web/service/inbound_settings_commit.go index 98d4bb64a..34e77041e 100644 --- a/internal/web/service/inbound_settings_commit.go +++ b/internal/web/service/inbound_settings_commit.go @@ -143,24 +143,61 @@ func mergeClientLists(base, ours, current []any) []any { // keepStoredClients puts the stored client list back into an inbound save's // payload: clients change through the client endpoints, never this form. -func keepStoredClients(payload, stored string) string { - var payloadM, storedM map[string]any - // A JSON null decodes into a nil map without an error; client validation refuses it next. - if json.Unmarshal([]byte(payload), &payloadM) != nil || json.Unmarshal([]byte(stored), &storedM) != nil || payloadM == nil { - return payload - } - storedClients, has := storedM["clients"] - if reflect.DeepEqual(payloadM["clients"], storedClients) { - return payload +func keepStoredClients(payload, stored map[string]any) bool { + storedClients, has := stored["clients"] + if reflect.DeepEqual(payload["clients"], storedClients) { + return false } if has { - payloadM["clients"] = storedClients + payload["clients"] = storedClients } else { - delete(payloadM, "clients") + delete(payload, "clients") } - b, err := json.MarshalIndent(payloadM, "", " ") - if err != nil { - return payload - } - return string(b) + return true +} + +// stampClientTimestamps fills a missing created_at / updated_at from the stored entry of +// the same email, or created_at with now: an inbound save never bumps a client's stamps. +func stampClientTimestamps(clients, stored []any, now int64) bool { + storedCreated := make(map[string]int64, len(stored)) + storedUpdated := make(map[string]int64, len(stored)) + for _, entry := range stored { + m, ok := entry.(map[string]any) + if !ok { + continue + } + email, ok := m["email"].(string) + if !ok { + continue + } + if v, ok := m["created_at"].(float64); ok { + storedCreated[email] = int64(v) + } + if v, ok := m["updated_at"].(float64); ok { + storedUpdated[email] = int64(v) + } + } + changed := false + for _, entry := range clients { + m, ok := entry.(map[string]any) + if !ok { + continue + } + email, _ := m["email"].(string) + if _, has := m["created_at"]; !has { + if v := storedCreated[email]; v > 0 { + m["created_at"] = v + } else { + m["created_at"] = now + } + changed = true + } + if _, has := m["updated_at"]; !has { + if v := storedUpdated[email]; v > 0 { + m["updated_at"] = v + changed = true + } + } + } + return changed } diff --git a/internal/web/service/inbound_update_client_steps_test.go b/internal/web/service/inbound_update_client_steps_test.go new file mode 100644 index 000000000..d41166ff7 --- /dev/null +++ b/internal/web/service/inbound_update_client_steps_test.go @@ -0,0 +1,135 @@ +package service + +import ( + "encoding/base64" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +// A master's push carries clients without stamps: the node keeps the ones it +// stored and dates a new client once, the same in settings and in its record. +func TestInboundUpdateFromMasterStampsClientTimestamps(t *testing.T) { + setupBulkDB(t) + const storedCreated, storedUpdated = int64(1700000000000), int64(1700000500000) + known := model.Client{Email: "known@stamp", ID: "aaaaaaaa-0000-0000-0000-000000000301", Enable: true} + added := model.Client{Email: "added@stamp", ID: "aaaaaaaa-0000-0000-0000-000000000302", Enable: true} + stored := known + stored.CreatedAt, stored.UpdatedAt = storedCreated, storedUpdated + ib := mkInbound(t, 23301, model.VLESS, clientsSettings(t, []model.Client{stored})) + + push := *ib + push.Settings = clientsSettings(t, []model.Client{known, added}) + before := time.Now().Unix() * 1000 + if _, _, err := (&InboundService{FromNodeSync: true}).UpdateInbound(&push); err != nil { + t.Fatalf("UpdateInbound: %v", err) + } + + if got, _ := settingsClient(t, ib.Id, known.Email); got.CreatedAt != storedCreated || got.UpdatedAt != storedUpdated { + t.Fatalf("known client stamps = %d/%d, want the stored %d/%d", got.CreatedAt, got.UpdatedAt, storedCreated, storedUpdated) + } + got, _ := settingsClient(t, ib.Id, added.Email) + if got.CreatedAt < before { + t.Fatalf("new client created_at = %d, want the save's time (>= %d)", got.CreatedAt, before) + } + if got.UpdatedAt != 0 { + t.Fatalf("new client updated_at = %d, want none: an inbound save is not a client edit", got.UpdatedAt) + } + if rec := lookupClientRecord(t, added.Email); rec.CreatedAt != got.CreatedAt { + t.Fatalf("new client record created at %d, its settings entry at %d", rec.CreatedAt, got.CreatedAt) + } +} + +// The form posts no clients, so the stored list is the one saved; an entry that +// predates the stamps still gets its date. +func TestInboundFormSaveDatesAClientStoredWithoutCreatedAt(t *testing.T) { + setupBulkDB(t) + ib := mkInbound(t, 23302, model.VLESS, clientsSettings(t, []model.Client{ + {Email: "legacy@stamp", ID: "aaaaaaaa-0000-0000-0000-000000000303", Enable: true}, + })) + + form := *ib + form.Settings = `{"decryption":"none"}` + form.Remark = "edited" + before := time.Now().Unix() * 1000 + if _, _, err := (&InboundService{}).UpdateInbound(&form); err != nil { + t.Fatalf("UpdateInbound: %v", err) + } + + got, ok := settingsClient(t, ib.Id, "legacy@stamp") + if !ok { + t.Fatal("the stored client was dropped by a form save that posted none") + } + if got.CreatedAt < before { + t.Fatalf("created_at = %d, want the save's time (>= %d)", got.CreatedAt, before) + } +} + +// Switching between SS-2022 ciphers of different key sizes leaves every stored +// client key the wrong length, and xray-core then rejects those users. +func TestInboundFormSaveRegeneratesKeysAfterAShadowsocksMethodResize(t *testing.T) { + setupBulkDB(t) + key16 := base64.StdEncoding.EncodeToString([]byte("0123456789abcdef")) + key32 := base64.StdEncoding.EncodeToString([]byte("0123456789abcdef0123456789abcdef")) + ib := mkInbound(t, 23303, model.Shadowsocks, + `{"method":"2022-blake3-aes-256-gcm","password":"`+key32+`","network":"tcp","clients":[{"email":"psk@ss","password":"`+key32+`","enable":true}]}`) + if err := (&ClientService{}).SyncInbound(nil, ib.Id, []model.Client{{Email: "psk@ss", Password: key32, Enable: true}}); err != nil { + t.Fatalf("seed client record: %v", err) + } + + form := *ib + form.Settings = `{"method":"2022-blake3-aes-128-gcm","password":"` + key16 + `","network":"tcp"}` + if _, _, err := (&InboundService{}).UpdateInbound(&form); err != nil { + t.Fatalf("UpdateInbound: %v", err) + } + + got, _ := settingsClient(t, ib.Id, "psk@ss") + if decoded, err := base64.StdEncoding.DecodeString(got.Password); err != nil || len(decoded) != 16 { + t.Fatalf("client key after the switch to aes-128 = %q, want a 16-byte key (decode err %v)", got.Password, err) + } + if rec := lookupClientRecord(t, "psk@ss"); rec.Password != got.Password { + t.Fatalf("client record still holds key %q, settings hold %q", rec.Password, got.Password) + } +} + +// Vision is stripped from a client while its XHTTP inbound has no vlessenc; the +// save that sets the encryption is the one that has to put it back. +func TestInboundFormSaveRestoresVisionOnceEncryptionIsSet(t *testing.T) { + db := initFlowTestDB(t) + ibSvc := &InboundService{} + const client = `"id":"ce8d33df-3a64-4f10-8f9b-91c3a8e0d101","email":"vision@x","subId":"s1","enable":true` + + sibling := &model.Inbound{ + Tag: "sib", Enable: true, Port: 52201, Protocol: model.VLESS, + StreamSettings: `{"network":"tcp","security":"reality"}`, + Settings: `{"clients":[{` + client + `,"flow":"` + visionFlow + `"}]}`, + } + target := &model.Inbound{ + Tag: "tgt", Enable: true, Port: 52202, Protocol: model.VLESS, + StreamSettings: `{"network":"xhttp","security":"reality"}`, + Settings: `{"clients":[{` + client + `,"flow":""}]}`, + } + for _, ib := range []*model.Inbound{sibling, target} { + if err := db.Create(ib).Error; err != nil { + t.Fatalf("create %s: %v", ib.Tag, err) + } + clients, err := ibSvc.GetClients(ib) + if err != nil { + t.Fatalf("GetClients %s: %v", ib.Tag, err) + } + if err := (&ClientService{}).SyncInbound(nil, ib.Id, clients); err != nil { + t.Fatalf("sync %s: %v", ib.Tag, err) + } + } + + form := *target + form.Settings = `{"decryption":"mlkem768x25519plus.native.0rtt.KEY","encryption":"mlkem768x25519plus.native.0rtt.KEY"}` + if _, _, err := ibSvc.UpdateInbound(&form); err != nil { + t.Fatalf("UpdateInbound: %v", err) + } + + if got, _ := settingsClient(t, target.Id, "vision@x"); got.Flow != visionFlow { + t.Fatalf("flow after encryption was set = %q, want %q", got.Flow, visionFlow) + } +} diff --git a/internal/web/service/port_conflict.go b/internal/web/service/port_conflict.go index 59a1eb635..91d7477b8 100644 --- a/internal/web/service/port_conflict.go +++ b/internal/web/service/port_conflict.go @@ -59,34 +59,29 @@ func inboundTransports(protocol model.Protocol, streamSettings, settings string) // a few protocols carry their L4 choice in settings instead of (or in // addition to) streamSettings: SS / Tunnel via a CSV field that wins // outright, Mixed via an additive udp boolean. - if settings != "" { - var st map[string]any - if json.Unmarshal([]byte(settings), &st) == nil { - switch protocol { - case model.Shadowsocks, model.Tunnel: - key := "network" - if protocol == model.Tunnel { - key = "allowedNetwork" - } - if n, ok := st[key].(string); ok && n != "" { - bits = 0 - for part := range strings.SplitSeq(n, ",") { - switch strings.TrimSpace(part) { - case "tcp": - bits |= transportTCP - case "udp": - bits |= transportUDP - } - } - } - case model.Mixed: - // socks/http "mixed" inbound: settings.udp=true means it - // also relays udp on the same port (socks5 udp associate). - if udpOn, _ := st["udp"].(bool); udpOn { + switch protocol { + case model.Shadowsocks, model.Tunnel: + key := "network" + if protocol == model.Tunnel { + key = "allowedNetwork" + } + if n, ok := settingsField(settings, key).(string); ok && n != "" { + bits = 0 + for part := range strings.SplitSeq(n, ",") { + switch strings.TrimSpace(part) { + case "tcp": + bits |= transportTCP + case "udp": bits |= transportUDP } } } + case model.Mixed: + // socks/http "mixed" inbound: settings.udp=true means it + // also relays udp on the same port (socks5 udp associate). + if udpOn, _ := settingsField(settings, "udp").(bool); udpOn { + bits |= transportUDP + } } // safety net: never return zero, even if every parse failed. diff --git a/internal/web/service/tx_pool_starvation_test.go b/internal/web/service/tx_pool_starvation_test.go index e14455a6f..e4fa54af8 100644 --- a/internal/web/service/tx_pool_starvation_test.go +++ b/internal/web/service/tx_pool_starvation_test.go @@ -130,13 +130,11 @@ func TestUpdateClientTrafficsStaysOnOneConnection(t *testing.T) { if err := database.GetDB().Create(&xray.ClientTraffic{InboundId: oldIb.Id, Email: "gone@x", Enable: true}).Error; err != nil { t.Fatalf("seed traffic: %v", err) } - newIb := *oldIb - newIb.Settings = `{"clients": []}` capPoolAtOneConn(t) err := runWithoutSecondConn(t, "inbound edit dropping a client", func() error { return database.GetDB().Transaction(func(tx *gorm.DB) error { - return svc.updateClientTraffics(tx, oldIb, &newIb) + return svc.updateClientTraffics(tx, oldIb.Id, clients, nil) }) }) if err != nil {