Просмотр исходного кода

Security hardening: sessions, SSRF, CSP nonce, CSRF logout, trusted proxies (#4275)

* refactor(session): store user ID in session instead of full struct

Replaces storing the full User object in the session cookie with just
the user ID. GetLoginUser now re-fetches the user from the database on
every request so credential/permission changes take effect immediately
without requiring a re-login. Includes a backward-compatible migration
path for existing sessions that still carry the old struct payload.

* feat(auth): block panel with default admin/admin credentials and guide credential change

checkLogin middleware now detects default admin/admin credentials and
redirects every panel route to /panel/settings until they are changed.
The settings page auto-opens the Authentication tab, shows a
non-dismissible error banner, and lists 'Default credentials' first in
the security checklist. Login response includes mustChangeCredentials
so the login page can redirect directly. Logout is now POST-only.
Password must be at least 10 characters and cannot be admin/admin.

* feat(settings): redact secrets in AllSettingView and add TrustedProxyCIDRs

Introduces AllSettingView which strips tgBotToken, twoFactorToken,
ldapPassword, apiToken and warp/nord secrets before sending them to
the browser, replacing them with boolean hasFoo presence flags. A new
/panel/setting/secret endpoint allows updating individual secrets by
key. Secrets that arrive blank on a save are preserved from the DB
rather than overwritten. Adds TrustedProxyCIDRs as a configurable
setting (defaults to localhost CIDRs). URL fields are validated before
save.

* fix(security): SSRF prevention, trusted-proxy header gating, CSP nonce, HTTP timeouts

Adds SanitizeHTTPURL / SanitizePublicHTTPURL to reject private-range
and loopback targets before any outbound HTTP request (node probe,
xray download, outbound test, external traffic inform, tgbot API
server, panel updater). Forwarded headers (X-Real-IP, X-Forwarded-For,
X-Forwarded-Host) are now only trusted when the direct connection
arrives from a CIDR in TrustedProxyCIDRs. CSP policy is tightened with
a per-request nonce. HTTP server gains read/write/idle timeouts. Panel
updater downloads the script to a temp file instead of piping curl into
shell. Xray archive download adds a size cap and response-code check.
backuptotgbot is changed from GET to POST.

* feat(nodes): add allow-private-address toggle per node

Adds AllowPrivateAddress to the Node model (DB default false). When
enabled it bypasses the SSRF private-range check for that node's probe
URL, allowing nodes hosted on RFC-1918 or loopback addresses (e.g.
a private VPN or LAN setup).

* chore: frontend UX improvements, CI pipeline, and dev tooling

- AppSidebar: logout via POST /logout instead of navigating to GET
- InboundList: persist filter state (search, protocol, node) to
  localStorage across page reloads; add protocol and node filter dropdowns
- IndexPage: add health status strip (Xray, CPU, Memory, Update) with
  quick-action buttons
- dependabot: weekly go mod and npm update schedule
- ci.yml: add GitHub Actions workflow for build and vet
- .nvmrc: pin Node 22 for local development
- frontend: bump package.json and package-lock.json
- SubPage, DnsPresetsModal, api-docs: minor fixes

* fix(ci): stub web/dist before go list to satisfy go:embed at compile time

* chore(ui): remove health-strip bar from dashboard top

* Revert "feat(auth): block panel with default admin/admin credentials and guide credential change"

This reverts commit 56ce6073ce09f08147f989858e0e88b3a4359546.

* fix(auth): make logout POST+CSRF and propagate session loss to other tabs

- Switch /logout from GET to POST with CSRFMiddleware so it matches the
  SPA's existing HttpUtil.post('/logout') call (previously 404'd silently)
  and blocks GET-based logout via image tags or link prefetchers. Handler
  now returns JSON; the SPA already navigates client-side.
- Return 401 (instead of 404) from /panel/api/* when the caller is a
  browser XHR (X-Requested-With: XMLHttpRequest) so the axios interceptor
  redirects to the login page on logout-in-another-tab, cookie expiry,
  and server restart. Anonymous callers still get 404 to keep endpoints
  hidden from casual scanners.
- One-shot the 401 redirect in axios-init.js and hang the rejected
  promise so queued polls don't stack reloads or surface error toasts
  while the browser is navigating away.
- Add the CSP nonce to the runtime-injected <script> in dist.go so the
  panel loads under the existing script-src 'nonce-...' policy.
- Update api-docs endpoints.js: GET /logout doc entry was missing.

* fix(settings): POST /logout after credential change

* fix(auth): invalidate other sessions when credentials change

When the admin changes username/password from one machine, sessions
on every other machine kept working until they manually logged out
because session storage is a signed client-side cookie — there is
no server-side session list to revoke.

Add a per-user LoginEpoch counter stamped into the session at login
and re-verified on every authenticated request. UpdateUser and
UpdateFirstUser bump the epoch (UpdateUser via gorm.Expr so a single
update statement is atomic), so any cookie issued before the change
no longer matches the user's current epoch and GetLoginUser returns
nil — the SPA's 401 interceptor then redirects to the login page.

Backward compatible: the column defaults to 0 and missing cookie
values are treated as 0, so sessions issued before this change
remain valid until the first credential update.

---------

Co-authored-by: Sanaei <[email protected]>
Farhad H. P. Shirvan 1 день назад
Родитель
Сommit
428f1333ac
40 измененных файлов с 966 добавлено и 161 удалено
  1. 8 0
      .github/dependabot.yml
  2. 63 0
      .github/workflows/ci.yml
  3. 1 0
      .nvmrc
  4. 17 24
      database/model/model.go
  5. 4 0
      frontend/package-lock.json
  6. 4 0
      frontend/package.json
  7. 10 21
      frontend/src/api/axios-init.js
  8. 8 2
      frontend/src/components/AppSidebar.vue
  9. 8 1
      frontend/src/models/setting.js
  10. 5 4
      frontend/src/pages/api-docs/endpoints.js
  11. 68 7
      frontend/src/pages/inbounds/InboundList.vue
  12. 7 0
      frontend/src/pages/nodes/NodeFormModal.vue
  13. 13 1
      frontend/src/pages/settings/GeneralTab.vue
  14. 3 4
      frontend/src/pages/settings/SecurityTab.vue
  15. 5 2
      frontend/src/pages/settings/TelegramTab.vue
  16. 8 2
      frontend/src/pages/settings/TwoFactorModal.vue
  17. 0 1
      frontend/src/pages/sub/SubPage.vue
  18. 1 1
      frontend/src/pages/xray/DnsPresetsModal.vue
  19. 6 16
      web/controller/api.go
  20. 5 1
      web/controller/dist.go
  21. 11 9
      web/controller/inbound.go
  22. 3 8
      web/controller/index.go
  23. 55 9
      web/controller/util.go
  24. 34 0
      web/controller/util_test.go
  25. 5 0
      web/controller/xray_setting.go
  26. 35 7
      web/entity/entity.go
  27. 5 0
      web/job/xray_traffic_job.go
  28. 13 1
      web/middleware/security.go
  29. 9 8
      web/service/node.go
  30. 50 3
      web/service/panel.go
  31. 70 12
      web/service/server.go
  32. 94 1
      web/service/setting.go
  33. 92 0
      web/service/setting_security_test.go
  34. 4 7
      web/service/tgbot.go
  35. 82 0
      web/service/url_safety.go
  36. 6 1
      web/service/user.go
  37. 4 4
      web/service/xray_metrics.go
  38. 98 3
      web/session/session.go
  39. 47 0
      web/session/session_test.go
  40. 5 1
      web/web.go

+ 8 - 0
.github/dependabot.yml

@@ -9,3 +9,11 @@ updates:
     directory: "/" # Location of package manifests
     schedule:
       interval: "weekly"
+  - package-ecosystem: "gomod"
+    directory: "/"
+    schedule:
+      interval: "weekly"
+  - package-ecosystem: "npm"
+    directory: "/frontend"
+    schedule:
+      interval: "weekly"

+ 63 - 0
.github/workflows/ci.yml

@@ -0,0 +1,63 @@
+name: CI
+
+on:
+  pull_request:
+  push:
+    branches:
+      - main
+
+permissions:
+  contents: read
+
+jobs:
+  go-test:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v5
+      - uses: actions/setup-go@v6
+        with:
+          go-version-file: go.mod
+          cache: true
+      - name: Stub web/dist for go:embed
+        run: mkdir -p web/dist && touch web/dist/.gitkeep
+      - name: Test
+        run: |
+          go list ./... | grep -v '/frontend/node_modules/' > /tmp/go-packages.txt
+          go test $(cat /tmp/go-packages.txt)
+
+  govulncheck:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v5
+      - uses: actions/setup-go@v6
+        with:
+          go-version-file: go.mod
+          cache: true
+      - name: Stub web/dist for go:embed
+        run: mkdir -p web/dist && touch web/dist/.gitkeep
+      - name: Install govulncheck
+        run: go install golang.org/x/vuln/cmd/govulncheck@latest
+      - name: Run govulncheck
+        run: govulncheck ./...
+
+  frontend:
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v5
+      - uses: actions/setup-node@v5
+        with:
+          node-version-file: .nvmrc
+          cache: npm
+          cache-dependency-path: frontend/package-lock.json
+      - name: Install
+        run: npm ci
+        working-directory: frontend
+      - name: Lint
+        run: npm run lint
+        working-directory: frontend
+      - name: Build
+        run: npm run build
+        working-directory: frontend
+      - name: Audit
+        run: npm audit --audit-level=high
+        working-directory: frontend

+ 1 - 0
.nvmrc

@@ -0,0 +1 @@
+22

+ 17 - 24
database/model/model.go

@@ -21,12 +21,8 @@ const (
 	Shadowsocks Protocol = "shadowsocks"
 	Mixed       Protocol = "mixed"
 	WireGuard   Protocol = "wireguard"
-	// UI stores Hysteria v1 and v2 both as "hysteria" and uses
-	// settings.version to discriminate. Imports from outside the panel
-	// can carry the literal "hysteria2" string, so IsHysteria below
-	// accepts both.
-	Hysteria  Protocol = "hysteria"
-	Hysteria2 Protocol = "hysteria2"
+	Hysteria    Protocol = "hysteria"
+	Hysteria2   Protocol = "hysteria2"
 )
 
 // IsHysteria returns true for both "hysteria" and "hysteria2".
@@ -38,9 +34,10 @@ func IsHysteria(p Protocol) bool {
 
 // User represents a user account in the 3x-ui panel.
 type User struct {
-	Id       int    `json:"id" gorm:"primaryKey;autoIncrement"`
-	Username string `json:"username"`
-	Password string `json:"password"`
+	Id         int    `json:"id" gorm:"primaryKey;autoIncrement"`
+	Username   string `json:"username"`
+	Password   string `json:"password"`
+	LoginEpoch int64  `json:"-" gorm:"default:0"`
 }
 
 // Inbound represents an Xray inbound configuration with traffic statistics and settings.
@@ -66,12 +63,7 @@ type Inbound struct {
 	StreamSettings string   `json:"streamSettings" form:"streamSettings"`
 	Tag            string   `json:"tag" form:"tag" gorm:"unique"`
 	Sniffing       string   `json:"sniffing" form:"sniffing"`
-
-	// NodeID points at the remote panel (Node) where this inbound's xray
-	// actually runs. NULL means the inbound runs on the local xray (the
-	// pre-multi-node behaviour). Existing rows migrate to NULL with no
-	// backfill.
-	NodeID *int `json:"nodeId,omitempty" form:"nodeId" gorm:"index"`
+	NodeID         *int     `json:"nodeId,omitempty" form:"nodeId" gorm:"index"`
 }
 
 // OutboundTraffics tracks traffic statistics for Xray outbound connections.
@@ -128,15 +120,16 @@ type Setting struct {
 // endpoint over HTTP using the per-node ApiToken to populate the runtime
 // status fields below.
 type Node struct {
-	Id       int    `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
-	Name     string `json:"name" form:"name" gorm:"uniqueIndex"`
-	Remark   string `json:"remark" form:"remark"`
-	Scheme   string `json:"scheme" form:"scheme"`
-	Address  string `json:"address" form:"address"`
-	Port     int    `json:"port" form:"port"`
-	BasePath string `json:"basePath" form:"basePath"`
-	ApiToken string `json:"apiToken" form:"apiToken"`
-	Enable   bool   `json:"enable" form:"enable" gorm:"default:true"`
+	Id                  int    `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
+	Name                string `json:"name" form:"name" gorm:"uniqueIndex"`
+	Remark              string `json:"remark" form:"remark"`
+	Scheme              string `json:"scheme" form:"scheme"`
+	Address             string `json:"address" form:"address"`
+	Port                int    `json:"port" form:"port"`
+	BasePath            string `json:"basePath" form:"basePath"`
+	ApiToken            string `json:"apiToken" form:"apiToken"`
+	Enable              bool   `json:"enable" form:"enable" gorm:"default:true"`
+	AllowPrivateAddress bool   `json:"allowPrivateAddress" form:"allowPrivateAddress" gorm:"default:false"`
 
 	// Heartbeat-updated fields. UpdatedAt advances on every probe even when
 	// the row is otherwise unchanged so the UI's "last seen" tooltip is

+ 4 - 0
frontend/package-lock.json

@@ -7,6 +7,10 @@
     "": {
       "name": "3x-ui-frontend",
       "version": "0.0.2",
+      "engines": {
+        "node": ">=22.0.0",
+        "npm": ">=10.0.0"
+      },
       "dependencies": {
         "@ant-design/icons-vue": "^7.0.1",
         "ant-design-vue": "^4.2.6",

+ 4 - 0
frontend/package.json

@@ -4,6 +4,10 @@
   "version": "0.0.2",
   "type": "module",
   "description": "3x-ui panel frontend (Vue 3 + Ant Design Vue 4 + Vite 8).",
+  "engines": {
+    "node": ">=22.0.0",
+    "npm": ">=10.0.0"
+  },
   "scripts": {
     "dev": "vite",
     "build": "vite build",

+ 10 - 21
frontend/src/api/axios-init.js

@@ -2,24 +2,16 @@ import axios from 'axios';
 import qs from 'qs';
 
 const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);
-// Public CSRF endpoint — works pre-login (the panel-scoped
-// /panel/csrf-token sits behind checkLogin and would 401 a fresh
-// login page that hasn't authenticated yet).
 const CSRF_TOKEN_PATH = '/csrf-token';
 
-// Cached session CSRF token. The legacy panel injects it via a
-// <meta name="csrf-token"> tag rendered by Go; the new SPA pages
-// fetch it once from /panel/csrf-token instead. Module-level so
-// every axios POST sees the latest value.
 let csrfToken = null;
 let csrfFetchPromise = null;
+let sessionExpired = false;
 
 function readMetaToken() {
   return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || null;
 }
 
-// Fetch the token via a bare fetch() (not axios) so the call doesn't
-// recurse through this same interceptor.
 async function fetchCsrfToken() {
   try {
     const basePath = window.X_UI_BASE_PATH;
@@ -91,19 +83,16 @@ export function setupAxios() {
     async (error) => {
       const status = error.response?.status;
       if (status === 401) {
-        // 401 → session is gone. In production, the panel routes
-        // are gated by Go's checkLogin which redirects to base_path
-        // serving the login page; a reload is enough. In dev, Vite
-        // serves /index.html directly at "/", so a reload would put
-        // the user right back on the dashboard and the interceptor
-        // would loop. Navigate to the dev login entry instead.
-        if (import.meta.env.DEV) {
-          const basePath = window.X_UI_BASE_PATH || '/';
-          window.location.href = `${basePath}login.html`;
-        } else {
-          window.location.reload();
+        if (!sessionExpired) {
+          sessionExpired = true;
+          if (import.meta.env.DEV) {
+            const basePath = window.X_UI_BASE_PATH || '/';
+            window.location.href = `${basePath}login.html`;
+          } else {
+            window.location.reload();
+          }
         }
-        return Promise.reject(error);
+        return new Promise(() => { });
       }
       // 403 with a stale/missing CSRF token: drop the cache, re-fetch, retry once.
       const cfg = error.config;

+ 8 - 2
frontend/src/components/AppSidebar.vue

@@ -14,6 +14,7 @@ import {
 } from '@ant-design/icons-vue';
 
 import { theme, currentTheme, toggleTheme, toggleUltra, pauseAnimationsUntilLeave } from '@/composables/useTheme.js';
+import { HttpUtil } from '@/utils';
 
 const { t } = useI18n();
 
@@ -45,7 +46,7 @@ const tabs = computed(() => [
   { key: `${prefix}panel/settings`, icon: 'setting', title: t('menu.settings') },
   { key: `${prefix}panel/xray`, icon: 'tool', title: t('menu.xray') },
   { key: `${prefix}panel/api-docs`, icon: 'apidocs', title: t('menu.apiDocs') },
-  { key: `${prefix}logout`, icon: 'logout', title: t('logout') },
+  { key: 'logout', icon: 'logout', title: t('logout') },
 ]);
 
 const navTabs = computed(() => tabs.value.filter((tab) => tab.icon !== 'logout'));
@@ -55,7 +56,12 @@ const drawerOpen = ref(false);
 const collapsed = ref(JSON.parse(localStorage.getItem(SIDEBAR_COLLAPSED_KEY) || 'false'));
 const drawerWidth = 'min(82vw, 320px)';
 
-function openLink(key) {
+async function openLink(key) {
+  if (key === 'logout') {
+    await HttpUtil.post('/logout');
+    window.location.href = props.basePath || '/';
+    return;
+  }
   if (key.startsWith('http')) {
     window.open(key);
   } else {

+ 8 - 1
frontend/src/models/setting.js

@@ -15,6 +15,7 @@ export class AllSetting {
         this.webKeyFile = "";
         this.webBasePath = "/";
         this.sessionMaxAge = 360;
+        this.trustedProxyCIDRs = "127.0.0.1/32,::1/128";
         this.pageSize = 25;
         this.expireDiff = 0;
         this.trafficDiff = 0;
@@ -87,6 +88,12 @@ export class AllSetting {
         this.ldapDefaultTotalGB = 0;
         this.ldapDefaultExpiryDays = 0;
         this.ldapDefaultLimitIP = 0;
+        this.hasTgBotToken = false;
+        this.hasTwoFactorToken = false;
+        this.hasLdapPassword = false;
+        this.hasApiToken = false;
+        this.hasWarpSecret = false;
+        this.hasNordSecret = false;
 
         if (data == null) {
             return
@@ -97,4 +104,4 @@ export class AllSetting {
     equals(other) {
         return ObjectUtil.equals(this, other);
     }
-}
+}

+ 5 - 4
frontend/src/pages/api-docs/endpoints.js

@@ -46,9 +46,10 @@ export const sections = [
           '{\n  "success": false,\n  "msg": "Wrong username or password"\n}',
       },
       {
-        method: 'GET',
+        method: 'POST',
         path: '/logout',
-        summary: 'Clear the session cookie. Redirects back to the login page; not useful from non-browser clients.',
+        summary: 'Clear the session cookie. Requires the CSRF header for browser sessions.',
+        response: '{\n  "success": true\n}',
       },
       {
         method: 'GET',
@@ -70,7 +71,7 @@ export const sections = [
     id: 'inbounds',
     title: 'Inbounds API',
     description:
-      'Manage inbound configurations and their clients. All endpoints live under /panel/api/inbounds and require a logged-in session or Bearer token. Link-generating endpoints honour X-Forwarded-Host / X-Forwarded-Proto, so callers behind a reverse proxy get the correct external host in returned URLs.',
+      'Manage inbound configurations and their clients. All endpoints live under /panel/api/inbounds and require a logged-in session or Bearer token. Link-generating endpoints honour forwarded headers only when the request comes from a configured trusted proxy.',
     endpoints: [
       {
         method: 'GET',
@@ -627,7 +628,7 @@ export const sections = [
     description: 'Operations that interact with the configured Telegram bot.',
     endpoints: [
       {
-        method: 'GET',
+        method: 'POST',
         path: '/panel/api/backuptotgbot',
         summary: 'Send a fresh DB backup to every Telegram chat configured as an admin recipient. No body, no params.',
       },

+ 68 - 7
frontend/src/pages/inbounds/InboundList.vue

@@ -67,9 +67,29 @@ const emit = defineEmits([
 ]);
 
 // ============ Toolbar / search & filter =============================
-const enableFilter = ref(false);
-const searchKey = ref('');
-const filterBy = ref('');
+const FILTER_STATE_KEY = 'inboundsFilterState';
+const savedFilterState = (() => {
+  try {
+    return JSON.parse(localStorage.getItem(FILTER_STATE_KEY) || '{}');
+  } catch (_e) {
+    return {};
+  }
+})();
+const enableFilter = ref(!!savedFilterState.enableFilter);
+const searchKey = ref(savedFilterState.searchKey || '');
+const filterBy = ref(savedFilterState.filterBy || '');
+const protocolFilter = ref(savedFilterState.protocolFilter || '');
+const nodeFilter = ref(savedFilterState.nodeFilter || '');
+
+watch([enableFilter, searchKey, filterBy, protocolFilter, nodeFilter], () => {
+  localStorage.setItem(FILTER_STATE_KEY, JSON.stringify({
+    enableFilter: enableFilter.value,
+    searchKey: searchKey.value,
+    filterBy: filterBy.value,
+    protocolFilter: protocolFilter.value,
+    nodeFilter: nodeFilter.value,
+  }));
+});
 
 // Toggle the filter mode — flip cleans the other input.
 function onToggleFilter() {
@@ -77,6 +97,35 @@ function onToggleFilter() {
   else filterBy.value = '';
 }
 
+const protocolOptions = computed(() => {
+  const values = new Set(props.dbInbounds.map((i) => i.protocol).filter(Boolean));
+  return [...values].sort();
+});
+
+const nodeOptions = computed(() => {
+  const values = new Map();
+  if (props.dbInbounds.some((i) => i.nodeId == null)) {
+    values.set('local', t('pages.inbounds.localPanel'));
+  }
+  for (const dbInbound of props.dbInbounds) {
+    if (dbInbound.nodeId == null) continue;
+    const node = props.nodesById.get(dbInbound.nodeId);
+    values.set(String(dbInbound.nodeId), node?.name || `#${dbInbound.nodeId}`);
+  }
+  return [...values.entries()].map(([value, label]) => ({ value, label }));
+});
+
+function applySecondaryFilters(rows) {
+  return rows.filter((dbInbound) => {
+    if (protocolFilter.value && dbInbound.protocol !== protocolFilter.value) return false;
+    if (nodeFilter.value) {
+      const nodeValue = dbInbound.nodeId == null ? 'local' : String(dbInbound.nodeId);
+      if (nodeValue !== nodeFilter.value) return false;
+    }
+    return true;
+  });
+}
+
 // ============ Search / filter projection =============================
 // Mirrors the legacy logic: when searching, keep inbounds that match
 // anywhere (deep search); when filtering, keep inbounds that have at
@@ -99,7 +148,7 @@ function projectInbound(dbInbound, predicate) {
 
 const visibleInbounds = computed(() => {
   if (enableFilter.value) {
-    if (ObjectUtil.isEmpty(filterBy.value)) return [...props.dbInbounds];
+    if (ObjectUtil.isEmpty(filterBy.value)) return applySecondaryFilters([...props.dbInbounds]);
     const out = [];
     for (const dbInbound of props.dbInbounds) {
       const c = props.clientCount[dbInbound.id];
@@ -107,15 +156,15 @@ const visibleInbounds = computed(() => {
       const list = c[filterBy.value];
       out.push(projectInbound(dbInbound, (client) => list.includes(client.email)));
     }
-    return out;
+    return applySecondaryFilters(out);
   }
-  if (ObjectUtil.isEmpty(searchKey.value)) return [...props.dbInbounds];
+  if (ObjectUtil.isEmpty(searchKey.value)) return applySecondaryFilters([...props.dbInbounds]);
   const out = [];
   for (const dbInbound of props.dbInbounds) {
     if (!ObjectUtil.deepSearch(dbInbound, searchKey.value)) continue;
     out.push(projectInbound(dbInbound, (client) => ObjectUtil.deepSearch(client, searchKey.value)));
   }
-  return out;
+  return applySecondaryFilters(out);
 });
 
 // ============ Sorting =================================================
@@ -319,6 +368,18 @@ function showQrCodeMenu(dbInbound) {
           <a-radio-button value="expiring">{{ t('depletingSoon') }}</a-radio-button>
           <a-radio-button value="online">{{ t('online') }}</a-radio-button>
         </a-radio-group>
+        <a-select v-model:value="protocolFilter" allow-clear :placeholder="t('pages.inbounds.protocol')"
+          :size="isMobile ? 'small' : 'middle'" :style="{ width: '150px' }">
+          <a-select-option v-for="protocol in protocolOptions" :key="protocol" :value="protocol">
+            {{ protocol }}
+          </a-select-option>
+        </a-select>
+        <a-select v-if="nodeOptions.length > 0" v-model:value="nodeFilter" allow-clear
+          :placeholder="t('pages.inbounds.node')" :size="isMobile ? 'small' : 'middle'" :style="{ width: '170px' }">
+          <a-select-option v-for="node in nodeOptions" :key="node.value" :value="node.value">
+            {{ node.label }}
+          </a-select-option>
+        </a-select>
       </div>
 
       <!-- ====================== Mobile: card list ======================= -->

+ 7 - 0
frontend/src/pages/nodes/NodeFormModal.vue

@@ -28,6 +28,7 @@ function defaultForm() {
     basePath: '/',
     apiToken: '',
     enable: true,
+    allowPrivateAddress: false,
   };
 }
 
@@ -69,6 +70,7 @@ function buildPayload() {
     basePath: form.basePath?.trim() || '/',
     apiToken: form.apiToken?.trim() || '',
     enable: !!form.enable,
+    allowPrivateAddress: !!form.allowPrivateAddress,
   };
 }
 
@@ -161,6 +163,11 @@ async function onSave() {
         </a-col>
       </a-row>
 
+      <a-form-item label="Allow private address">
+        <a-switch v-model:checked="form.allowPrivateAddress" />
+        <div class="hint">Enable only for nodes on a private network or VPN.</div>
+      </a-form-item>
+
       <a-form-item :label="t('pages.nodes.apiToken')" required>
         <a-input-password v-model:value="form.apiToken" :placeholder="t('pages.nodes.apiTokenPlaceholder')" />
         <div class="hint">{{ t('pages.nodes.apiTokenHint') }}</div>

+ 13 - 1
frontend/src/pages/settings/GeneralTab.vue

@@ -153,6 +153,14 @@ onMounted(loadInboundTags);
         </template>
       </SettingListItem>
 
+      <SettingListItem paddings="small">
+        <template #title>Trusted proxy CIDRs</template>
+        <template #description>Comma-separated IPs/CIDRs allowed to set forwarded host, proto, and client IP headers.</template>
+        <template #control>
+          <a-input v-model:value="allSetting.trustedProxyCIDRs" placeholder="127.0.0.1/32,::1/128" />
+        </template>
+      </SettingListItem>
+
       <SettingListItem paddings="small">
         <template #title>{{ t('pages.settings.pageSize') }}</template>
         <template #description>{{ t('pages.settings.pageSizeDesc') }}</template>
@@ -298,8 +306,12 @@ onMounted(loadInboundTags);
 
       <SettingListItem paddings="small">
         <template #title>{{ t('password') }}</template>
+        <template #description>
+          {{ allSetting.hasLdapPassword ? 'Configured; leave blank to keep current password.' : 'Not configured.' }}
+        </template>
         <template #control>
-          <a-input-password v-model:value="allSetting.ldapPassword" />
+          <a-input-password v-model:value="allSetting.ldapPassword"
+            :placeholder="allSetting.hasLdapPassword ? 'Configured - enter a new value to replace' : ''" />
         </template>
       </SettingListItem>
 

+ 3 - 4
frontend/src/pages/settings/SecurityTab.vue

@@ -52,10 +52,9 @@ async function sendUpdateUser() {
   try {
     const msg = await HttpUtil.post('/panel/setting/updateUser', user);
     if (msg?.success) {
-      // Force re-login at the standard logout path; basePath is handled
-      // by the Go router so a relative redirect is correct here.
-      const basePath = window.X_UI_BASE_PATH || '';
-      window.location.replace(`${basePath}logout`);
+      await HttpUtil.post('/logout');
+      const basePath = window.X_UI_BASE_PATH || '/';
+      window.location.replace(basePath);
     }
   } finally {
     updating.value = false;

+ 5 - 2
frontend/src/pages/settings/TelegramTab.vue

@@ -23,9 +23,12 @@ defineProps({
 
       <SettingListItem paddings="small">
         <template #title>{{ t('pages.settings.telegramToken') }}</template>
-        <template #description>{{ t('pages.settings.telegramTokenDesc') }}</template>
+        <template #description>
+          {{ allSetting.hasTgBotToken ? 'Configured; leave blank to keep current token.' : t('pages.settings.telegramTokenDesc') }}
+        </template>
         <template #control>
-          <a-input v-model:value="allSetting.tgBotToken" type="text" />
+          <a-input-password v-model:value="allSetting.tgBotToken"
+            :placeholder="allSetting.hasTgBotToken ? 'Configured - enter a new token to replace' : ''" />
         </template>
       </SettingListItem>
 

+ 8 - 2
frontend/src/pages/settings/TwoFactorModal.vue

@@ -38,18 +38,24 @@ function buildTotp() {
 watch(() => props.open, (next) => {
   if (!next) return;
   enteredCode.value = '';
+  totp = null;
+  qrValue.value = '';
   if (props.token) {
     buildTotp();
   }
 });
 
-function close(success) {
-  emit('confirm', success);
+function close(success, code = '') {
+  emit('confirm', success, code);
   emit('update:open', false);
   enteredCode.value = '';
 }
 
 function onOk() {
+  if (props.type === 'confirm' && !props.token) {
+    close(true, enteredCode.value);
+    return;
+  }
   if (!totp) return;
   if (totp.generate() === enteredCode.value) {
     close(true);

+ 0 - 1
frontend/src/pages/sub/SubPage.vue

@@ -40,7 +40,6 @@ const subUrl = subData.subUrl || '';
 const subJsonUrl = subData.subJsonUrl || '';
 const subClashUrl = subData.subClashUrl || '';
 const subTitle = subData.subTitle || '';
-const subSupportUrl = subData.subSupportUrl || '';
 const links = Array.isArray(subData.links) ? subData.links : [];
 // Panel's "Calendar Type" setting; controls whether expiry / lastOnline
 // render in Gregorian or Jalali on this standalone subscription page.

+ 1 - 1
frontend/src/pages/xray/DnsPresetsModal.vue

@@ -4,7 +4,7 @@ import { useI18n } from 'vue-i18n';
 
 const { t } = useI18n();
 
-const props = defineProps({
+defineProps({
   open: { type: Boolean, default: false },
 });
 

+ 6 - 16
web/controller/api.go

@@ -29,25 +29,11 @@ func NewAPIController(g *gin.RouterGroup, customGeo *service.CustomGeoService) *
 	return a
 }
 
-// checkAPIAuth is a middleware that returns 404 for unauthenticated API requests
-// to hide the existence of API endpoints from unauthorized users.
-//
-// Two auth paths are accepted:
-//  1. Authorization: Bearer <apiToken> — used by remote central panels
-//     polling this instance as a node. Matches via constant-time compare.
-//     Sets c.Set("api_authed", true) so CSRFMiddleware can short-circuit.
-//  2. Existing session cookie — used by browsers logged into the panel UI.
-//
-// Anything else falls through to a 404 so the API endpoints remain hidden.
 func (a *APIController) checkAPIAuth(c *gin.Context) {
 	auth := c.GetHeader("Authorization")
 	if strings.HasPrefix(auth, "Bearer ") {
 		tok := strings.TrimPrefix(auth, "Bearer ")
 		if a.settingService.MatchApiToken(tok) {
-			// Handlers like InboundController.addInbound assume a logged-in
-			// user (inbound.UserId = user.Id). Bearer callers have no
-			// session, so attach the first user as a fallback. Single-user
-			// panels are the norm here.
 			if u, err := a.userService.GetFirstUser(); err == nil {
 				session.SetAPIAuthUser(c, u)
 			}
@@ -57,7 +43,11 @@ func (a *APIController) checkAPIAuth(c *gin.Context) {
 		}
 	}
 	if !session.IsLogin(c) {
-		c.AbortWithStatus(http.StatusNotFound)
+		if c.GetHeader("X-Requested-With") == "XMLHttpRequest" {
+			c.AbortWithStatus(http.StatusUnauthorized)
+		} else {
+			c.AbortWithStatus(http.StatusNotFound)
+		}
 		return
 	}
 	c.Next()
@@ -85,7 +75,7 @@ func (a *APIController) initRouter(g *gin.RouterGroup, customGeo *service.Custom
 	NewCustomGeoController(api.Group("/custom-geo"), customGeo)
 
 	// Extra routes
-	api.GET("/backuptotgbot", a.BackuptoTgbot)
+	api.POST("/backuptotgbot", a.BackuptoTgbot)
 }
 
 // BackuptoTgbot sends a backup of the panel data to Telegram bot admins.

+ 5 - 1
web/controller/dist.go

@@ -57,7 +57,11 @@ func serveDistPage(c *gin.Context, name string) {
 	}
 	csrfMeta := []byte(`<meta name="csrf-token" content="` + htmlpkg.EscapeString(csrfToken) + `">`)
 
-	script := `<script>window.X_UI_BASE_PATH="` + escapedBase + `"`
+	nonceAttr := ""
+	if nonce := c.GetString("csp_nonce"); nonce != "" {
+		nonceAttr = ` nonce="` + htmlpkg.EscapeString(nonce) + `"`
+	}
+	script := `<script` + nonceAttr + `>window.X_UI_BASE_PATH="` + escapedBase + `"`
 	if name != "login.html" {
 		escapedVer := jsEscape.Replace(config.GetVersion())
 		script += `;window.X_UI_CUR_VER="` + escapedVer + `"`

+ 11 - 9
web/controller/inbound.go

@@ -582,17 +582,19 @@ func (a *InboundController) delInboundClientByEmail(c *gin.Context) {
 // controller layer means the service interface stays HTTP-agnostic — service
 // methods receive a plain host string instead of a *gin.Context.
 func resolveHost(c *gin.Context) string {
-	if h := strings.TrimSpace(c.GetHeader("X-Forwarded-Host")); h != "" {
-		if i := strings.Index(h, ","); i >= 0 {
-			h = strings.TrimSpace(h[:i])
+	if isTrustedForwardedRequest(c) {
+		if h := strings.TrimSpace(c.GetHeader("X-Forwarded-Host")); h != "" {
+			if i := strings.Index(h, ","); i >= 0 {
+				h = strings.TrimSpace(h[:i])
+			}
+			if hp, _, err := net.SplitHostPort(h); err == nil {
+				return hp
+			}
+			return h
 		}
-		if hp, _, err := net.SplitHostPort(h); err == nil {
-			return hp
+		if h := c.GetHeader("X-Real-IP"); h != "" {
+			return h
 		}
-		return h
-	}
-	if h := c.GetHeader("X-Real-IP"); h != "" {
-		return h
 	}
 	if h, _, err := net.SplitHostPort(c.Request.Host); err == nil {
 		return h

+ 3 - 8
web/controller/index.go

@@ -39,15 +39,10 @@ func NewIndexController(g *gin.RouterGroup) *IndexController {
 // initRouter sets up the routes for index, login, logout, and two-factor authentication.
 func (a *IndexController) initRouter(g *gin.RouterGroup) {
 	g.GET("/", a.index)
-	g.GET("/logout", a.logout)
-	// Public CSRF endpoint — the SPA login page (served by Vite in
-	// dev or by serveDistPage in prod) needs a token to POST /login,
-	// but the panel-side /panel/csrf-token sits behind checkLogin.
-	// EnsureCSRFToken creates a session token even for anonymous
-	// callers, so any pre-login flow can bootstrap from here.
 	g.GET("/csrf-token", a.csrfToken)
 
 	g.POST("/login", middleware.CSRFMiddleware(), a.login)
+	g.POST("/logout", middleware.CSRFMiddleware(), a.logout)
 	g.POST("/getTwoFactorEnable", middleware.CSRFMiddleware(), a.getTwoFactorEnable)
 }
 
@@ -140,7 +135,7 @@ func loginFailureReason(err error) string {
 	return "invalid credentials"
 }
 
-// logout handles user logout by clearing the session and redirecting to the login page.
+// logout clears the session. The SPA performs the navigation client-side.
 func (a *IndexController) logout(c *gin.Context) {
 	user := session.GetLoginUser(c)
 	if user != nil {
@@ -150,7 +145,7 @@ func (a *IndexController) logout(c *gin.Context) {
 		logger.Warning("Unable to clear session on logout:", err)
 	}
 	c.Header("Cache-Control", "no-store")
-	c.Redirect(http.StatusTemporaryRedirect, c.GetString("base_path"))
+	c.JSON(http.StatusOK, gin.H{"success": true})
 }
 
 // csrfToken returns the session CSRF token. Public — the login page

+ 55 - 9
web/controller/util.go

@@ -9,29 +9,75 @@ import (
 
 	"github.com/mhsanaei/3x-ui/v3/logger"
 	"github.com/mhsanaei/3x-ui/v3/web/entity"
+	"github.com/mhsanaei/3x-ui/v3/web/service"
 
 	"github.com/gin-gonic/gin"
 )
 
 // getRemoteIp extracts the real IP address from the request headers or remote address.
 func getRemoteIp(c *gin.Context) string {
-	if ip, ok := extractTrustedIP(c.GetHeader("X-Real-IP")); ok {
-		return ip
+	remoteIP, ok := extractTrustedIP(c.Request.RemoteAddr)
+	if !ok {
+		return "unknown"
 	}
 
-	if xff := c.GetHeader("X-Forwarded-For"); xff != "" {
-		for _, part := range strings.Split(xff, ",") {
-			if ip, ok := extractTrustedIP(part); ok {
-				return ip
+	if isTrustedProxy(remoteIP) {
+		if ip, ok := extractTrustedIP(c.GetHeader("X-Real-IP")); ok {
+			return ip
+		}
+
+		if xff := c.GetHeader("X-Forwarded-For"); xff != "" {
+			for _, part := range strings.Split(xff, ",") {
+				if ip, ok := extractTrustedIP(part); ok {
+					return ip
+				}
 			}
 		}
 	}
 
-	if ip, ok := extractTrustedIP(c.Request.RemoteAddr); ok {
-		return ip
+	return remoteIP
+}
+
+func isTrustedForwardedRequest(c *gin.Context) bool {
+	remoteIP, ok := extractTrustedIP(c.Request.RemoteAddr)
+	return ok && isTrustedProxy(remoteIP)
+}
+
+func isTrustedProxy(ip string) bool {
+	addr, err := netip.ParseAddr(ip)
+	if err != nil {
+		return false
 	}
 
-	return "unknown"
+	trusted := trustedProxyCIDRs()
+	for _, value := range strings.Split(trusted, ",") {
+		value = strings.TrimSpace(value)
+		if value == "" {
+			continue
+		}
+		if prefix, err := netip.ParsePrefix(value); err == nil {
+			if prefix.Contains(addr) {
+				return true
+			}
+			continue
+		}
+		if proxyIP, err := netip.ParseAddr(value); err == nil && proxyIP.Unmap() == addr.Unmap() {
+			return true
+		}
+	}
+	return false
+}
+
+func trustedProxyCIDRs() (trusted string) {
+	trusted = "127.0.0.1/32,::1/128"
+	defer func() {
+		_ = recover()
+	}()
+	settingService := service.SettingService{}
+	if value, err := settingService.GetTrustedProxyCIDRs(); err == nil && strings.TrimSpace(value) != "" {
+		trusted = value
+	}
+	return trusted
 }
 
 func extractTrustedIP(value string) (string, bool) {

+ 34 - 0
web/controller/util_test.go

@@ -0,0 +1,34 @@
+package controller
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"testing"
+
+	"github.com/gin-gonic/gin"
+)
+
+func TestGetRemoteIpIgnoresForwardedHeadersFromUntrustedRemote(t *testing.T) {
+	gin.SetMode(gin.TestMode)
+	c, _ := gin.CreateTestContext(httptest.NewRecorder())
+	c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
+	c.Request.RemoteAddr = "203.0.113.10:12345"
+	c.Request.Header.Set("X-Real-IP", "198.51.100.9")
+	c.Request.Header.Set("X-Forwarded-For", "198.51.100.8")
+
+	if got := getRemoteIp(c); got != "203.0.113.10" {
+		t.Fatalf("remote IP = %q, want request remote address", got)
+	}
+}
+
+func TestGetRemoteIpHonorsForwardedHeadersFromTrustedLoopbackProxy(t *testing.T) {
+	gin.SetMode(gin.TestMode)
+	c, _ := gin.CreateTestContext(httptest.NewRecorder())
+	c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
+	c.Request.RemoteAddr = "127.0.0.1:12345"
+	c.Request.Header.Set("X-Forwarded-For", "198.51.100.8, 127.0.0.1")
+
+	if got := getRemoteIp(c); got != "198.51.100.8" {
+		t.Fatalf("remote IP = %q, want forwarded client IP", got)
+	}
+}

+ 5 - 0
web/controller/xray_setting.go

@@ -213,6 +213,11 @@ func (a *XraySettingController) testOutbound(c *gin.Context) {
 
 	// Load the test URL from server settings to prevent SSRF via user-controlled URLs
 	testURL, _ := a.SettingService.GetXrayOutboundTestUrl()
+	testURL, err := service.SanitizePublicHTTPURL(testURL, false)
+	if err != nil {
+		jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
+		return
+	}
 
 	result, err := a.OutboundService.TestOutbound(outboundJSON, testURL, allOutboundsJSON, mode)
 	if err != nil {

+ 35 - 7
web/entity/entity.go

@@ -21,13 +21,14 @@ type Msg struct {
 // AllSetting contains all configuration settings for the 3x-ui panel including web server, Telegram bot, and subscription settings.
 type AllSetting struct {
 	// Web server settings
-	WebListen     string `json:"webListen" form:"webListen"`         // Web server listen IP address
-	WebDomain     string `json:"webDomain" form:"webDomain"`         // Web server domain for domain validation
-	WebPort       int    `json:"webPort" form:"webPort"`             // Web server port number
-	WebCertFile   string `json:"webCertFile" form:"webCertFile"`     // Path to SSL certificate file for web server
-	WebKeyFile    string `json:"webKeyFile" form:"webKeyFile"`       // Path to SSL private key file for web server
-	WebBasePath   string `json:"webBasePath" form:"webBasePath"`     // Base path for web panel URLs
-	SessionMaxAge int    `json:"sessionMaxAge" form:"sessionMaxAge"` // Session maximum age in minutes
+	WebListen         string `json:"webListen" form:"webListen"`                 // Web server listen IP address
+	WebDomain         string `json:"webDomain" form:"webDomain"`                 // Web server domain for domain validation
+	WebPort           int    `json:"webPort" form:"webPort"`                     // Web server port number
+	WebCertFile       string `json:"webCertFile" form:"webCertFile"`             // Path to SSL certificate file for web server
+	WebKeyFile        string `json:"webKeyFile" form:"webKeyFile"`               // Path to SSL private key file for web server
+	WebBasePath       string `json:"webBasePath" form:"webBasePath"`             // Base path for web panel URLs
+	SessionMaxAge     int    `json:"sessionMaxAge" form:"sessionMaxAge"`         // Session maximum age in minutes
+	TrustedProxyCIDRs string `json:"trustedProxyCIDRs" form:"trustedProxyCIDRs"` // Trusted reverse proxy IPs/CIDRs for forwarded headers
 
 	// UI settings
 	PageSize    int    `json:"pageSize" form:"pageSize"`       // Number of items per page in lists
@@ -110,6 +111,20 @@ type AllSetting struct {
 	// JSON subscription routing rules
 }
 
+// AllSettingView is the browser-safe settings read model. Secret values
+// are redacted from the embedded write model and represented by presence
+// flags so the UI can show configured/not configured state.
+type AllSettingView struct {
+	AllSetting
+
+	HasTgBotToken     bool `json:"hasTgBotToken"`
+	HasTwoFactorToken bool `json:"hasTwoFactorToken"`
+	HasLdapPassword   bool `json:"hasLdapPassword"`
+	HasApiToken       bool `json:"hasApiToken"`
+	HasWarpSecret     bool `json:"hasWarpSecret"`
+	HasNordSecret     bool `json:"hasNordSecret"`
+}
+
 // CheckValid validates all settings in the AllSetting struct, checking IP addresses, ports, SSL certificates, and other configuration values.
 func (s *AllSetting) CheckValid() error {
 	if s.WebListen != "" {
@@ -179,6 +194,19 @@ func (s *AllSetting) CheckValid() error {
 		s.SubClashPath += "/"
 	}
 
+	for _, cidr := range strings.Split(s.TrustedProxyCIDRs, ",") {
+		cidr = strings.TrimSpace(cidr)
+		if cidr == "" {
+			continue
+		}
+		if ip := net.ParseIP(cidr); ip != nil {
+			continue
+		}
+		if _, _, err := net.ParseCIDR(cidr); err != nil {
+			return common.NewError("trusted proxy CIDR is not valid:", cidr)
+		}
+	}
+
 	_, err := time.LoadLocation(s.TimeLocation)
 	if err != nil {
 		return common.NewError("time location not exist:", s.TimeLocation)

+ 5 - 0
web/job/xray_traffic_job.go

@@ -152,6 +152,11 @@ func (j *XrayTrafficJob) informTrafficToExternalAPI(inboundTraffics []*xray.Traf
 		logger.Warning("get ExternalTrafficInformURI failed:", err)
 		return
 	}
+	informURL, err = service.SanitizePublicHTTPURL(informURL, false)
+	if err != nil {
+		logger.Warning("ExternalTrafficInformURI blocked:", err)
+		return
+	}
 	requestBody, err := json.Marshal(map[string]any{"clientTraffics": clientTraffics, "inboundTraffics": inboundTraffics})
 	if err != nil {
 		logger.Warning("parse client/inbound traffic failed:", err)

+ 13 - 1
web/middleware/security.go

@@ -1,6 +1,8 @@
 package middleware
 
 import (
+	"crypto/rand"
+	"encoding/base64"
 	"net/http"
 
 	"github.com/mhsanaei/3x-ui/v3/web/session"
@@ -11,10 +13,12 @@ import (
 // SecurityHeadersMiddleware adds browser hardening headers to panel responses.
 func SecurityHeadersMiddleware(directHTTPS bool) gin.HandlerFunc {
 	return func(c *gin.Context) {
+		nonce := newCSPNonce()
+		c.Set("csp_nonce", nonce)
 		c.Header("X-Content-Type-Options", "nosniff")
 		c.Header("X-Frame-Options", "DENY")
 		c.Header("Referrer-Policy", "no-referrer")
-		c.Header("Content-Security-Policy", "frame-ancestors 'none'; base-uri 'self'; form-action 'self'")
+		c.Header("Content-Security-Policy", "default-src 'self'; script-src 'self' 'nonce-"+nonce+"'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' ws: wss:; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'")
 		if directHTTPS {
 			c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
 		}
@@ -22,6 +26,14 @@ func SecurityHeadersMiddleware(directHTTPS bool) gin.HandlerFunc {
 	}
 }
 
+func newCSPNonce() string {
+	var b [16]byte
+	if _, err := rand.Read(b[:]); err != nil {
+		return ""
+	}
+	return base64.RawStdEncoding.EncodeToString(b[:])
+}
+
 // CSRFMiddleware rejects unsafe requests that do not include the session CSRF token.
 // Bearer-token-authenticated callers (api_authed flag set by APIController.checkAPIAuth)
 // short-circuit the CSRF check — they are not browser sessions, so the

+ 9 - 8
web/service/node.go

@@ -105,14 +105,15 @@ func (s *NodeService) Update(id int, in *model.Node) error {
 		return err
 	}
 	updates := map[string]any{
-		"name":      in.Name,
-		"remark":    in.Remark,
-		"scheme":    in.Scheme,
-		"address":   in.Address,
-		"port":      in.Port,
-		"base_path": in.BasePath,
-		"api_token": in.ApiToken,
-		"enable":    in.Enable,
+		"name":                  in.Name,
+		"remark":                in.Remark,
+		"scheme":                in.Scheme,
+		"address":               in.Address,
+		"port":                  in.Port,
+		"base_path":             in.BasePath,
+		"api_token":             in.ApiToken,
+		"enable":                in.Enable,
+		"allow_private_address": in.AllowPrivateAddress,
 	}
 	if err := db.Model(model.Node{}).Where("id = ?", id).Updates(updates).Error; err != nil {
 		return err

+ 50 - 3
web/service/panel.go

@@ -3,6 +3,7 @@ package service
 import (
 	"encoding/json"
 	"fmt"
+	"io"
 	"net/http"
 	"os"
 	"os/exec"
@@ -28,6 +29,11 @@ type PanelUpdateInfo struct {
 	UpdateAvailable bool   `json:"updateAvailable"`
 }
 
+const (
+	panelUpdaterURL      = "https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh"
+	maxPanelUpdaterBytes = 2 << 20
+)
+
 func (s *PanelService) RestartPanel(delay time.Duration) error {
 	p, err := os.FindProcess(syscall.Getpid())
 	if err != nil {
@@ -67,13 +73,14 @@ func (s *PanelService) StartUpdate() error {
 	if err != nil {
 		return fmt.Errorf("bash is required to run the panel updater: %w", err)
 	}
-	curl, err := exec.LookPath("curl")
+
+	scriptPath, err := downloadPanelUpdater()
 	if err != nil {
-		return fmt.Errorf("curl is required to download the panel updater: %w", err)
+		return err
 	}
 
 	mainFolder, serviceFolder := resolveUpdateFolders()
-	updateScript := fmt.Sprintf("set -o pipefail; %s -fLs https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh | %s", shellQuote(curl), shellQuote(bash))
+	updateScript := fmt.Sprintf("set -e; trap 'rm -f %s' EXIT; %s %s", shellQuote(scriptPath), shellQuote(bash), shellQuote(scriptPath))
 
 	if systemdRun, err := exec.LookPath("systemd-run"); err == nil {
 		unitName := fmt.Sprintf("x-ui-web-update-%d", time.Now().Unix())
@@ -88,6 +95,7 @@ func (s *PanelService) StartUpdate() error {
 			output := strings.TrimSpace(string(out))
 			if !strings.Contains(output, "System has not been booted with systemd") &&
 				!strings.Contains(output, "Failed to connect to bus") {
+				_ = os.Remove(scriptPath)
 				return fmt.Errorf("failed to start panel update job: %w: %s", err, output)
 			}
 			logger.Warning("systemd-run is unavailable, falling back to detached update process:", output)
@@ -104,6 +112,7 @@ func (s *PanelService) StartUpdate() error {
 	)
 	setDetachedProcess(cmd)
 	if err := cmd.Start(); err != nil {
+		_ = os.Remove(scriptPath)
 		return fmt.Errorf("failed to start panel update job: %w", err)
 	}
 	if err := cmd.Process.Release(); err != nil {
@@ -113,6 +122,44 @@ func (s *PanelService) StartUpdate() error {
 	return nil
 }
 
+func downloadPanelUpdater() (string, error) {
+	client := &http.Client{Timeout: 15 * time.Second}
+	resp, err := client.Get(panelUpdaterURL)
+	if err != nil {
+		return "", fmt.Errorf("download panel updater: %w", err)
+	}
+	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return "", fmt.Errorf("download panel updater: unexpected HTTP %d", resp.StatusCode)
+	}
+
+	file, err := os.CreateTemp("", "3x-ui-update-*.sh")
+	if err != nil {
+		return "", err
+	}
+	path := file.Name()
+	ok := false
+	defer func() {
+		_ = file.Close()
+		if !ok {
+			_ = os.Remove(path)
+		}
+	}()
+
+	n, err := io.Copy(file, io.LimitReader(resp.Body, maxPanelUpdaterBytes+1))
+	if err != nil {
+		return "", fmt.Errorf("write panel updater: %w", err)
+	}
+	if n > maxPanelUpdaterBytes {
+		return "", fmt.Errorf("panel updater exceeds %d bytes", maxPanelUpdaterBytes)
+	}
+	if err := file.Chmod(0700); err != nil {
+		return "", err
+	}
+	ok = true
+	return path, nil
+}
+
 func fetchLatestPanelVersion() (string, error) {
 	client := &http.Client{Timeout: 10 * time.Second}
 	resp, err := client.Get("https://api.github.com/repos/MHSanaei/3x-ui/releases/latest")

+ 70 - 12
web/service/server.go

@@ -14,6 +14,7 @@ import (
 	"path/filepath"
 	"regexp"
 	"runtime"
+	"slices"
 	"strconv"
 	"strings"
 	"sync"
@@ -493,6 +494,11 @@ func (s *ServerService) sampleCPUUtilization() (float64, error) {
 
 var xrayVersionsClient = &http.Client{Timeout: 10 * time.Second}
 
+const (
+	maxXrayArchiveBytes = 200 << 20
+	maxXrayBinaryBytes  = 200 << 20
+)
+
 func (s *ServerService) GetXrayVersions() ([]string, error) {
 	const (
 		XrayURL    = "https://api.github.com/repos/XTLS/Xray-core/releases"
@@ -601,28 +607,53 @@ func (s *ServerService) downloadXRay(version string) (string, error) {
 
 	fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch)
 	url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName)
-	resp, err := http.Get(url)
+	client := &http.Client{Timeout: 60 * time.Second}
+	resp, err := client.Get(url)
 	if err != nil {
 		return "", err
 	}
 	defer resp.Body.Close()
+	if resp.StatusCode != http.StatusOK {
+		return "", fmt.Errorf("download xray: unexpected HTTP %d", resp.StatusCode)
+	}
+	if resp.ContentLength > maxXrayArchiveBytes {
+		return "", fmt.Errorf("download xray: archive exceeds %d bytes", maxXrayArchiveBytes)
+	}
 
-	os.Remove(fileName)
-	file, err := os.Create(fileName)
+	file, err := os.CreateTemp("", "xray-*.zip")
 	if err != nil {
 		return "", err
 	}
-	defer file.Close()
+	path := file.Name()
+	ok := false
+	defer func() {
+		_ = file.Close()
+		if !ok {
+			_ = os.Remove(path)
+		}
+	}()
 
-	_, err = io.Copy(file, resp.Body)
+	n, err := io.Copy(file, io.LimitReader(resp.Body, maxXrayArchiveBytes+1))
 	if err != nil {
 		return "", err
 	}
+	if n > maxXrayArchiveBytes {
+		return "", fmt.Errorf("download xray: archive exceeds %d bytes", maxXrayArchiveBytes)
+	}
 
-	return fileName, nil
+	ok = true
+	return path, nil
 }
 
 func (s *ServerService) UpdateXray(version string) error {
+	versions, err := s.GetXrayVersions()
+	if err != nil {
+		return err
+	}
+	if !slices.Contains(versions, version) {
+		return fmt.Errorf("xray version %q is not in the fetched release list", version)
+	}
+
 	// 1. Stop xray before doing anything
 	if err := s.StopXrayService(); err != nil {
 		logger.Warning("failed to stop xray before update:", err)
@@ -657,15 +688,42 @@ func (s *ServerService) UpdateXray(version string) error {
 			return err
 		}
 		defer zipFile.Close()
-		os.MkdirAll(filepath.Dir(fileName), 0755)
-		os.Remove(fileName)
-		file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0755)
+		if err := os.MkdirAll(filepath.Dir(fileName), 0755); err != nil {
+			return err
+		}
+		tmpFile, err := os.CreateTemp(filepath.Dir(fileName), ".xray-*")
 		if err != nil {
 			return err
 		}
-		defer file.Close()
-		_, err = io.Copy(file, zipFile)
-		return err
+		tmpPath := tmpFile.Name()
+		ok := false
+		defer func() {
+			_ = tmpFile.Close()
+			if !ok {
+				_ = os.Remove(tmpPath)
+			}
+		}()
+		n, err := io.Copy(tmpFile, io.LimitReader(zipFile, maxXrayBinaryBytes+1))
+		if err != nil {
+			return err
+		}
+		if n > maxXrayBinaryBytes {
+			return fmt.Errorf("xray binary exceeds %d bytes", maxXrayBinaryBytes)
+		}
+		if err := tmpFile.Chmod(0755); err != nil {
+			return err
+		}
+		if err := tmpFile.Close(); err != nil {
+			return err
+		}
+		if runtime.GOOS == "windows" {
+			_ = os.Remove(fileName)
+		}
+		if err := os.Rename(tmpPath, fileName); err != nil {
+			return err
+		}
+		ok = true
+		return nil
 	}
 
 	// 4. Extract correct binary

+ 94 - 1
web/service/setting.go

@@ -36,6 +36,7 @@ var defaultValueMap = map[string]string{
 	"apiToken":                    "",
 	"webBasePath":                 "/",
 	"sessionMaxAge":               "360",
+	"trustedProxyCIDRs":           "127.0.0.1/32,::1/128",
 	"pageSize":                    "25",
 	"expireDiff":                  "0",
 	"trafficDiff":                 "0",
@@ -199,6 +200,32 @@ func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) {
 	return allSetting, nil
 }
 
+func (s *SettingService) GetAllSettingView() (*entity.AllSettingView, error) {
+	allSetting, err := s.GetAllSetting()
+	if err != nil {
+		return nil, err
+	}
+	view := &entity.AllSettingView{AllSetting: *allSetting}
+	view.HasTgBotToken = secretConfigured(allSetting.TgBotToken)
+	view.HasTwoFactorToken = secretConfigured(allSetting.TwoFactorToken)
+	view.HasLdapPassword = secretConfigured(allSetting.LdapPassword)
+	view.HasWarpSecret = secretConfigured(mustString(s.GetWarp()))
+	view.HasNordSecret = secretConfigured(mustString(s.GetNord()))
+	view.HasApiToken = secretConfigured(mustString(s.getString("apiToken")))
+	view.TgBotToken = ""
+	view.TwoFactorToken = ""
+	view.LdapPassword = ""
+	return view, nil
+}
+
+func secretConfigured(value string) bool {
+	return strings.TrimSpace(value) != ""
+}
+
+func mustString(value string, _ error) string {
+	return value
+}
+
 func (s *SettingService) ResetSettings() error {
 	db := database.GetDB()
 	err := db.Where("1 = 1").Delete(model.Setting{}).Error
@@ -286,7 +313,11 @@ func (s *SettingService) GetXrayOutboundTestUrl() (string, error) {
 }
 
 func (s *SettingService) SetXrayOutboundTestUrl(url string) error {
-	return s.setString("xrayOutboundTestUrl", url)
+	clean, err := SanitizeHTTPURL(url)
+	if err != nil {
+		return err
+	}
+	return s.setString("xrayOutboundTestUrl", clean)
 }
 
 func (s *SettingService) GetListen() (string, error) {
@@ -417,6 +448,10 @@ func (s *SettingService) GetSessionMaxAge() (int, error) {
 	return s.getInt("sessionMaxAge")
 }
 
+func (s *SettingService) GetTrustedProxyCIDRs() (string, error) {
+	return s.getString("trustedProxyCIDRs")
+}
+
 func (s *SettingService) GetRemarkModel() (string, error) {
 	return s.getString("remarkModel")
 }
@@ -771,6 +806,12 @@ func (s *SettingService) GetLdapDefaultLimitIP() (int, error) {
 }
 
 func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting) error {
+	if err := s.preserveRedactedSecrets(allSetting); err != nil {
+		return err
+	}
+	if err := validateSettingsURLs(allSetting); err != nil {
+		return err
+	}
 	if err := allSetting.CheckValid(); err != nil {
 		return err
 	}
@@ -791,6 +832,58 @@ func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting) error {
 	return common.Combine(errs...)
 }
 
+func (s *SettingService) preserveRedactedSecrets(allSetting *entity.AllSetting) error {
+	if strings.TrimSpace(allSetting.TgBotToken) == "" {
+		value, err := s.GetTgBotToken()
+		if err != nil {
+			return err
+		}
+		allSetting.TgBotToken = value
+	}
+	if strings.TrimSpace(allSetting.LdapPassword) == "" {
+		value, err := s.GetLdapPassword()
+		if err != nil {
+			return err
+		}
+		allSetting.LdapPassword = value
+	}
+	if allSetting.TwoFactorEnable && strings.TrimSpace(allSetting.TwoFactorToken) == "" {
+		value, err := s.GetTwoFactorToken()
+		if err != nil {
+			return err
+		}
+		allSetting.TwoFactorToken = value
+	}
+	return nil
+}
+
+func validateSettingsURLs(allSetting *entity.AllSetting) error {
+	if allSetting.ExternalTrafficInformURI != "" {
+		u, err := SanitizeHTTPURL(allSetting.ExternalTrafficInformURI)
+		if err != nil {
+			return common.NewError("external traffic inform URI is invalid:", err)
+		}
+		allSetting.ExternalTrafficInformURI = u
+	}
+	if allSetting.TgBotAPIServer != "" {
+		u, err := SanitizeHTTPURL(allSetting.TgBotAPIServer)
+		if err != nil {
+			return common.NewError("telegram API server URL is invalid:", err)
+		}
+		allSetting.TgBotAPIServer = u
+	}
+	return nil
+}
+
+func (s *SettingService) UpdateSecret(key string, value string) error {
+	switch key {
+	case "tgBotToken", "ldapPassword", "twoFactorToken", "apiToken":
+		return s.saveSetting(key, strings.TrimSpace(value))
+	default:
+		return common.NewError("secret key is not replaceable:", key)
+	}
+}
+
 func (s *SettingService) GetDefaultXrayConfig() (any, error) {
 	var jsonData any
 	err := json.Unmarshal([]byte(xrayTemplateConfig), &jsonData)

+ 92 - 0
web/service/setting_security_test.go

@@ -0,0 +1,92 @@
+package service
+
+import (
+	"path/filepath"
+	"testing"
+
+	"github.com/mhsanaei/3x-ui/v3/database"
+)
+
+func setupSettingTestDB(t *testing.T) {
+	t.Helper()
+	if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() {
+		if err := database.CloseDB(); err != nil {
+			t.Fatal(err)
+		}
+	})
+}
+
+func TestGetAllSettingViewRedactsSecrets(t *testing.T) {
+	setupSettingTestDB(t)
+	s := &SettingService{}
+	if err := s.saveSetting("tgBotToken", "telegram-secret"); err != nil {
+		t.Fatal(err)
+	}
+	if err := s.saveSetting("twoFactorToken", "totp-secret"); err != nil {
+		t.Fatal(err)
+	}
+	if err := s.saveSetting("ldapPassword", "ldap-secret"); err != nil {
+		t.Fatal(err)
+	}
+	if err := s.saveSetting("apiToken", "api-secret"); err != nil {
+		t.Fatal(err)
+	}
+
+	view, err := s.GetAllSettingView()
+	if err != nil {
+		t.Fatal(err)
+	}
+	if view.TgBotToken != "" || view.TwoFactorToken != "" || view.LdapPassword != "" {
+		t.Fatalf("settings view leaked secrets: %#v", view)
+	}
+	if !view.HasTgBotToken || !view.HasTwoFactorToken || !view.HasLdapPassword || !view.HasApiToken {
+		t.Fatalf("settings view did not report configured secret flags: %#v", view)
+	}
+}
+
+func TestUpdateAllSettingPreservesRedactedSecrets(t *testing.T) {
+	setupSettingTestDB(t)
+	s := &SettingService{}
+	if err := s.saveSetting("tgBotToken", "telegram-secret"); err != nil {
+		t.Fatal(err)
+	}
+	if err := s.saveSetting("ldapPassword", "ldap-secret"); err != nil {
+		t.Fatal(err)
+	}
+	if err := s.saveSetting("twoFactorEnable", "true"); err != nil {
+		t.Fatal(err)
+	}
+	if err := s.saveSetting("twoFactorToken", "totp-secret"); err != nil {
+		t.Fatal(err)
+	}
+
+	view, err := s.GetAllSettingView()
+	if err != nil {
+		t.Fatal(err)
+	}
+	settings := &view.AllSetting
+	if err := s.UpdateAllSetting(settings); err != nil {
+		t.Fatal(err)
+	}
+	if got, _ := s.GetTgBotToken(); got != "telegram-secret" {
+		t.Fatalf("tg token = %q, want preserved secret", got)
+	}
+	if got, _ := s.GetLdapPassword(); got != "ldap-secret" {
+		t.Fatalf("ldap password = %q, want preserved secret", got)
+	}
+	if got, _ := s.GetTwoFactorToken(); got != "totp-secret" {
+		t.Fatalf("2fa token = %q, want preserved secret", got)
+	}
+}
+
+func TestSanitizePublicHTTPURLBlocksPrivateAddressUnlessAllowed(t *testing.T) {
+	if _, err := SanitizePublicHTTPURL("http://127.0.0.1:8080/hook", false); err == nil {
+		t.Fatal("expected localhost URL to be blocked")
+	}
+	if got, err := SanitizePublicHTTPURL("http://127.0.0.1:8080/hook", true); err != nil || got != "http://127.0.0.1:8080/hook" {
+		t.Fatalf("allowPrivate result = %q, %v", got, err)
+	}
+}

+ 4 - 7
web/service/tgbot.go

@@ -341,15 +341,12 @@ func (t *Tgbot) NewBot(token string, proxyUrl string, apiServerUrl string) (*tel
 
 	// Validate API server URL if provided
 	if apiServerUrl != "" {
-		if !strings.HasPrefix(apiServerUrl, "http") {
-			logger.Warning("Invalid http(s) URL for API server, using default")
+		safeURL, err := SanitizePublicHTTPURL(apiServerUrl, false)
+		if err != nil {
+			logger.Warningf("Invalid or blocked API server URL, using default: %v", err)
 			apiServerUrl = ""
 		} else {
-			_, err := url.Parse(apiServerUrl)
-			if err != nil {
-				logger.Warningf("Can't parse API server URL, using default: %v", err)
-				apiServerUrl = ""
-			}
+			apiServerUrl = safeURL
 		}
 	}
 

+ 82 - 0
web/service/url_safety.go

@@ -0,0 +1,82 @@
+package service
+
+import (
+	"context"
+	"fmt"
+	"net"
+	"net/url"
+	"strings"
+	"time"
+)
+
+// SanitizeHTTPURL validates and normalizes an http(s) URL without resolving
+// DNS. Use SanitizePublicHTTPURL at the point of an outbound request.
+func SanitizeHTTPURL(raw string) (string, error) {
+	raw = strings.TrimSpace(raw)
+	if raw == "" {
+		return "", nil
+	}
+	u, err := url.Parse(raw)
+	if err != nil {
+		return "", err
+	}
+	if u.Scheme != "http" && u.Scheme != "https" {
+		return "", fmt.Errorf("unsupported URL scheme %q", u.Scheme)
+	}
+	if u.Host == "" || u.Hostname() == "" {
+		return "", fmt.Errorf("URL host is required")
+	}
+	clean := &url.URL{
+		Scheme:   u.Scheme,
+		Host:     u.Host,
+		Path:     u.Path,
+		RawPath:  u.RawPath,
+		RawQuery: u.RawQuery,
+		Fragment: u.Fragment,
+	}
+	return clean.String(), nil
+}
+
+// SanitizePublicHTTPURL validates and normalizes an http(s) URL, then blocks
+// private/internal targets unless the caller explicitly allows them.
+func SanitizePublicHTTPURL(raw string, allowPrivate bool) (string, error) {
+	clean, err := SanitizeHTTPURL(raw)
+	if err != nil || clean == "" {
+		return clean, err
+	}
+	if allowPrivate {
+		return clean, nil
+	}
+	u, err := url.Parse(clean)
+	if err != nil {
+		return "", err
+	}
+	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	defer cancel()
+	if err := rejectPrivateHost(ctx, u.Hostname()); err != nil {
+		return "", err
+	}
+	return clean, nil
+}
+
+func rejectPrivateHost(ctx context.Context, hostname string) error {
+	if ip := net.ParseIP(hostname); ip != nil {
+		if isBlockedIP(ip) {
+			return fmt.Errorf("blocked private/internal address %s", ip.String())
+		}
+		return nil
+	}
+	ips, err := net.DefaultResolver.LookupIPAddr(ctx, hostname)
+	if err != nil {
+		return fmt.Errorf("cannot resolve host %s: %w", hostname, err)
+	}
+	if len(ips) == 0 {
+		return fmt.Errorf("host %s has no IP addresses", hostname)
+	}
+	for _, ipAddr := range ips {
+		if isBlockedIP(ipAddr.IP) {
+			return fmt.Errorf("host %s resolves to blocked private/internal address %s", hostname, ipAddr.IP.String())
+		}
+	}
+	return nil
+}

+ 6 - 1
web/service/user.go

@@ -122,7 +122,11 @@ func (s *UserService) UpdateUser(id int, username string, password string) error
 
 	return db.Model(model.User{}).
 		Where("id = ?", id).
-		Updates(map[string]any{"username": username, "password": hashedPassword}).
+		Updates(map[string]any{
+			"username":    username,
+			"password":    hashedPassword,
+			"login_epoch": gorm.Expr("login_epoch + 1"),
+		}).
 		Error
 }
 
@@ -150,5 +154,6 @@ func (s *UserService) UpdateFirstUser(username string, password string) error {
 	}
 	user.Username = username
 	user.Password = hashedPassword
+	user.LoginEpoch++
 	return db.Save(user).Error
 }

+ 4 - 4
web/service/xray_metrics.go

@@ -32,10 +32,10 @@ type ObsTagSnapshot struct {
 type XrayMetricsService struct {
 	settingService SettingService
 
-	mu        sync.RWMutex
-	state     xrayMetricsState
-	client    *http.Client
-	obsByTag  map[string]ObsTagSnapshot
+	mu       sync.RWMutex
+	state    xrayMetricsState
+	client   *http.Client
+	obsByTag map[string]ObsTagSnapshot
 }
 
 var validObsTag = regexp.MustCompile(`^[a-zA-Z0-9._\-]+$`)

+ 98 - 3
web/session/session.go

@@ -5,6 +5,7 @@ import (
 	"net/http"
 	"time"
 
+	"github.com/mhsanaei/3x-ui/v3/database"
 	"github.com/mhsanaei/3x-ui/v3/database/model"
 	"github.com/mhsanaei/3x-ui/v3/logger"
 
@@ -14,6 +15,7 @@ import (
 
 const (
 	loginUserKey      = "LOGIN_USER"
+	loginEpochKey     = "LOGIN_EPOCH"
 	apiAuthUserKey    = "api_auth_user"
 	sessionCookieName = "3x-ui"
 )
@@ -27,7 +29,8 @@ func SetLoginUser(c *gin.Context, user *model.User) error {
 		return nil
 	}
 	s := sessions.Default(c)
-	s.Set(loginUserKey, *user)
+	s.Set(loginUserKey, user.Id)
+	s.Set(loginEpochKey, user.LoginEpoch)
 	return s.Save()
 }
 
@@ -49,21 +52,113 @@ func GetLoginUser(c *gin.Context) *model.User {
 	if obj == nil {
 		return nil
 	}
-	user, ok := obj.(model.User)
+	userID, ok := sessionUserID(obj)
 	if !ok {
 		s.Delete(loginUserKey)
+		s.Delete(loginEpochKey)
 		if err := s.Save(); err != nil {
 			logger.Warning("session: failed to drop stale user payload:", err)
 		}
 		return nil
 	}
-	return &user
+	if legacyUserID, ok := legacySessionUserID(obj); ok {
+		s.Set(loginUserKey, legacyUserID)
+		if err := s.Save(); err != nil {
+			logger.Warning("session: failed to migrate legacy user payload:", err)
+		}
+	}
+	user, err := getUserByID(userID)
+	if err != nil {
+		logger.Warning("session: failed to load user:", err)
+		s.Delete(loginUserKey)
+		s.Delete(loginEpochKey)
+		if saveErr := s.Save(); saveErr != nil {
+			logger.Warning("session: failed to drop missing user:", saveErr)
+		}
+		return nil
+	}
+	if !sessionEpochMatches(s.Get(loginEpochKey), user.LoginEpoch) {
+		s.Delete(loginUserKey)
+		s.Delete(loginEpochKey)
+		if saveErr := s.Save(); saveErr != nil {
+			logger.Warning("session: failed to drop stale epoch:", saveErr)
+		}
+		return nil
+	}
+	return user
+}
+
+func sessionEpochMatches(cookieVal any, userEpoch int64) bool {
+	var got int64
+	switch v := cookieVal.(type) {
+	case nil:
+	case int64:
+		got = v
+	case int:
+		got = int64(v)
+	case int32:
+		got = int64(v)
+	case float64:
+		got = int64(v)
+	default:
+		return false
+	}
+	return got == userEpoch
 }
 
 func IsLogin(c *gin.Context) bool {
 	return GetLoginUser(c) != nil
 }
 
+func sessionUserID(obj any) (int, bool) {
+	switch v := obj.(type) {
+	case int:
+		return v, v > 0
+	case int64:
+		return int(v), v > 0
+	case int32:
+		return int(v), v > 0
+	case float64:
+		id := int(v)
+		return id, v == float64(id) && id > 0
+	case model.User:
+		return v.Id, v.Id > 0
+	case *model.User:
+		if v == nil {
+			return 0, false
+		}
+		return v.Id, v.Id > 0
+	default:
+		return 0, false
+	}
+}
+
+func legacySessionUserID(obj any) (int, bool) {
+	switch v := obj.(type) {
+	case model.User:
+		return v.Id, v.Id > 0
+	case *model.User:
+		if v == nil {
+			return 0, false
+		}
+		return v.Id, v.Id > 0
+	default:
+		return 0, false
+	}
+}
+
+func getUserByID(id int) (*model.User, error) {
+	db := database.GetDB()
+	if db == nil {
+		return nil, http.ErrServerClosed
+	}
+	user := &model.User{}
+	if err := db.Model(model.User{}).Where("id = ?", id).First(user).Error; err != nil {
+		return nil, err
+	}
+	return user, nil
+}
+
 func ClearSession(c *gin.Context) error {
 	s := sessions.Default(c)
 	s.Clear()

+ 47 - 0
web/session/session_test.go

@@ -0,0 +1,47 @@
+package session
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"testing"
+
+	"github.com/mhsanaei/3x-ui/v3/database/model"
+
+	"github.com/gin-contrib/sessions"
+	"github.com/gin-contrib/sessions/cookie"
+	"github.com/gin-gonic/gin"
+)
+
+func TestSetLoginUserStoresOnlyUserID(t *testing.T) {
+	gin.SetMode(gin.TestMode)
+	router := gin.New()
+	router.Use(sessions.Sessions(sessionCookieName, cookie.NewStore([]byte("01234567890123456789012345678901"))))
+	router.GET("/", func(c *gin.Context) {
+		if err := SetLoginUser(c, &model.User{Id: 7, Username: "admin", Password: "hash"}); err != nil {
+			t.Fatal(err)
+		}
+		got := sessions.Default(c).Get(loginUserKey)
+		if got != 7 {
+			t.Fatalf("stored session payload = %#v, want user id only", got)
+		}
+		c.Status(http.StatusNoContent)
+	})
+
+	rec := httptest.NewRecorder()
+	req := httptest.NewRequest(http.MethodGet, "/", nil)
+	router.ServeHTTP(rec, req)
+	if rec.Code != http.StatusNoContent {
+		t.Fatalf("status = %d, want %d", rec.Code, http.StatusNoContent)
+	}
+}
+
+func TestSessionUserIDSupportsLegacyUserPayload(t *testing.T) {
+	id, ok := sessionUserID(model.User{Id: 11, Username: "admin", Password: "hash"})
+	if !ok || id != 11 {
+		t.Fatalf("legacy session payload resolved to (%d, %v), want (11, true)", id, ok)
+	}
+	id, ok = sessionUserID(&model.User{Id: 12, Username: "admin", Password: "hash"})
+	if !ok || id != 12 {
+		t.Fatalf("legacy pointer session payload resolved to (%d, %v), want (12, true)", id, ok)
+	}
+}

+ 5 - 1
web/web.go

@@ -431,7 +431,11 @@ func (s *Server) start(restartXray bool, startTgBot bool) (err error) {
 	s.listener = listener
 
 	s.httpServer = &http.Server{
-		Handler: engine,
+		Handler:           engine,
+		ReadHeaderTimeout: 5 * time.Second,
+		ReadTimeout:       30 * time.Second,
+		WriteTimeout:      30 * time.Second,
+		IdleTimeout:       120 * time.Second,
 	}
 
 	go func() {