3x-ui/web/controller/util.go

167 lines
3.8 KiB
Go
Raw Normal View History

2023-02-09 19:18:06 +00:00
package controller
import (
"fmt"
2023-02-09 19:18:06 +00:00
"net"
"net/http"
"net/netip"
2023-02-09 19:18:06 +00:00
"strings"
2026-05-10 00:13:42 +00:00
"github.com/mhsanaei/3x-ui/v3/logger"
"github.com/mhsanaei/3x-ui/v3/web/entity"
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 <ho3ein.sanaei@gmail.com>
2026-05-13 10:52:52 +00:00
"github.com/mhsanaei/3x-ui/v3/web/service"
"github.com/gin-gonic/gin"
2023-02-09 19:18:06 +00:00
)
2025-09-20 07:35:50 +00:00
// getRemoteIp extracts the real IP address from the request headers or remote address.
2023-02-09 19:18:06 +00:00
func getRemoteIp(c *gin.Context) string {
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 <ho3ein.sanaei@gmail.com>
2026-05-13 10:52:52 +00:00
remoteIP, ok := extractTrustedIP(c.Request.RemoteAddr)
if !ok {
return "unknown"
}
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 <ho3ein.sanaei@gmail.com>
2026-05-13 10:52:52 +00:00
if isTrustedProxy(remoteIP) {
if ip, ok := extractTrustedIP(c.GetHeader("X-Real-IP")); ok {
return ip
}
if xff := c.GetHeader("X-Forwarded-For"); xff != "" {
Feat/multi inbound clients (#4469) * feat(clients): add shadow tables for first-class client promotion Introduces three new GORM-backed tables (clients, client_inbounds, inbound_fallback_children) and a populate-only seeder that backfills them from each inbound's existing settings.clients JSON. Duplicate emails across inbounds auto-merge under one client row, with each field conflict logged. Existing services are unchanged and continue reading from settings.clients — this commit is groundwork only. * feat(clients): make clients+client_inbounds the runtime source of truth Adds ClientService.SyncInbound that reconciles the new tables from each inbound's clients list whenever existing service paths mutate settings.clients. Wires it into AddInbound, UpdateInbound, AddInboundClient, UpdateInboundClient, DelInboundClient, DelInboundClientByEmail, DelDepletedClients, autoRenewClients, and the timestamp-backfill path in adjustTraffics, plus DetachInbound on DelInbound. GetXrayConfig now builds settings.clients from the new tables before writing config.json, and getInboundsBySubId joins through them instead of JSON_EACH on settings JSON. Live Xray config and subscription endpoints are now driven by the relational view; settings.clients JSON stays in step as a side effect of every write. * feat(clients): add top-level Clients tab and CRUD API Adds /panel/api/clients endpoints (list, get, add, update, del, attach, detach) backed by ClientService methods that orchestrate the per-inbound Add/Update/Del flows so a single client row is created once and attached to many inbounds in one operation. The frontend gains a dedicated Clients page (frontend/clients.html + src/pages/clients/) with an AntD table, multi-inbound attach modal, and full CRUD. Axios interceptor learns to honour Content-Type: application/json so the JSON endpoints work alongside the legacy form-encoded ones. The legacy per-inbound client modal stays untouched in this PR — both flows now write to the same source of truth. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(inbounds): add Port-with-Fallback inbound type Adds a new "portfallback" protocol that emits as a VLESS-TLS inbound under the hood but is paired with a sidecar table of child inbounds. Panel auto-builds settings.fallbacks at Xray-config-gen time from the sidecar — each child's listen+port becomes the fallback dest, with SNI/ALPN/path/xver match criteria pulled from the row. No more typing loopback ports by hand or keeping settings.fallbacks in sync. Backend: new FallbackService (Get/SetChildren, BuildFallbacksJSON); two new routes (GET/POST /panel/api/inbounds/:id/fallbackChildren); xray.GetXrayConfig injects fallbacks for PortFallback inbounds; the inbound model emits protocol="vless" so Xray accepts the config. Frontend: PORTFALLBACK joins the protocol dropdown; selecting it shows the standard VLESS controls plus a Fallback Children table (inbound picker + per-row SNI/ALPN/path/xver). Children are loaded on edit and replaced atomically on save. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): add Reset Traffic, QR Code, Info actions + Online/Remaining columns The Clients page table gains: - Online column — green/grey tag driven by /panel/api/inbounds/onlines, polled every 10s. - Remaining column — bytes-remaining tag, coloured green/orange/red against quota, purple infinity when unlimited. - Action icons per row: QR, Info, Reset traffic, Edit, Delete. ClientInfoModal shows the full client detail (uuid/password/auth, traffic ↑/↓ + remaining + all-time, expiry absolute + relative, attached inbounds chip list, online + last-online). ClientQrModal fetches links for the client's subId via /panel/api/inbounds/getSubLinks/:subId and renders each one through the existing QrPanel component. Reset Traffic confirms then calls the existing per-inbound endpoint on the client's first attached inbound (the traffic row is keyed on email globally, so any attached inbound resets the shared counter). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): expose Attached inbounds in edit mode The multi-select was gated on add-only, so editing a client had no way to change which inbounds it belonged to. The picker now shows in both modes, and on submit the modal diffs the picked set against the original attachedIds — additions go through the /attach endpoint, removals through /detach, both after the field update lands so the new attachments get the latest values. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): unbreak template parsing + stale i18n keys - InboundFormModal: split the multi-line help string in the PortFallback section onto one line — Vue's template parser was bailing on Unterminated string constant because a single-quoted literal spanned two lines inside a {{ }} interpolation. - ClientInfoModal: t('disable') was missing at the root level, so vue-i18n returned the key path literally. Use t('disabled') which exists. - Linter cleanup elsewhere: pages.client.* references renamed to pages.clients.* to match the merged i18n block; whitespace normalisation in a few unrelated Vue templates. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * 1 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(traffic): drop all-time traffic tracking Removes the AllTime field from Inbound and ClientTraffic and migrates existing DBs by dropping the all_time columns on startup. The counter duplicated up+down without adding signal, and the per-event accumulator ran on every traffic write. Frontend: drop the All-time column from the inbound list and the client-row table, the All-time row from the client info modal, and the All-Time Total Usage tile from the inbounds summary card. The allTimeTraffic/allTimeTrafficUsage i18n keys are removed across every locale. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): mobile cards, multi-select, bulk add Adds the same row-card layout the inbounds page uses on mobile: the table is suppressed under the mobile breakpoint and each client renders as a compact card with a status dot, email, Info button, Enable switch, and overflow menu. All the per-client detail (traffic, remaining, expiry, attached inbounds, flow, created/updated, URL, subscription) opens through the existing info modal. Multi-select with bulk delete wires AntD row-selection on desktop and a per-card checkbox on mobile; a Delete (N) button appears in the toolbar when anything is selected. Bulk add reuses the five email-generation modes from the inbound bulk modal but takes a multi-inbound picker so one bulk run can attach to several inbounds at once. Submits client-by-client through the existing /panel/api/clients/add endpoint. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(inbounds): remove legacy per-inbound client UI Now that clients live as first-class rows attached to one or many inbounds, the per-inbound client UI on the inbounds page is dead weight — every client action either has a global equivalent on the Clients page or makes no sense in a many-to-many world. Deletes ClientFormModal, ClientBulkModal, CopyClientsModal, and ClientRowTable from inbounds/. Strips the matching emits, refs, handlers, and dropdown menu items from InboundList and InboundsPage, and removes the dead mobile expand-chevron state and the desktop expanded-row plumbing that drove the inline client table. The InboundFormModal Clients tab still works in add-mode (one inline client at inbound creation) — that flow goes through ClientService. SyncInbound on save and remains useful. Fixes a stray "</a-dropdown>" left over by an earlier toolbar edit in ClientsPage that broke the template parser. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): add Delete depleted action Mirrors the legacy delDepletedClients action that lived under the inbounds page, but as a first-class /panel/api/clients/delDepleted endpoint backed by ClientService. The new path goes through ClientService.Delete for each depleted email, so the new clients + client_inbounds + xray_client_traffic tables stay consistent. Adds a danger-styled toolbar button on the Clients page (next to Reset all client traffic) with a confirm dialog and a toast reporting the deleted count. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(api): move every client-shaped endpoint off /inbounds onto /clients After the multi-inbound client migration, client state belongs to the client API surface, not the inbound one. Twelve routes that were crammed under /panel/api/inbounds/* now live where they belong, under /panel/api/clients/*. Moved (route, handler, doc): POST /clientIps/:email POST /clearClientIps/:email POST /onlines POST /lastOnline POST /updateClientTraffic/:email POST /resetAllClientTraffics/:id POST /delDepletedClients/:id POST /:id/resetClientTraffic/:email GET /getClientTraffics/:email GET /getClientTrafficsById/:id GET /getSubLinks/:subId GET /getClientLinks/:id/:email Their /clients/* counterparts are: POST /clients/clientIps/:email POST /clients/clearClientIps/:email POST /clients/onlines POST /clients/lastOnline POST /clients/updateTraffic/:email POST /clients/resetTraffic/:email (email-only, fans out) GET /clients/traffic/:email GET /clients/traffic/byId/:id GET /clients/subLinks/:subId GET /clients/links/:id/:email per-inbound resetAllClientTraffics and delDepletedClients are dropped entirely — the Clients page already exposes global Reset All Traffic and Delete depleted actions, and per-inbound resets are meaningless once a client can be attached to many inbounds. ClientService.ResetTrafficByEmail is the new email-only reset path: it looks up every inbound the client is attached to and pushes the counter reset + Xray re-add through inboundService.ResetClientTraffic for each one, so depleted users come back online instantly. Frontend callers (ClientsPage, useClients, ClientQrModal, ClientInfoModal, InboundInfoModal, InboundsPage, useInbounds) all switched to the new paths. The Inbounds page drops its per-inbound "Reset client traffic" and "Delete depleted clients" dropdown items — users do those at the client level now. api-docs is rebuilt to match. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(service): switch tgbot + ldap callers to ClientService Adds two thin helpers to ClientService (CreateOne, DetachByEmail) and rewrites tgbot.SubmitAddClient and ldap_sync_job to call ClientService directly. Removes the JSON-blob payloads (BuildJSONForProtocol output for add, clientsToJSON/clientToJSON helpers) that callers previously fed to InboundService.AddInboundClient/DelInboundClient. ldap_sync_job.batchSetEnable now loops InboundService.SetClientEnableByEmail per email instead of trying to coerce AddInboundClient into doing the update — the old path would have failed duplicate-email validation for existing clients anyway. The legacy InboundService.AddInboundClient/UpdateInboundClient/ DelInboundClient methods stay in place; they are now only used internally by ClientService Create/Update/Delete/Attach. Inlining + deleting them follows in a separate commit. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(service): move all client mutation methods to ClientService Moves the client mutation surface out of InboundService and into ClientService. These methods all operate on a single client (identity fields, traffic limits, expiry, ip limit, enable state, telegram tg id) and didn't belong on the inbound aggregate. Moved (12 methods): AddInboundClient, UpdateInboundClient, DelInboundClient, DelInboundClientByEmail, checkEmailsExistForClients, SetClientTelegramUserID, checkIsEnabledByEmail, ToggleClientEnableByEmail, SetClientEnableByEmail, ResetClientIpLimitByEmail, ResetClientExpiryTimeByEmail, ResetClientTrafficLimitByEmail. Each method now takes an explicit *InboundService for the helpers that legitimately stay on InboundService (GetInbound, GetClients, runtimeFor, AddClientStat / UpdateClientStat / DelClientStat, DelClientIPs / UpdateClientIPs, emailUsedByOtherInbounds, getAllEmailSubIDs, GetClientInboundByEmail / GetClientInboundByTrafficID, GetClientTrafficByEmail). Stays on InboundService: ResetClientTrafficByEmail and ResetClientTraffic(id, email) — these mutate xray_client_traffic rows, not client identity, so they're inbound-side bookkeeping. Callers updated: tgbot (6 calls), ldap_sync_job (1 call), InboundService internal (writeBackClientSubID, CopyInboundClients, AddInbound's email-uniqueness check), ClientService Create/Update/ Delete/Attach/Detach. Also removes a dead resetAllClientTraffics controller handler whose route was already gone after the previous /clients API migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(clients): finish migrating to ClientService + tidy IP routes Two related cleanups in the new /clients surface: 1. Move ResetAllClientTraffics (bulk-reset of xray_client_traffic + last_traffic_reset_time, with node-runtime propagation) from InboundService to ClientService. PeriodicTrafficResetJob now holds a clientService and calls j.clientService.ResetAllClientTraffics(&j.inboundService, id). The last client-mutation method on InboundService is gone. 2. Shorten redundantly-named routes/handlers under /panel/api/clients: - /clientIps/:email -> /ips/:email (handler getIps) - /clearClientIps/:email -> /clearIps/:email (handler clearIps) The "client" prefix was redundant inside the clients namespace. Frontend (InboundInfoModal) and api-docs updated to match. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(inbounds,clients): clean up inbound modal + enrich client modal Inbound modal rework (InboundFormModal.vue + inbound.js): - Drop the embedded Client subform in the Protocol tab. Multi-inbound clients are managed exclusively from the Clients page now; a fresh inbound is created with zero clients (settings constructors default to []) and the user attaches clients afterwards. - Hide the Protocol tab entirely when it has nothing to render (VMESS, Trojan without fallbacks, Hysteria). Auto-switches active tab to Basic when the tab disappears while focused. - Move the Security section (Security selector + TLS block with certs and ECH + Reality block) out of the Stream tab into its own Security tab, sharing the canEnableStream gate. Client modal additions (ClientFormModal.vue + ClientBulkAddModal.vue): - Flow select (xtls-rprx-vision / -udp443) appears only when the panel actually has a Vision-capable inbound (VLESS or PortFallback on TCP with TLS or Reality). Hidden otherwise, and cleared when it disappears. - IP Limit input is disabled when the panel-level ipLimitEnable setting is off, fetched into useClients alongside subSettings and threaded through ClientsPage to both modals. - Edit modal now shows an "IP Log" section listing IPs that have connected with the client's credentials, with refresh and clear buttons (calls the renamed /panel/api/clients/ips and /clearIps endpoints). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(inbounds): drop manual Fallbacks UI from inbound modal The PortFallback protocol type now covers the common VLESS-master-plus-children case with auto-wired dests, so the manual Fallbacks editor (showFallbacks block in the Protocol tab) is mostly redundant. Removed: - the v-if="showFallbacks" template block (SNI/ALPN/Path/dest/PROXY rows) - the showFallbacks computed - the addFallback / delFallback helpers - the .fallbacks-header / .fallbacks-title styles - the showFallbacks gate from hasProtocolTabContent (so Trojan-over-TCP no longer shows an empty Protocol tab) Power users who need a non-inbound fallback dest (nginx, static site) can still author settings.fallbacks via the Advanced JSON tab. * feat(clients,inbounds): move search/filter to Clients page + small fixes Search/filter relocation: - Remove the search/filter toolbar (search switch + filter radio + protocol/node selects + the visibleInbounds projection + inboundsFilterState localStorage + filter CSS + the SearchOutlined/ FilterOutlined/ObjectUtil/Inbound imports it required) from InboundList. The filters were all client-oriented buckets bolted onto the inbound row. - Add a search/filter toolbar to ClientsPage with the same shape: switch between deep-text search and bucket filter (active / deactive / depleted / expiring / online) + protocol filter that matches clients attached to at least one inbound with the chosen protocol. State persists in clientsFilterState localStorage. filteredClients drives both the desktop table and the mobile card list, and select-all / allSelected / someSelected only span the visible subset. - useClients now also fetches expireDiff and trafficDiff from /panel/setting/defaultSettings (used to detect the expiring bucket); ClientsPage threads them into the client-bucket helper. Loose fixes folded in: - Add Client: email field is auto-filled with a random handle on open, matching uuid/subId/password/auth. - Inbound clone: parse and reuse the source settings JSON (with clients reset to []) instead of building a fresh defaulted Settings, so VLESS Encryption/Decryption and other non-client fields survive the clone. - en-US.json: add the ipLog string used by the edit-client modal. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): add Reverse tag field for VLESS-attached clients Mirrors the Flow field's pattern: a Reverse tag input appears in the Add/Edit Client modal whenever at least one selected inbound is VLESS or PortFallback. The value rides over the wire as client.reverse = { tag: '...' } so it lands directly in model.Client's *ClientReverse field; an empty value omits the reverse key entirely. On edit the field is hydrated from props.client.reverse?.tag, and the showReverseTag watcher clears the field if the user drops the last VLESS-like inbound from the selection. * fix(xray): emit only protocol-relevant fields per client entry The Xray config synthesizer was writing every identifier field (id, password, flow, auth, security/method, reverse) on every client entry regardless of the inbound's protocol. Xray ignores unknown fields, so the config worked, but it diverged from the spec and leaked secrets across protocols when one client was attached to multiple inbounds — a VLESS inbound's generated config carried the same client's Trojan password and Hysteria auth alongside its uuid. Switch on inbound.Protocol when building each entry: - VLESS / PortFallback: id, flow, reverse - VMess: id, security - Trojan: password, flow - Shadowsocks: password, method - Hysteria / Hysteria2: auth email is emitted for every protocol. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): restore auto-disable kick under new schema disableInvalidClients still resolved (inbound_tag, email) pairs via JSON_EACH(inbounds.settings.clients), which is empty after migrating to the clients + client_inbounds tables. Result: xrayApi.RemoveUser never ran for depleted clients, clients.enable stayed true so the UI showed them as active, and only xray_client_traffic.enable got flipped - making "Restart Xray After Auto Disable" only half-work. Resolve the targets via a JOIN through the new schema, flip clients.enable so the Clients page reflects the state, and drop the legacy JSON write-back plus the subId cascade workaround (email is unique now). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): live WebSocket updates + Ended status surfacing ClientsPage now subscribes to traffic / client_stats / invalidate WebSocket events instead of polling /onlines every 10s. Per-row traffic counters refresh in place, online state stays current, and list-level mutations elsewhere trigger a refresh. The client roll-up summary moves from InboundsPage to ClientsPage where it belongs, restructured into six labeled stat tiles (Total / Online / Ended / Expiring / Disabled / Active) with email popovers on the ones with issues. Auto-disabled clients (traffic exhausted or expiry passed) now classify as 'depleted' even though clients.enable=false, so they show up under the Ended filter and render a red Ended tag instead of looking indistinguishable from an operator-disabled row. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(nodes): per-node client roll-up and panel version Added transient inboundCount / clientCount / onlineCount / depletedCount fields to model.Node, populated by NodeService.GetAll via aggregated queries (one join across inbounds + client_inbounds, one over client_traffics intersected with the in-memory online emails). The Nodes list renders these as colored chips on a new "Clients" column so an operator can see at a glance how many users each node carries and how many are currently online or depleted. Also exposes the remote panel's version. The central panel adds panelVersion to its /api/server/status payload (sourced from config.GetVersion). Probe reads that field and persists it on the node row, mirroring how xrayVersion already flows. NodesPage gets a new column next to Xray Version, in both desktop and mobile views, with English and Persian strings. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): stop node sync from resurrecting deleted clients Several related issues around node-managed clients: - Remote runtime: drop the per-inbound resetAllClientTraffics path and point traffic/onlines/lastOnline fetches at the new /panel/api/clients/* routes. - Delete from master: always push the updated inbound to the node even when the client was already disabled or depleted, so the node actually loses the user instead of silently keeping it. - setRemoteTraffic: mirror remote clients into the central tables only on first discovery of a node inbound. Matched inbounds let the master own the join table, so a stale snap can no longer re-create a ClientRecord (and join row) for a client that was just deleted on the master. - ClientService.Delete: route through submitTrafficWrite so deletes serialize with node traffic merges, and switch the final ClientRecord delete to an explicit Where("id = ?") clause. - setRemoteTraffic UNIQUE-constraint fix: use clause.OnConflict on inserts and email-keyed UPDATEs for client_traffics, so mirroring a snap doesn't trip the unique email index. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(clients): switch client API endpoints from id to email All client-scoped routes now use the unique email as the path key (get, update, del, attach, detach, links). Email is the stable, protocol-independent identifier — UUIDs don't exist for trojan or shadowsocks, and internal numeric ids leaked panel implementation detail into the public API. Removed the redundant /traffic/byId/:id endpoint (covered by /traffic/:email) and collapsed /links/:id/:email into /links/:email, which now returns links across every attached inbound for the client. Frontend selection, bulk delete, and toggle state are now keyed by email as well, dropping the id→email lookup workaround. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(server): move cached state and helpers into ServerService ServerController had grown to hold its own status cache, version-list TTL cache, history-bucket whitelist, and the loop that drove all three — concerns that belong in the service layer. Pull them out: - lastStatus + the @2s refresh become ServerService.RefreshStatus and ServerService.LastStatus; the controller's cron now just orchestrates the cross-service side effects (xrayMetrics sample, websocket broadcast). - The 15-minute Xray-versions cache (with stale-on-error fallback) moves into ServerService.GetXrayVersionsCached, collapsing the controller handler to a single call. - The freedom/blackhole outbound-tag walk used by /xraylogs becomes ServerService.GetDefaultLogOutboundTags. - The allowed-history-bucket whitelist moves to package-level service.IsAllowedHistoryBucket, so both NodeController and ServerController validate against the same list. Net result: web/controller/server.go drops from 458 to 365 lines and contains only HTTP wiring + presentation-y side effects. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(api): emit JSON-text columns as nested objects Inbound, ClientRecord, and InboundClientIps store settings / streamSettings / sniffing / reverse / ips as JSON-text in the DB. The API was passing that text through verbatim, so every consumer had to JSON.parse a string inside a string. Add MarshalJSON / UnmarshalJSON so the wire format is a real nested object, while still accepting the legacy escaped-string shape on write. Frontend dbinbound.js gets a matching coerceInboundJsonField helper for the same dual-shape read path, and inbound.js toJson stops emitting empty/placeholder fields (externalProxy [], sniffing destOverride when disabled, etc.) so the new normalised JSON stays terse. api-docs and the inbound-clone path are updated to the new shape. Controller route lists are regrouped so all GETs sit above POSTs. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): include inboundIds and traffic in /clients/list ClientRecord got its own MarshalJSON in the previous commit, and ClientWithAttachments embeds it to add inboundIds and traffic. Go promotes the embedded MarshalJSON to the outer struct, so the encoder was calling ClientRecord.MarshalJSON for the whole value and silently dropping the extras. The frontend reads row.inboundIds / row.traffic from /clients/list, so attached inbounds didn't render and newly added clients looked like they hadn't saved. Add an explicit MarshalJSON on ClientWithAttachments that splices the extras in. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): gate IP Log on ipLimitEnable + clean access-log dropdown Legacy panel hid the IP Log section when access logging was off; the Vue 3 migration left it gated on isEdit only, so the section showed even when xray's access log was 'none' and nothing was being recorded. Restore the ipLimitEnable gate on the edit modal's IP Log form-item. While here, clean up the Xray Settings access-log dropdown: previously two 'none' entries appeared (an empty value labelled with t('none') and the literal 'none' from the options array). Drop the empty option for access log (the literal 'none' covers it) and relabel the empty option for error log / mask address to t('empty') so they're distinguishable. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(nodes): route per-client ops through node clients API + orphan sweep Adds Runtime methods AddClient, UpdateUser, and DeleteUser so master mutates clients on a node via /panel/api/clients/{add,update,del} rather than pushing the whole inbound. The previous rt.UpdateInbound path made the node DelInbound+AddInbound on every single-client change, briefly cycling every other user on the same inbound. DelInbound no longer filters by enable=true, so a disabled node inbound actually gets removed from the node instead of being resurrected by the next snap. setRemoteTrafficLocked now sweeps any ClientRecord with zero ClientInbound rows after SyncInbound rebuilds the attachments, which is how a node-side delete propagates back to master instead of leaving a detached ghost. ClientService.Delete tombstones the email first so a snap arriving mid-delete can't re-create the record. WebSocket broadcasts an "invalidate(clients)" message on every client mutation so the Clients page refreshes without manual reload. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(balancers): allow fallback on all strategies + feed burstObservatory from random/roundRobin Drops the random/roundRobin gate on the Fallback field in BalancerFormModal so every strategy can pick a fallback outbound. syncObservatories now feeds burstObservatory from leastLoad + random + roundRobin balancers (was leastLoad only), matching how leastPing feeds observatory. Fix the JsonEditor "Unexpected end of JSON input" that appeared when switching a balancer between leastPing and another strategy: the obsView watcher was gated on showObsEditor (a boolean OR of the two flags) and missed the case where one observatory swapped for the other in the same tick. Watch the individual flags instead so obsView flips to the surviving editor and the getter stops pointing at a deleted key. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(inbounds): use sortedInbounds for mobile empty-state check InboundList referenced an undefined visibleInbounds in the mobile card list's empty-state guard, throwing "Cannot read properties of undefined (reading 'length')" and breaking the entire mobile render. * feat(clients): sortable table columns Adds the same sortState / sortableCol / sortFns pattern InboundList uses, wrapping filteredClients in sortedClients so sort composes with the existing search/filter pipeline. Sortable: enable, email, inboundIds (attachment count), traffic, remaining, expiryTime; actions and online stay unsorted. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(shadowsocks): generate valid ss2022 keys and per-client method for legacy ciphers The Add Client flow on shadowsocks inbounds was producing xray configs that failed to start: - 2022-blake3-* ciphers need a base64-encoded key of an exact byte length per cipher. fillProtocolDefaults was assigning a uuid-style string, which xray rejects as "bad key". Now the password is generated (or replaced if invalid) via random.Base64Bytes(n) sized to the chosen cipher. - Legacy ciphers (aes-256-gcm, chacha20-*, xchacha20-*) require a per-client method field in multi-user mode; model.Client has no Method, so settings.clients was stored without one and xray failed with "unsupported cipher method:". applyShadowsocksClientMethod now injects the top-level method into each client on add/update, and healShadowsocksClientMethods backfills it at xray-config-build time so existing inbounds heal on the next start. - xray/api.go ssCipherType switch was missing aes-256-gcm, which fell through to ss2022 path. - SSMethods dropdown now offers aes-256-gcm. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): preserve ClientRecord on inbound delete + filter Attached inbounds to multi-client protocols Replace the global orphan sweep in setRemoteTrafficLocked with a per-inbound diff cleanup: only delete a ClientRecord whose email disappeared from a snap-tracked inbound (i.e. a node-side delete). Inbounds that vanished entirely from the snap (e.g. admin deleted the inbound on master) aren't iterated, so a client whose last attachment came from that inbound is now left alone instead of being deleted alongside the inbound. ClientFormModal and ClientBulkAddModal now filter the Attached inbounds dropdown to protocols that actually support multiple clients: shadowsocks, vless, vmess, trojan, hysteria, hysteria2, and portfallback (which routes through VLESS settings). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): make empty-state text readable on dark/ultra themes The "No clients yet" empty state had a hardcoded black color (rgba(0,0,0,0.45)) that vanished against the dark backgrounds. Drop the inline color, let it inherit from the AntD theme, and fade with opacity like the mobile card empty state already does. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): client-first tgbot add flow, tgId field, lightweight inbound options - tgbot: drop legacy per-protocol Add Client UI in favour of a client-first multi-inbound flow. New BuildClientDraftMessage / getInboundsAttachPicker let an admin pick one or more inbounds and submit a single client; per- protocol secrets are now generated server-side via fillProtocolDefaults. Drops awaiting_id/awaiting_password_tr/awaiting_password_sh state cases and add_client_ch_default_id/pass_tr/pass_sh/flow callbacks. Adds a setTGUser button + awaiting_tg_id state so the bot can set Client.TgID during Add. - clients UI: add Telegram user ID input to ClientFormModal (0 = none). Hide IP Limit field entirely when ipLimitEnable is off — disabled fields still take layout space, this collapses Auth(Hysteria) to full width. - inbounds API: new GET /panel/api/inbounds/options that returns just {id, remark, protocol, port, tlsFlowCapable}. Used by the clients page pickers so the dropdown payload stays small on panels with thousands of clients (drops settings JSON, clientStats, streamSettings). Server-side TlsFlowCapable mirrors Inbound.canEnableTlsFlow so the modal no longer needs to parse streamSettings client-side. - clientInfoMsg now shows attached inbound remarks, and getInboundUsages reports the attached client count per inbound. - api-docs: document the new /options endpoint and add tgId / flow to the clients add/update bodies. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(inbounds): keep Node column visible for node-attached inbounds The Node column was bound to hasActiveNode, so disabling every node hid the column even when inbounds were still attached to those nodes — the admin lost the visual cue that those inbounds belonged to a node and would come back when it was re-enabled. Combine hasActiveNode with a new hasNodeAttachedInbound check (any dbInbound with nodeId != null) so the column survives node-disable. * fix(api-docs): accept functional-component icons in EndpointSection AntD-Vue icons (SafetyCertificateOutlined, etc.) are functional components, so the icon prop's type: Object validator was rejecting them with a "Expected Object, got Function" warning at runtime. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test: cover crypto, random, netsafe, sub helpers, xray equals, websocket hub, node service Adds ~110 unit tests across previously untested packages. Focus on pure-logic and concurrency surfaces where regressions would silently affect users: - util/crypto, util/random: password hashing round-trip, ss2022 key generation, alphabet/length invariants. - util/netsafe: IsBlockedIP edge cases, NormalizeHost validation, SSRF guard with AllowPrivate context bypass. - util/common, util/json_util: traffic formatter, Combine nil-skip, RawMessage empty-as-null and copy-on-unmarshal. - sub: splitLinkLines, searchKey/searchHost, kcp share fields, finalmask normalization, buildVmessLink round-trip. - xray: Config.Equals and InboundConfig.Equals field-by-field, getRequiredUserString/getOptionalUserString type checks. - web/websocket: hub registration, throttling, slow-client eviction, nil-receiver safety, concurrent register/unregister. - web/service: NodeService.normalize validation, normalizeBasePath, HeartbeatPatch.ToUI mapping. - web/job: atomicBool concurrent set/takeAndReset semantics. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * i18n(clients): replace English fallbacks with proper translation keys Pulls every hard-coded English label/title in the Clients page and its four modals through the i18n layer so localized panels stop leaking English. New keys live under pages.clients (auth, hysteriaAuth, uuid, flow, flowNone, reverseTag, reverseTagPlaceholder, telegramId, telegramIdPlaceholder, created, updated, ipLimit) plus refresh at the root and toasts.bulkDeletedMixed / bulkCreatedMixed for partial-failure toasts. Also switches the add-client modal's primary button from "Add" to "Create" for consistency with other create flows. The bulk-add Random/Random+Prefix/... email-method options stay hard-coded by request - they're identifier-shaped strings. * i18n: backfill 99 missing keys across all 12 non-English locales Brings every translation file up to parity with en-US.json so the Clients page, the fallback-children inbound section, the new refresh verb, the Nodes panel-version label and a handful of older holes stop falling through to the English fallback. New strings span: - pages.clients.* (labels, confirmations, toasts, emailMethods) - pages.inbounds.portFallback.* (Reality fallback inbound section) - pages.nodes.panelVersion, menu.clients, refresh Technical identifiers (Auth, UUID, Flow, Reverse tag) are intentionally left untranslated since they correspond to xray-core field names. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * i18n: drop stale pages.client block duplicated in every non-English locale Every non-English locale carried a pages.client (singular) section with 30 entries that duplicated pages.clients (plural). The plural namespace is what the Vue code actually consumes; the singular one was dead weight from an older rename that never got cleaned up in the non-English files. Removing it brings every locale to exactly 984 keys, matching en-US.json. * chore: apply modernize analyzer fixes across codebase Mechanical replacements suggested by golang.org/x/tools/.../modernize: strings.Cut/CutPrefix/SplitSeq, slices.Contains, maps.Copy, min(), range-over-int, new(expr), strings.Builder for hot += loops, reflect.TypeFor[T](), sync.WaitGroup.Go(), drop legacy //+build lines. * feat(database): add PostgreSQL as an optional backend alongside SQLite Lets operators with large client counts or multi-node setups pick PostgreSQL at install time without breaking the existing SQLite default. Backend is selected at runtime via XUI_DB_TYPE/XUI_DB_DSN, a small dialect layer keeps the five JSON_EXTRACT/JSON_EACH queries portable, and a new `x-ui migrate-db` subcommand copies SQLite data into PostgreSQL in FK-aware order. * fix(inbounds): gate node selector to multi-node-capable protocols Hide the Deploy-To selector and clear nodeId when switching to a protocol that can't run on a remote node. Also: - subs: return 404 (not 400) when subId matches no inbounds, so VPN clients distinguish "deleted/unknown" from a server error - hysteria link gen: use the inbound's resolved address so node-managed inbounds advertise the node host instead of the central panel - shadowsocks: default network to 'tcp' (udp was causing issues for some clients on first-create) - vite dev proxy: rewrite migrated-route bypass against the live base path instead of a hardcoded single-segment regex Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): bulk add/delete correctness + perf, working pagination, delayed-start in form Bulk add/delete were serial on the frontend (one toast per call, N round-trips) and the backend race exposed by parallelizing them lost client attachments and hit UNIQUE constraint failed on client_inbounds. The single add/edit modal also had no Start-After-First-Use option, and the table never showed the delayed duration. Backend (web/service/client.go): - Per-inbound mutex on Add/Update/Del InboundClient so concurrent writers on the same inbound don't lose the read-modify-write of settings JSON. - SyncInbound skips create+join when the email is tombstoned so a concurrent maintenance pass (adjustTraffics, autoRenewClients, markClientsDisabledIn- Settings) that did a stale RMW can't resurrect a just-deleted client with a fresh id. - compactOrphans sweeps settings.clients entries whose ClientRecord no longer exists, applied in Add/DelInboundClient + DelInboundClientByEmail so each user-initiated mutation self-heals the inbound's settings. - DelInboundClient uses Pluck instead of First for the stats lookup so a missing row doesn't abort the delete with a noisy ErrRecordNotFound log. Frontend: - HttpUtil.{get,post} accept a silent option that suppresses the auto-toast. - ClientBulkAddModal fires creates in parallel + silent + one summary toast. - useClients.removeMany runs deletes in parallel + silent and refreshes once; ClientsPage bulk delete uses it and shows one aggregate toast. - useClients.applyInvalidate debounces 200 ms so the burst of N WebSocket invalidate events from the backend collapses into a single refresh. - ClientsPage pagination is reactive (paginationState ref + tablePagination computed); onTableChange persists page-size and page changes. - ClientFormModal gains a Start-After-First-Use switch + Duration days input alongside the existing Expiry Date picker; on edit-mode open a negative expiryTime is decoded back to delayed mode + days; on submit the payload sends -86400000 * days or the absolute timestamp. - ClientsPage table shows the delayed-start duration (blue tag Nd, tooltip Start After First Use: Nd) instead of infinity. - Telegram ID field in the form is hidden when /panel/setting/defaultSettings reports tgBotEnable=false; Comment then fills the row. - Form row 3 collapses UUID (span 12) + Total GB (span 8) + Limit IP (span 4) when ipLimitEnable is on, else UUID + Total GB at 12/12. - useInbounds.rollupClients counts only clients with a matching clientStats row, so orphans in settings.clients no longer inflate the inbound's count. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(windows): clean shutdown, working panel restart, harden kernel32 load Three Windows-specific issues addressed: 1. Orphaned xray-windows-amd64 after VS Code debugger stop. Delve's "Stop" sends TerminateProcess to the Go binary, which is uncatchable — our signal handlers never run, so xrayService.StopXray() is skipped and xray is left dangling. Spawn xray as a child of a Job Object with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE so the OS kills xray when our handle to the job is closed (which happens even on TerminateProcess). Also trap os.Interrupt in main so Ctrl+C in the terminal runs the graceful path. 2. /panel/setting/restartPanel logged "failed to send SIGHUP signal: not supported by windows" because Windows can't deliver arbitrary signals. Add a restart hook in web/global; main registers it to push SIGHUP into its own signal channel, and RestartPanel calls the hook before falling back to the (Unix-only) signal path. Same restart-loop code runs in both cases. 3. util/sys/sys_windows.go now uses windows.NewLazySystemDLL so the kernel32.dll resolve is pinned to %SystemRoot%\System32 (prevents DLL hijacking by a planted DLL next to the binary). Local filetime type replaced with windows.Filetime, and the unreliable syscall.GetLastError() fallback replaced with a type assertion on the errno captured at call time. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(sys): correct CPU/connection accounting on linux + darwin util/sys/sys_linux.go: - GetTCPCount/GetUDPCount were counting the column header row in /proc/net/{tcp,udp}[6] as a connection, inflating the reported total by 1 per non-empty file (so the panel status line always showed 2 more connections than actually existed). Replace getLinesNum + safeGetLinesNum with a single bufio.Scanner-based countConnections that skips the header. - CPUPercentRaw now opens HostProc("stat") instead of a hardcoded /proc/stat so HOST_PROC overrides apply, matching the connection counters in the same file. - Simplify CPU field unpacking: pad nums to 8 once instead of guarding every assignment with a len check. util/sys/sys_darwin.go: - Fix swapped idle/intr indices on kern.cp_time. BSD CPUSTATES order is user, nice, sys, intr, idle (CP_INTR=3, CP_IDLE=4) — gopsutil's cpu_darwin_nocgo.go reads the same layout. The previous code used out[3] as idle and out[4] as intr, so busy = total - dIdle was actually subtracting interrupt time, making the panel report CPU usage close to 100% on macOS regardless of actual load. - Collapse the per-field delta math into a single loop. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(xray): rotate crash reports into log folder, prevent overwrites writeCrashReport had two flaws: it wrote to the bin folder (alongside the xray binary) which conflates artifacts, and the second-precision timestamp meant a tight restart-loop crash burst overwrote prior reports. Write to the log folder with nanosecond precision and keep the last 10 reports. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * revert(inbounds): drop unreleased portfallback protocol The Port-with-Fallback inbound (commit 62fd9f9d) was confusing as a standalone protocol — fallbacks belong on a regular VLESS/Trojan TCP-TLS inbound, the way Xray models them natively. Rip out the entire feature cleanly (no migration needed since it was never released): protocol constant, fallback children DB table, FallbackService, 2 API endpoints, all UI rows, related translations and api-docs. A native fallback flow attached to VLESS/Trojan TCP-TLS/Reality will land in a follow-up commit. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(inbounds): native fallbacks on VLESS/Trojan TCP-TLS, with working child links A VLESS or Trojan inbound on TCP with TLS or Reality can now act as a fallback master: pick existing inbounds as children and the panel auto- fills the SNI / ALPN / path / xver routing fields from each child's transport, auto-builds settings.fallbacks at config-gen time, and rewrites the child's client-share link so it advertises the master's reachable endpoint and TLS state instead of the child's loopback listen. Layout matches the Xray All-in-One Nginx example: master at :443 with clients + TLS, each child on 127.0.0.1 with its own transport+clients. Order matters (Xray walks fallbacks top-to-bottom) — reorder via the per-row up/down arrows. Path / SNI / ALPN are exposed under a per-row Edit toggle for the rare cases where the auto-derivation needs overriding; otherwise just pick a child and you're done. Backend: new InboundFallback table + FallbackService (GetByMaster / SetByMaster / GetParentForChild / BuildFallbacksJSON); two routes (GET / POST /panel/api/inbounds/:id/fallbacks); xray.GetXrayConfig injects settings.fallbacks for any VLESS/Trojan TCP-TLS/Reality inbound; GetInbounds annotates each child with FallbackParent so the frontend can rewrite links without an extra round-trip. Link projection covers every emission path — clients-page QR/links, per-inbound Get URL, raw subscription, sub-JSON, sub-Clash, and the inbounds-page link/info/QR — via a shared projectThroughFallbackMaster on the backend and a shared projectChildThroughMaster on the frontend that both handle the panel-tracked relationship and the legacy unix-socket (@vless-ws) convention. Strings translated into all 12 non-English locales. * docs: rewrite CONTRIBUTING with full local-dev setup The prior three-line CONTRIBUTING left newcomers guessing at every non-trivial step: which Go / Node versions, where xray comes from, why the panel goes blank when XUI_DEBUG=true is flipped on, how the Vue multi-page setup is wired, what to do on Windows when go build trips on the CGo SQLite driver. Now covers prerequisites, MinGW-w64 install on Windows (niXman builds or MSYS2), one-shot first-time setup, two frontend dev workflows with the XUI_DEBUG asset-cache gotcha called out, the architecture and conventions of the Vue side, a project-layout map, useful env vars, and the PR checklist. ---------
2026-05-19 10:16:42 +00:00
for part := range strings.SplitSeq(xff, ",") {
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 <ho3ein.sanaei@gmail.com>
2026-05-13 10:52:52 +00:00
if ip, ok := extractTrustedIP(part); ok {
return ip
}
}
}
}
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 <ho3ein.sanaei@gmail.com>
2026-05-13 10:52:52 +00:00
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
}
trusted := trustedProxyCIDRs()
Feat/multi inbound clients (#4469) * feat(clients): add shadow tables for first-class client promotion Introduces three new GORM-backed tables (clients, client_inbounds, inbound_fallback_children) and a populate-only seeder that backfills them from each inbound's existing settings.clients JSON. Duplicate emails across inbounds auto-merge under one client row, with each field conflict logged. Existing services are unchanged and continue reading from settings.clients — this commit is groundwork only. * feat(clients): make clients+client_inbounds the runtime source of truth Adds ClientService.SyncInbound that reconciles the new tables from each inbound's clients list whenever existing service paths mutate settings.clients. Wires it into AddInbound, UpdateInbound, AddInboundClient, UpdateInboundClient, DelInboundClient, DelInboundClientByEmail, DelDepletedClients, autoRenewClients, and the timestamp-backfill path in adjustTraffics, plus DetachInbound on DelInbound. GetXrayConfig now builds settings.clients from the new tables before writing config.json, and getInboundsBySubId joins through them instead of JSON_EACH on settings JSON. Live Xray config and subscription endpoints are now driven by the relational view; settings.clients JSON stays in step as a side effect of every write. * feat(clients): add top-level Clients tab and CRUD API Adds /panel/api/clients endpoints (list, get, add, update, del, attach, detach) backed by ClientService methods that orchestrate the per-inbound Add/Update/Del flows so a single client row is created once and attached to many inbounds in one operation. The frontend gains a dedicated Clients page (frontend/clients.html + src/pages/clients/) with an AntD table, multi-inbound attach modal, and full CRUD. Axios interceptor learns to honour Content-Type: application/json so the JSON endpoints work alongside the legacy form-encoded ones. The legacy per-inbound client modal stays untouched in this PR — both flows now write to the same source of truth. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(inbounds): add Port-with-Fallback inbound type Adds a new "portfallback" protocol that emits as a VLESS-TLS inbound under the hood but is paired with a sidecar table of child inbounds. Panel auto-builds settings.fallbacks at Xray-config-gen time from the sidecar — each child's listen+port becomes the fallback dest, with SNI/ALPN/path/xver match criteria pulled from the row. No more typing loopback ports by hand or keeping settings.fallbacks in sync. Backend: new FallbackService (Get/SetChildren, BuildFallbacksJSON); two new routes (GET/POST /panel/api/inbounds/:id/fallbackChildren); xray.GetXrayConfig injects fallbacks for PortFallback inbounds; the inbound model emits protocol="vless" so Xray accepts the config. Frontend: PORTFALLBACK joins the protocol dropdown; selecting it shows the standard VLESS controls plus a Fallback Children table (inbound picker + per-row SNI/ALPN/path/xver). Children are loaded on edit and replaced atomically on save. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): add Reset Traffic, QR Code, Info actions + Online/Remaining columns The Clients page table gains: - Online column — green/grey tag driven by /panel/api/inbounds/onlines, polled every 10s. - Remaining column — bytes-remaining tag, coloured green/orange/red against quota, purple infinity when unlimited. - Action icons per row: QR, Info, Reset traffic, Edit, Delete. ClientInfoModal shows the full client detail (uuid/password/auth, traffic ↑/↓ + remaining + all-time, expiry absolute + relative, attached inbounds chip list, online + last-online). ClientQrModal fetches links for the client's subId via /panel/api/inbounds/getSubLinks/:subId and renders each one through the existing QrPanel component. Reset Traffic confirms then calls the existing per-inbound endpoint on the client's first attached inbound (the traffic row is keyed on email globally, so any attached inbound resets the shared counter). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): expose Attached inbounds in edit mode The multi-select was gated on add-only, so editing a client had no way to change which inbounds it belonged to. The picker now shows in both modes, and on submit the modal diffs the picked set against the original attachedIds — additions go through the /attach endpoint, removals through /detach, both after the field update lands so the new attachments get the latest values. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): unbreak template parsing + stale i18n keys - InboundFormModal: split the multi-line help string in the PortFallback section onto one line — Vue's template parser was bailing on Unterminated string constant because a single-quoted literal spanned two lines inside a {{ }} interpolation. - ClientInfoModal: t('disable') was missing at the root level, so vue-i18n returned the key path literally. Use t('disabled') which exists. - Linter cleanup elsewhere: pages.client.* references renamed to pages.clients.* to match the merged i18n block; whitespace normalisation in a few unrelated Vue templates. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * 1 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(traffic): drop all-time traffic tracking Removes the AllTime field from Inbound and ClientTraffic and migrates existing DBs by dropping the all_time columns on startup. The counter duplicated up+down without adding signal, and the per-event accumulator ran on every traffic write. Frontend: drop the All-time column from the inbound list and the client-row table, the All-time row from the client info modal, and the All-Time Total Usage tile from the inbounds summary card. The allTimeTraffic/allTimeTrafficUsage i18n keys are removed across every locale. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): mobile cards, multi-select, bulk add Adds the same row-card layout the inbounds page uses on mobile: the table is suppressed under the mobile breakpoint and each client renders as a compact card with a status dot, email, Info button, Enable switch, and overflow menu. All the per-client detail (traffic, remaining, expiry, attached inbounds, flow, created/updated, URL, subscription) opens through the existing info modal. Multi-select with bulk delete wires AntD row-selection on desktop and a per-card checkbox on mobile; a Delete (N) button appears in the toolbar when anything is selected. Bulk add reuses the five email-generation modes from the inbound bulk modal but takes a multi-inbound picker so one bulk run can attach to several inbounds at once. Submits client-by-client through the existing /panel/api/clients/add endpoint. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(inbounds): remove legacy per-inbound client UI Now that clients live as first-class rows attached to one or many inbounds, the per-inbound client UI on the inbounds page is dead weight — every client action either has a global equivalent on the Clients page or makes no sense in a many-to-many world. Deletes ClientFormModal, ClientBulkModal, CopyClientsModal, and ClientRowTable from inbounds/. Strips the matching emits, refs, handlers, and dropdown menu items from InboundList and InboundsPage, and removes the dead mobile expand-chevron state and the desktop expanded-row plumbing that drove the inline client table. The InboundFormModal Clients tab still works in add-mode (one inline client at inbound creation) — that flow goes through ClientService. SyncInbound on save and remains useful. Fixes a stray "</a-dropdown>" left over by an earlier toolbar edit in ClientsPage that broke the template parser. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): add Delete depleted action Mirrors the legacy delDepletedClients action that lived under the inbounds page, but as a first-class /panel/api/clients/delDepleted endpoint backed by ClientService. The new path goes through ClientService.Delete for each depleted email, so the new clients + client_inbounds + xray_client_traffic tables stay consistent. Adds a danger-styled toolbar button on the Clients page (next to Reset all client traffic) with a confirm dialog and a toast reporting the deleted count. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(api): move every client-shaped endpoint off /inbounds onto /clients After the multi-inbound client migration, client state belongs to the client API surface, not the inbound one. Twelve routes that were crammed under /panel/api/inbounds/* now live where they belong, under /panel/api/clients/*. Moved (route, handler, doc): POST /clientIps/:email POST /clearClientIps/:email POST /onlines POST /lastOnline POST /updateClientTraffic/:email POST /resetAllClientTraffics/:id POST /delDepletedClients/:id POST /:id/resetClientTraffic/:email GET /getClientTraffics/:email GET /getClientTrafficsById/:id GET /getSubLinks/:subId GET /getClientLinks/:id/:email Their /clients/* counterparts are: POST /clients/clientIps/:email POST /clients/clearClientIps/:email POST /clients/onlines POST /clients/lastOnline POST /clients/updateTraffic/:email POST /clients/resetTraffic/:email (email-only, fans out) GET /clients/traffic/:email GET /clients/traffic/byId/:id GET /clients/subLinks/:subId GET /clients/links/:id/:email per-inbound resetAllClientTraffics and delDepletedClients are dropped entirely — the Clients page already exposes global Reset All Traffic and Delete depleted actions, and per-inbound resets are meaningless once a client can be attached to many inbounds. ClientService.ResetTrafficByEmail is the new email-only reset path: it looks up every inbound the client is attached to and pushes the counter reset + Xray re-add through inboundService.ResetClientTraffic for each one, so depleted users come back online instantly. Frontend callers (ClientsPage, useClients, ClientQrModal, ClientInfoModal, InboundInfoModal, InboundsPage, useInbounds) all switched to the new paths. The Inbounds page drops its per-inbound "Reset client traffic" and "Delete depleted clients" dropdown items — users do those at the client level now. api-docs is rebuilt to match. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(service): switch tgbot + ldap callers to ClientService Adds two thin helpers to ClientService (CreateOne, DetachByEmail) and rewrites tgbot.SubmitAddClient and ldap_sync_job to call ClientService directly. Removes the JSON-blob payloads (BuildJSONForProtocol output for add, clientsToJSON/clientToJSON helpers) that callers previously fed to InboundService.AddInboundClient/DelInboundClient. ldap_sync_job.batchSetEnable now loops InboundService.SetClientEnableByEmail per email instead of trying to coerce AddInboundClient into doing the update — the old path would have failed duplicate-email validation for existing clients anyway. The legacy InboundService.AddInboundClient/UpdateInboundClient/ DelInboundClient methods stay in place; they are now only used internally by ClientService Create/Update/Delete/Attach. Inlining + deleting them follows in a separate commit. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(service): move all client mutation methods to ClientService Moves the client mutation surface out of InboundService and into ClientService. These methods all operate on a single client (identity fields, traffic limits, expiry, ip limit, enable state, telegram tg id) and didn't belong on the inbound aggregate. Moved (12 methods): AddInboundClient, UpdateInboundClient, DelInboundClient, DelInboundClientByEmail, checkEmailsExistForClients, SetClientTelegramUserID, checkIsEnabledByEmail, ToggleClientEnableByEmail, SetClientEnableByEmail, ResetClientIpLimitByEmail, ResetClientExpiryTimeByEmail, ResetClientTrafficLimitByEmail. Each method now takes an explicit *InboundService for the helpers that legitimately stay on InboundService (GetInbound, GetClients, runtimeFor, AddClientStat / UpdateClientStat / DelClientStat, DelClientIPs / UpdateClientIPs, emailUsedByOtherInbounds, getAllEmailSubIDs, GetClientInboundByEmail / GetClientInboundByTrafficID, GetClientTrafficByEmail). Stays on InboundService: ResetClientTrafficByEmail and ResetClientTraffic(id, email) — these mutate xray_client_traffic rows, not client identity, so they're inbound-side bookkeeping. Callers updated: tgbot (6 calls), ldap_sync_job (1 call), InboundService internal (writeBackClientSubID, CopyInboundClients, AddInbound's email-uniqueness check), ClientService Create/Update/ Delete/Attach/Detach. Also removes a dead resetAllClientTraffics controller handler whose route was already gone after the previous /clients API migration. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(clients): finish migrating to ClientService + tidy IP routes Two related cleanups in the new /clients surface: 1. Move ResetAllClientTraffics (bulk-reset of xray_client_traffic + last_traffic_reset_time, with node-runtime propagation) from InboundService to ClientService. PeriodicTrafficResetJob now holds a clientService and calls j.clientService.ResetAllClientTraffics(&j.inboundService, id). The last client-mutation method on InboundService is gone. 2. Shorten redundantly-named routes/handlers under /panel/api/clients: - /clientIps/:email -> /ips/:email (handler getIps) - /clearClientIps/:email -> /clearIps/:email (handler clearIps) The "client" prefix was redundant inside the clients namespace. Frontend (InboundInfoModal) and api-docs updated to match. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(inbounds,clients): clean up inbound modal + enrich client modal Inbound modal rework (InboundFormModal.vue + inbound.js): - Drop the embedded Client subform in the Protocol tab. Multi-inbound clients are managed exclusively from the Clients page now; a fresh inbound is created with zero clients (settings constructors default to []) and the user attaches clients afterwards. - Hide the Protocol tab entirely when it has nothing to render (VMESS, Trojan without fallbacks, Hysteria). Auto-switches active tab to Basic when the tab disappears while focused. - Move the Security section (Security selector + TLS block with certs and ECH + Reality block) out of the Stream tab into its own Security tab, sharing the canEnableStream gate. Client modal additions (ClientFormModal.vue + ClientBulkAddModal.vue): - Flow select (xtls-rprx-vision / -udp443) appears only when the panel actually has a Vision-capable inbound (VLESS or PortFallback on TCP with TLS or Reality). Hidden otherwise, and cleared when it disappears. - IP Limit input is disabled when the panel-level ipLimitEnable setting is off, fetched into useClients alongside subSettings and threaded through ClientsPage to both modals. - Edit modal now shows an "IP Log" section listing IPs that have connected with the client's credentials, with refresh and clear buttons (calls the renamed /panel/api/clients/ips and /clearIps endpoints). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(inbounds): drop manual Fallbacks UI from inbound modal The PortFallback protocol type now covers the common VLESS-master-plus-children case with auto-wired dests, so the manual Fallbacks editor (showFallbacks block in the Protocol tab) is mostly redundant. Removed: - the v-if="showFallbacks" template block (SNI/ALPN/Path/dest/PROXY rows) - the showFallbacks computed - the addFallback / delFallback helpers - the .fallbacks-header / .fallbacks-title styles - the showFallbacks gate from hasProtocolTabContent (so Trojan-over-TCP no longer shows an empty Protocol tab) Power users who need a non-inbound fallback dest (nginx, static site) can still author settings.fallbacks via the Advanced JSON tab. * feat(clients,inbounds): move search/filter to Clients page + small fixes Search/filter relocation: - Remove the search/filter toolbar (search switch + filter radio + protocol/node selects + the visibleInbounds projection + inboundsFilterState localStorage + filter CSS + the SearchOutlined/ FilterOutlined/ObjectUtil/Inbound imports it required) from InboundList. The filters were all client-oriented buckets bolted onto the inbound row. - Add a search/filter toolbar to ClientsPage with the same shape: switch between deep-text search and bucket filter (active / deactive / depleted / expiring / online) + protocol filter that matches clients attached to at least one inbound with the chosen protocol. State persists in clientsFilterState localStorage. filteredClients drives both the desktop table and the mobile card list, and select-all / allSelected / someSelected only span the visible subset. - useClients now also fetches expireDiff and trafficDiff from /panel/setting/defaultSettings (used to detect the expiring bucket); ClientsPage threads them into the client-bucket helper. Loose fixes folded in: - Add Client: email field is auto-filled with a random handle on open, matching uuid/subId/password/auth. - Inbound clone: parse and reuse the source settings JSON (with clients reset to []) instead of building a fresh defaulted Settings, so VLESS Encryption/Decryption and other non-client fields survive the clone. - en-US.json: add the ipLog string used by the edit-client modal. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): add Reverse tag field for VLESS-attached clients Mirrors the Flow field's pattern: a Reverse tag input appears in the Add/Edit Client modal whenever at least one selected inbound is VLESS or PortFallback. The value rides over the wire as client.reverse = { tag: '...' } so it lands directly in model.Client's *ClientReverse field; an empty value omits the reverse key entirely. On edit the field is hydrated from props.client.reverse?.tag, and the showReverseTag watcher clears the field if the user drops the last VLESS-like inbound from the selection. * fix(xray): emit only protocol-relevant fields per client entry The Xray config synthesizer was writing every identifier field (id, password, flow, auth, security/method, reverse) on every client entry regardless of the inbound's protocol. Xray ignores unknown fields, so the config worked, but it diverged from the spec and leaked secrets across protocols when one client was attached to multiple inbounds — a VLESS inbound's generated config carried the same client's Trojan password and Hysteria auth alongside its uuid. Switch on inbound.Protocol when building each entry: - VLESS / PortFallback: id, flow, reverse - VMess: id, security - Trojan: password, flow - Shadowsocks: password, method - Hysteria / Hysteria2: auth email is emitted for every protocol. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): restore auto-disable kick under new schema disableInvalidClients still resolved (inbound_tag, email) pairs via JSON_EACH(inbounds.settings.clients), which is empty after migrating to the clients + client_inbounds tables. Result: xrayApi.RemoveUser never ran for depleted clients, clients.enable stayed true so the UI showed them as active, and only xray_client_traffic.enable got flipped - making "Restart Xray After Auto Disable" only half-work. Resolve the targets via a JOIN through the new schema, flip clients.enable so the Clients page reflects the state, and drop the legacy JSON write-back plus the subId cascade workaround (email is unique now). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): live WebSocket updates + Ended status surfacing ClientsPage now subscribes to traffic / client_stats / invalidate WebSocket events instead of polling /onlines every 10s. Per-row traffic counters refresh in place, online state stays current, and list-level mutations elsewhere trigger a refresh. The client roll-up summary moves from InboundsPage to ClientsPage where it belongs, restructured into six labeled stat tiles (Total / Online / Ended / Expiring / Disabled / Active) with email popovers on the ones with issues. Auto-disabled clients (traffic exhausted or expiry passed) now classify as 'depleted' even though clients.enable=false, so they show up under the Ended filter and render a red Ended tag instead of looking indistinguishable from an operator-disabled row. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(nodes): per-node client roll-up and panel version Added transient inboundCount / clientCount / onlineCount / depletedCount fields to model.Node, populated by NodeService.GetAll via aggregated queries (one join across inbounds + client_inbounds, one over client_traffics intersected with the in-memory online emails). The Nodes list renders these as colored chips on a new "Clients" column so an operator can see at a glance how many users each node carries and how many are currently online or depleted. Also exposes the remote panel's version. The central panel adds panelVersion to its /api/server/status payload (sourced from config.GetVersion). Probe reads that field and persists it on the node row, mirroring how xrayVersion already flows. NodesPage gets a new column next to Xray Version, in both desktop and mobile views, with English and Persian strings. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): stop node sync from resurrecting deleted clients Several related issues around node-managed clients: - Remote runtime: drop the per-inbound resetAllClientTraffics path and point traffic/onlines/lastOnline fetches at the new /panel/api/clients/* routes. - Delete from master: always push the updated inbound to the node even when the client was already disabled or depleted, so the node actually loses the user instead of silently keeping it. - setRemoteTraffic: mirror remote clients into the central tables only on first discovery of a node inbound. Matched inbounds let the master own the join table, so a stale snap can no longer re-create a ClientRecord (and join row) for a client that was just deleted on the master. - ClientService.Delete: route through submitTrafficWrite so deletes serialize with node traffic merges, and switch the final ClientRecord delete to an explicit Where("id = ?") clause. - setRemoteTraffic UNIQUE-constraint fix: use clause.OnConflict on inserts and email-keyed UPDATEs for client_traffics, so mirroring a snap doesn't trip the unique email index. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(clients): switch client API endpoints from id to email All client-scoped routes now use the unique email as the path key (get, update, del, attach, detach, links). Email is the stable, protocol-independent identifier — UUIDs don't exist for trojan or shadowsocks, and internal numeric ids leaked panel implementation detail into the public API. Removed the redundant /traffic/byId/:id endpoint (covered by /traffic/:email) and collapsed /links/:id/:email into /links/:email, which now returns links across every attached inbound for the client. Frontend selection, bulk delete, and toggle state are now keyed by email as well, dropping the id→email lookup workaround. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(server): move cached state and helpers into ServerService ServerController had grown to hold its own status cache, version-list TTL cache, history-bucket whitelist, and the loop that drove all three — concerns that belong in the service layer. Pull them out: - lastStatus + the @2s refresh become ServerService.RefreshStatus and ServerService.LastStatus; the controller's cron now just orchestrates the cross-service side effects (xrayMetrics sample, websocket broadcast). - The 15-minute Xray-versions cache (with stale-on-error fallback) moves into ServerService.GetXrayVersionsCached, collapsing the controller handler to a single call. - The freedom/blackhole outbound-tag walk used by /xraylogs becomes ServerService.GetDefaultLogOutboundTags. - The allowed-history-bucket whitelist moves to package-level service.IsAllowedHistoryBucket, so both NodeController and ServerController validate against the same list. Net result: web/controller/server.go drops from 458 to 365 lines and contains only HTTP wiring + presentation-y side effects. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(api): emit JSON-text columns as nested objects Inbound, ClientRecord, and InboundClientIps store settings / streamSettings / sniffing / reverse / ips as JSON-text in the DB. The API was passing that text through verbatim, so every consumer had to JSON.parse a string inside a string. Add MarshalJSON / UnmarshalJSON so the wire format is a real nested object, while still accepting the legacy escaped-string shape on write. Frontend dbinbound.js gets a matching coerceInboundJsonField helper for the same dual-shape read path, and inbound.js toJson stops emitting empty/placeholder fields (externalProxy [], sniffing destOverride when disabled, etc.) so the new normalised JSON stays terse. api-docs and the inbound-clone path are updated to the new shape. Controller route lists are regrouped so all GETs sit above POSTs. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): include inboundIds and traffic in /clients/list ClientRecord got its own MarshalJSON in the previous commit, and ClientWithAttachments embeds it to add inboundIds and traffic. Go promotes the embedded MarshalJSON to the outer struct, so the encoder was calling ClientRecord.MarshalJSON for the whole value and silently dropping the extras. The frontend reads row.inboundIds / row.traffic from /clients/list, so attached inbounds didn't render and newly added clients looked like they hadn't saved. Add an explicit MarshalJSON on ClientWithAttachments that splices the extras in. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): gate IP Log on ipLimitEnable + clean access-log dropdown Legacy panel hid the IP Log section when access logging was off; the Vue 3 migration left it gated on isEdit only, so the section showed even when xray's access log was 'none' and nothing was being recorded. Restore the ipLimitEnable gate on the edit modal's IP Log form-item. While here, clean up the Xray Settings access-log dropdown: previously two 'none' entries appeared (an empty value labelled with t('none') and the literal 'none' from the options array). Drop the empty option for access log (the literal 'none' covers it) and relabel the empty option for error log / mask address to t('empty') so they're distinguishable. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(nodes): route per-client ops through node clients API + orphan sweep Adds Runtime methods AddClient, UpdateUser, and DeleteUser so master mutates clients on a node via /panel/api/clients/{add,update,del} rather than pushing the whole inbound. The previous rt.UpdateInbound path made the node DelInbound+AddInbound on every single-client change, briefly cycling every other user on the same inbound. DelInbound no longer filters by enable=true, so a disabled node inbound actually gets removed from the node instead of being resurrected by the next snap. setRemoteTrafficLocked now sweeps any ClientRecord with zero ClientInbound rows after SyncInbound rebuilds the attachments, which is how a node-side delete propagates back to master instead of leaving a detached ghost. ClientService.Delete tombstones the email first so a snap arriving mid-delete can't re-create the record. WebSocket broadcasts an "invalidate(clients)" message on every client mutation so the Clients page refreshes without manual reload. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(balancers): allow fallback on all strategies + feed burstObservatory from random/roundRobin Drops the random/roundRobin gate on the Fallback field in BalancerFormModal so every strategy can pick a fallback outbound. syncObservatories now feeds burstObservatory from leastLoad + random + roundRobin balancers (was leastLoad only), matching how leastPing feeds observatory. Fix the JsonEditor "Unexpected end of JSON input" that appeared when switching a balancer between leastPing and another strategy: the obsView watcher was gated on showObsEditor (a boolean OR of the two flags) and missed the case where one observatory swapped for the other in the same tick. Watch the individual flags instead so obsView flips to the surviving editor and the getter stops pointing at a deleted key. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(inbounds): use sortedInbounds for mobile empty-state check InboundList referenced an undefined visibleInbounds in the mobile card list's empty-state guard, throwing "Cannot read properties of undefined (reading 'length')" and breaking the entire mobile render. * feat(clients): sortable table columns Adds the same sortState / sortableCol / sortFns pattern InboundList uses, wrapping filteredClients in sortedClients so sort composes with the existing search/filter pipeline. Sortable: enable, email, inboundIds (attachment count), traffic, remaining, expiryTime; actions and online stay unsorted. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(shadowsocks): generate valid ss2022 keys and per-client method for legacy ciphers The Add Client flow on shadowsocks inbounds was producing xray configs that failed to start: - 2022-blake3-* ciphers need a base64-encoded key of an exact byte length per cipher. fillProtocolDefaults was assigning a uuid-style string, which xray rejects as "bad key". Now the password is generated (or replaced if invalid) via random.Base64Bytes(n) sized to the chosen cipher. - Legacy ciphers (aes-256-gcm, chacha20-*, xchacha20-*) require a per-client method field in multi-user mode; model.Client has no Method, so settings.clients was stored without one and xray failed with "unsupported cipher method:". applyShadowsocksClientMethod now injects the top-level method into each client on add/update, and healShadowsocksClientMethods backfills it at xray-config-build time so existing inbounds heal on the next start. - xray/api.go ssCipherType switch was missing aes-256-gcm, which fell through to ss2022 path. - SSMethods dropdown now offers aes-256-gcm. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): preserve ClientRecord on inbound delete + filter Attached inbounds to multi-client protocols Replace the global orphan sweep in setRemoteTrafficLocked with a per-inbound diff cleanup: only delete a ClientRecord whose email disappeared from a snap-tracked inbound (i.e. a node-side delete). Inbounds that vanished entirely from the snap (e.g. admin deleted the inbound on master) aren't iterated, so a client whose last attachment came from that inbound is now left alone instead of being deleted alongside the inbound. ClientFormModal and ClientBulkAddModal now filter the Attached inbounds dropdown to protocols that actually support multiple clients: shadowsocks, vless, vmess, trojan, hysteria, hysteria2, and portfallback (which routes through VLESS settings). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): make empty-state text readable on dark/ultra themes The "No clients yet" empty state had a hardcoded black color (rgba(0,0,0,0.45)) that vanished against the dark backgrounds. Drop the inline color, let it inherit from the AntD theme, and fade with opacity like the mobile card empty state already does. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(clients): client-first tgbot add flow, tgId field, lightweight inbound options - tgbot: drop legacy per-protocol Add Client UI in favour of a client-first multi-inbound flow. New BuildClientDraftMessage / getInboundsAttachPicker let an admin pick one or more inbounds and submit a single client; per- protocol secrets are now generated server-side via fillProtocolDefaults. Drops awaiting_id/awaiting_password_tr/awaiting_password_sh state cases and add_client_ch_default_id/pass_tr/pass_sh/flow callbacks. Adds a setTGUser button + awaiting_tg_id state so the bot can set Client.TgID during Add. - clients UI: add Telegram user ID input to ClientFormModal (0 = none). Hide IP Limit field entirely when ipLimitEnable is off — disabled fields still take layout space, this collapses Auth(Hysteria) to full width. - inbounds API: new GET /panel/api/inbounds/options that returns just {id, remark, protocol, port, tlsFlowCapable}. Used by the clients page pickers so the dropdown payload stays small on panels with thousands of clients (drops settings JSON, clientStats, streamSettings). Server-side TlsFlowCapable mirrors Inbound.canEnableTlsFlow so the modal no longer needs to parse streamSettings client-side. - clientInfoMsg now shows attached inbound remarks, and getInboundUsages reports the attached client count per inbound. - api-docs: document the new /options endpoint and add tgId / flow to the clients add/update bodies. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(inbounds): keep Node column visible for node-attached inbounds The Node column was bound to hasActiveNode, so disabling every node hid the column even when inbounds were still attached to those nodes — the admin lost the visual cue that those inbounds belonged to a node and would come back when it was re-enabled. Combine hasActiveNode with a new hasNodeAttachedInbound check (any dbInbound with nodeId != null) so the column survives node-disable. * fix(api-docs): accept functional-component icons in EndpointSection AntD-Vue icons (SafetyCertificateOutlined, etc.) are functional components, so the icon prop's type: Object validator was rejecting them with a "Expected Object, got Function" warning at runtime. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * test: cover crypto, random, netsafe, sub helpers, xray equals, websocket hub, node service Adds ~110 unit tests across previously untested packages. Focus on pure-logic and concurrency surfaces where regressions would silently affect users: - util/crypto, util/random: password hashing round-trip, ss2022 key generation, alphabet/length invariants. - util/netsafe: IsBlockedIP edge cases, NormalizeHost validation, SSRF guard with AllowPrivate context bypass. - util/common, util/json_util: traffic formatter, Combine nil-skip, RawMessage empty-as-null and copy-on-unmarshal. - sub: splitLinkLines, searchKey/searchHost, kcp share fields, finalmask normalization, buildVmessLink round-trip. - xray: Config.Equals and InboundConfig.Equals field-by-field, getRequiredUserString/getOptionalUserString type checks. - web/websocket: hub registration, throttling, slow-client eviction, nil-receiver safety, concurrent register/unregister. - web/service: NodeService.normalize validation, normalizeBasePath, HeartbeatPatch.ToUI mapping. - web/job: atomicBool concurrent set/takeAndReset semantics. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * i18n(clients): replace English fallbacks with proper translation keys Pulls every hard-coded English label/title in the Clients page and its four modals through the i18n layer so localized panels stop leaking English. New keys live under pages.clients (auth, hysteriaAuth, uuid, flow, flowNone, reverseTag, reverseTagPlaceholder, telegramId, telegramIdPlaceholder, created, updated, ipLimit) plus refresh at the root and toasts.bulkDeletedMixed / bulkCreatedMixed for partial-failure toasts. Also switches the add-client modal's primary button from "Add" to "Create" for consistency with other create flows. The bulk-add Random/Random+Prefix/... email-method options stay hard-coded by request - they're identifier-shaped strings. * i18n: backfill 99 missing keys across all 12 non-English locales Brings every translation file up to parity with en-US.json so the Clients page, the fallback-children inbound section, the new refresh verb, the Nodes panel-version label and a handful of older holes stop falling through to the English fallback. New strings span: - pages.clients.* (labels, confirmations, toasts, emailMethods) - pages.inbounds.portFallback.* (Reality fallback inbound section) - pages.nodes.panelVersion, menu.clients, refresh Technical identifiers (Auth, UUID, Flow, Reverse tag) are intentionally left untranslated since they correspond to xray-core field names. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * i18n: drop stale pages.client block duplicated in every non-English locale Every non-English locale carried a pages.client (singular) section with 30 entries that duplicated pages.clients (plural). The plural namespace is what the Vue code actually consumes; the singular one was dead weight from an older rename that never got cleaned up in the non-English files. Removing it brings every locale to exactly 984 keys, matching en-US.json. * chore: apply modernize analyzer fixes across codebase Mechanical replacements suggested by golang.org/x/tools/.../modernize: strings.Cut/CutPrefix/SplitSeq, slices.Contains, maps.Copy, min(), range-over-int, new(expr), strings.Builder for hot += loops, reflect.TypeFor[T](), sync.WaitGroup.Go(), drop legacy //+build lines. * feat(database): add PostgreSQL as an optional backend alongside SQLite Lets operators with large client counts or multi-node setups pick PostgreSQL at install time without breaking the existing SQLite default. Backend is selected at runtime via XUI_DB_TYPE/XUI_DB_DSN, a small dialect layer keeps the five JSON_EXTRACT/JSON_EACH queries portable, and a new `x-ui migrate-db` subcommand copies SQLite data into PostgreSQL in FK-aware order. * fix(inbounds): gate node selector to multi-node-capable protocols Hide the Deploy-To selector and clear nodeId when switching to a protocol that can't run on a remote node. Also: - subs: return 404 (not 400) when subId matches no inbounds, so VPN clients distinguish "deleted/unknown" from a server error - hysteria link gen: use the inbound's resolved address so node-managed inbounds advertise the node host instead of the central panel - shadowsocks: default network to 'tcp' (udp was causing issues for some clients on first-create) - vite dev proxy: rewrite migrated-route bypass against the live base path instead of a hardcoded single-segment regex Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(clients): bulk add/delete correctness + perf, working pagination, delayed-start in form Bulk add/delete were serial on the frontend (one toast per call, N round-trips) and the backend race exposed by parallelizing them lost client attachments and hit UNIQUE constraint failed on client_inbounds. The single add/edit modal also had no Start-After-First-Use option, and the table never showed the delayed duration. Backend (web/service/client.go): - Per-inbound mutex on Add/Update/Del InboundClient so concurrent writers on the same inbound don't lose the read-modify-write of settings JSON. - SyncInbound skips create+join when the email is tombstoned so a concurrent maintenance pass (adjustTraffics, autoRenewClients, markClientsDisabledIn- Settings) that did a stale RMW can't resurrect a just-deleted client with a fresh id. - compactOrphans sweeps settings.clients entries whose ClientRecord no longer exists, applied in Add/DelInboundClient + DelInboundClientByEmail so each user-initiated mutation self-heals the inbound's settings. - DelInboundClient uses Pluck instead of First for the stats lookup so a missing row doesn't abort the delete with a noisy ErrRecordNotFound log. Frontend: - HttpUtil.{get,post} accept a silent option that suppresses the auto-toast. - ClientBulkAddModal fires creates in parallel + silent + one summary toast. - useClients.removeMany runs deletes in parallel + silent and refreshes once; ClientsPage bulk delete uses it and shows one aggregate toast. - useClients.applyInvalidate debounces 200 ms so the burst of N WebSocket invalidate events from the backend collapses into a single refresh. - ClientsPage pagination is reactive (paginationState ref + tablePagination computed); onTableChange persists page-size and page changes. - ClientFormModal gains a Start-After-First-Use switch + Duration days input alongside the existing Expiry Date picker; on edit-mode open a negative expiryTime is decoded back to delayed mode + days; on submit the payload sends -86400000 * days or the absolute timestamp. - ClientsPage table shows the delayed-start duration (blue tag Nd, tooltip Start After First Use: Nd) instead of infinity. - Telegram ID field in the form is hidden when /panel/setting/defaultSettings reports tgBotEnable=false; Comment then fills the row. - Form row 3 collapses UUID (span 12) + Total GB (span 8) + Limit IP (span 4) when ipLimitEnable is on, else UUID + Total GB at 12/12. - useInbounds.rollupClients counts only clients with a matching clientStats row, so orphans in settings.clients no longer inflate the inbound's count. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(windows): clean shutdown, working panel restart, harden kernel32 load Three Windows-specific issues addressed: 1. Orphaned xray-windows-amd64 after VS Code debugger stop. Delve's "Stop" sends TerminateProcess to the Go binary, which is uncatchable — our signal handlers never run, so xrayService.StopXray() is skipped and xray is left dangling. Spawn xray as a child of a Job Object with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE so the OS kills xray when our handle to the job is closed (which happens even on TerminateProcess). Also trap os.Interrupt in main so Ctrl+C in the terminal runs the graceful path. 2. /panel/setting/restartPanel logged "failed to send SIGHUP signal: not supported by windows" because Windows can't deliver arbitrary signals. Add a restart hook in web/global; main registers it to push SIGHUP into its own signal channel, and RestartPanel calls the hook before falling back to the (Unix-only) signal path. Same restart-loop code runs in both cases. 3. util/sys/sys_windows.go now uses windows.NewLazySystemDLL so the kernel32.dll resolve is pinned to %SystemRoot%\System32 (prevents DLL hijacking by a planted DLL next to the binary). Local filetime type replaced with windows.Filetime, and the unreliable syscall.GetLastError() fallback replaced with a type assertion on the errno captured at call time. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(sys): correct CPU/connection accounting on linux + darwin util/sys/sys_linux.go: - GetTCPCount/GetUDPCount were counting the column header row in /proc/net/{tcp,udp}[6] as a connection, inflating the reported total by 1 per non-empty file (so the panel status line always showed 2 more connections than actually existed). Replace getLinesNum + safeGetLinesNum with a single bufio.Scanner-based countConnections that skips the header. - CPUPercentRaw now opens HostProc("stat") instead of a hardcoded /proc/stat so HOST_PROC overrides apply, matching the connection counters in the same file. - Simplify CPU field unpacking: pad nums to 8 once instead of guarding every assignment with a len check. util/sys/sys_darwin.go: - Fix swapped idle/intr indices on kern.cp_time. BSD CPUSTATES order is user, nice, sys, intr, idle (CP_INTR=3, CP_IDLE=4) — gopsutil's cpu_darwin_nocgo.go reads the same layout. The previous code used out[3] as idle and out[4] as intr, so busy = total - dIdle was actually subtracting interrupt time, making the panel report CPU usage close to 100% on macOS regardless of actual load. - Collapse the per-field delta math into a single loop. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(xray): rotate crash reports into log folder, prevent overwrites writeCrashReport had two flaws: it wrote to the bin folder (alongside the xray binary) which conflates artifacts, and the second-precision timestamp meant a tight restart-loop crash burst overwrote prior reports. Write to the log folder with nanosecond precision and keep the last 10 reports. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * revert(inbounds): drop unreleased portfallback protocol The Port-with-Fallback inbound (commit 62fd9f9d) was confusing as a standalone protocol — fallbacks belong on a regular VLESS/Trojan TCP-TLS inbound, the way Xray models them natively. Rip out the entire feature cleanly (no migration needed since it was never released): protocol constant, fallback children DB table, FallbackService, 2 API endpoints, all UI rows, related translations and api-docs. A native fallback flow attached to VLESS/Trojan TCP-TLS/Reality will land in a follow-up commit. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(inbounds): native fallbacks on VLESS/Trojan TCP-TLS, with working child links A VLESS or Trojan inbound on TCP with TLS or Reality can now act as a fallback master: pick existing inbounds as children and the panel auto- fills the SNI / ALPN / path / xver routing fields from each child's transport, auto-builds settings.fallbacks at config-gen time, and rewrites the child's client-share link so it advertises the master's reachable endpoint and TLS state instead of the child's loopback listen. Layout matches the Xray All-in-One Nginx example: master at :443 with clients + TLS, each child on 127.0.0.1 with its own transport+clients. Order matters (Xray walks fallbacks top-to-bottom) — reorder via the per-row up/down arrows. Path / SNI / ALPN are exposed under a per-row Edit toggle for the rare cases where the auto-derivation needs overriding; otherwise just pick a child and you're done. Backend: new InboundFallback table + FallbackService (GetByMaster / SetByMaster / GetParentForChild / BuildFallbacksJSON); two routes (GET / POST /panel/api/inbounds/:id/fallbacks); xray.GetXrayConfig injects settings.fallbacks for any VLESS/Trojan TCP-TLS/Reality inbound; GetInbounds annotates each child with FallbackParent so the frontend can rewrite links without an extra round-trip. Link projection covers every emission path — clients-page QR/links, per-inbound Get URL, raw subscription, sub-JSON, sub-Clash, and the inbounds-page link/info/QR — via a shared projectThroughFallbackMaster on the backend and a shared projectChildThroughMaster on the frontend that both handle the panel-tracked relationship and the legacy unix-socket (@vless-ws) convention. Strings translated into all 12 non-English locales. * docs: rewrite CONTRIBUTING with full local-dev setup The prior three-line CONTRIBUTING left newcomers guessing at every non-trivial step: which Go / Node versions, where xray comes from, why the panel goes blank when XUI_DEBUG=true is flipped on, how the Vue multi-page setup is wired, what to do on Windows when go build trips on the CGo SQLite driver. Now covers prerequisites, MinGW-w64 install on Windows (niXman builds or MSYS2), one-shot first-time setup, two frontend dev workflows with the XUI_DEBUG asset-cache gotcha called out, the architecture and conventions of the Vue side, a project-layout map, useful env vars, and the PR checklist. ---------
2026-05-19 10:16:42 +00:00
for value := range strings.SplitSeq(trusted, ",") {
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 <ho3ein.sanaei@gmail.com>
2026-05-13 10:52:52 +00:00
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
}
}
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 <ho3ein.sanaei@gmail.com>
2026-05-13 10:52:52 +00:00
return false
}
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 <ho3ein.sanaei@gmail.com>
2026-05-13 10:52:52 +00:00
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) {
candidate := strings.TrimSpace(value)
if candidate == "" {
return "", false
}
if ip, ok := parseIPCandidate(candidate); ok {
return ip.String(), true
}
if host, _, err := net.SplitHostPort(candidate); err == nil {
if ip, ok := parseIPCandidate(host); ok {
return ip.String(), true
}
}
if strings.Count(candidate, ":") == 1 {
if host, _, err := net.SplitHostPort(fmt.Sprintf("[%s]", candidate)); err == nil {
if ip, ok := parseIPCandidate(host); ok {
return ip.String(), true
}
}
}
return "", false
}
func parseIPCandidate(value string) (netip.Addr, bool) {
ip, err := netip.ParseAddr(strings.TrimSpace(value))
if err != nil {
return netip.Addr{}, false
}
return ip.Unmap(), true
2023-02-09 19:18:06 +00:00
}
2025-09-20 07:35:50 +00:00
// jsonMsg sends a JSON response with a message and error status.
2023-02-09 19:18:06 +00:00
func jsonMsg(c *gin.Context, msg string, err error) {
jsonMsgObj(c, msg, nil, err)
}
2025-09-20 07:35:50 +00:00
// jsonObj sends a JSON response with an object and error status.
func jsonObj(c *gin.Context, obj any, err error) {
2023-02-09 19:18:06 +00:00
jsonMsgObj(c, "", obj, err)
}
2025-09-20 07:35:50 +00:00
// jsonMsgObj sends a JSON response with a message, object, and error status.
func jsonMsgObj(c *gin.Context, msg string, obj any, err error) {
2023-02-09 19:18:06 +00:00
m := entity.Msg{
Obj: obj,
}
if err == nil {
m.Success = true
if msg != "" {
2025-05-09 03:46:29 +00:00
m.Msg = msg
2023-02-09 19:18:06 +00:00
}
} else {
m.Success = false
errStr := err.Error()
if errStr != "" {
m.Msg = msg + " (" + errStr + ")"
logger.Warning(msg+" "+I18nWeb(c, "fail")+": ", err)
} else if msg != "" {
m.Msg = msg
logger.Warning(msg + " " + I18nWeb(c, "fail"))
} else {
m.Msg = I18nWeb(c, "somethingWentWrong")
logger.Warning(I18nWeb(c, "somethingWentWrong") + " " + I18nWeb(c, "fail"))
}
2023-02-09 19:18:06 +00:00
}
c.JSON(http.StatusOK, m)
}
2025-09-20 07:35:50 +00:00
// pureJsonMsg sends a pure JSON message response with custom status code.
func pureJsonMsg(c *gin.Context, statusCode int, success bool, msg string) {
c.JSON(statusCode, entity.Msg{
Success: success,
Msg: msg,
})
2023-02-09 19:18:06 +00:00
}
2025-09-20 07:35:50 +00:00
// isAjax checks if the request is an AJAX request.
2023-02-09 19:18:06 +00:00
func isAjax(c *gin.Context) bool {
return c.GetHeader("X-Requested-With") == "XMLHttpRequest"
}