From 9ea6f9d50b25c781c35ac35fd9f9aa8339abd458 Mon Sep 17 00:00:00 2001 From: Mohamadhosein Moazennia Date: Wed, 18 Feb 2026 20:12:04 +0330 Subject: [PATCH] docs: add panel guide documentation --- PANEL_GUIDE_SOURCE_OF_TRUTH.md | 1233 +++++++++++++++++ .../01-overview-and-architecture.md | 81 ++ docs/panel-guide/02-pages-and-operations.md | 92 ++ docs/panel-guide/03-api-and-cli-reference.md | 73 + docs/panel-guide/04-security-and-hardening.md | 57 + .../panel-guide/05-client-management-model.md | 46 + .../06-custom-client-center-feature.md | 68 + .../07-dev-and-testing-workflow.md | 66 + .../08-protocols-and-config-analysis.md | 93 ++ .../panel-guide/09-xray-protocol-reference.md | 141 ++ docs/panel-guide/10-glossary-and-concepts.md | 61 + .../panel-guide/11-troubleshooting-runbook.md | 84 ++ .../12-change-management-and-rollout.md | 53 + .../13-feature-file-map-and-decision-log.md | 61 + .../99-session-context-transfer-2026-02-18.md | 98 ++ docs/panel-guide/README.md | 40 + 16 files changed, 2347 insertions(+) create mode 100644 PANEL_GUIDE_SOURCE_OF_TRUTH.md create mode 100644 docs/panel-guide/01-overview-and-architecture.md create mode 100644 docs/panel-guide/02-pages-and-operations.md create mode 100644 docs/panel-guide/03-api-and-cli-reference.md create mode 100644 docs/panel-guide/04-security-and-hardening.md create mode 100644 docs/panel-guide/05-client-management-model.md create mode 100644 docs/panel-guide/06-custom-client-center-feature.md create mode 100644 docs/panel-guide/07-dev-and-testing-workflow.md create mode 100644 docs/panel-guide/08-protocols-and-config-analysis.md create mode 100644 docs/panel-guide/09-xray-protocol-reference.md create mode 100644 docs/panel-guide/10-glossary-and-concepts.md create mode 100644 docs/panel-guide/11-troubleshooting-runbook.md create mode 100644 docs/panel-guide/12-change-management-and-rollout.md create mode 100644 docs/panel-guide/13-feature-file-map-and-decision-log.md create mode 100644 docs/panel-guide/99-session-context-transfer-2026-02-18.md create mode 100644 docs/panel-guide/README.md diff --git a/PANEL_GUIDE_SOURCE_OF_TRUTH.md b/PANEL_GUIDE_SOURCE_OF_TRUTH.md new file mode 100644 index 00000000..9617c443 --- /dev/null +++ b/PANEL_GUIDE_SOURCE_OF_TRUTH.md @@ -0,0 +1,1233 @@ +# 3x-ui Panel Deep Guide (Source of Truth) + +## Scope and trust model + +This document is built from: +- Official project wiki pages cloned from `https://github.com/MHSanaei/3x-ui.wiki.git`. +- Source code in this repository (`MHSanaei/3x-ui`, current local `main`). +- Live panel inspection against your running instance via Playwright. + +This is intended to be a practical source of truth for operating the panel. + +Important constraints: +- The panel evolves quickly; always re-check against current code/wiki before risky production changes. +- Some behavior differs by version, settings, and enabled modules (Telegram, LDAP, Fail2Ban, subscription JSON). + +--- + +## 1. What 3x-ui is + +3x-ui is a web control panel around Xray-core. It manages: +- Inbounds and client accounts. +- Traffic/expiry limits and stats. +- Xray config template editing and advanced routing/outbound controls. +- Operational actions (restart Xray, logs, geofile updates, DB export/import). +- Optional subscription service (links and JSON endpoint). +- Optional Telegram bot features. + +--- + +## 2. Runtime architecture + +## 2.1 Core processes + +The binary starts two servers: +- Web panel server (UI + panel API). +- Subscription server (separate listener/path logic). + +Code references: +- `main.go` boot and signal handling. +- `web/web.go` panel server setup. +- `sub/sub.go` subscription server setup. + +## 2.2 Data layer + +Persistent data is SQLite (GORM). +Default models auto-migrated at startup: +- `User` +- `Inbound` +- `OutboundTraffics` +- `Setting` +- `InboundClientIps` +- `xray.ClientTraffic` +- `HistoryOfSeeders` + +Code references: +- `database/db.go` +- `database/model/model.go` +- `xray/client_traffic.go` + +## 2.3 Session/auth model + +- Session cookie store is configured with secret from settings. +- Cookie is `HttpOnly`, `SameSite=Lax`, max age based on `sessionMaxAge`. +- Panel routes under `/panel` require login session. +- API routes under `/panel/api` also require session; unauthorized API returns `404` (not `401`) to hide endpoint existence. + +Code references: +- `web/web.go` (session setup) +- `web/session/session.go` +- `web/controller/xui.go` and `web/controller/api.go` + +## 2.4 Scheduler/background jobs + +Panel cron jobs include: +- Xray running check: every `1s`. +- Conditional Xray restart pass: every `30s`. +- Traffic pull from Xray API: every `10s` (after initial delay). +- Client IP checks: every `10s`. +- Log cleanup: daily. +- Periodic traffic reset: daily/weekly/monthly. +- LDAP sync: configurable cron, when enabled. +- Telegram stats notify: configurable cron, when enabled. +- Hash storage cleanup: every `2m` (Telegram callbacks). +- CPU threshold monitor: every `10s` (Telegram feature). + +Code references: +- `web/web.go` +- `web/job/*.go` + +--- + +## 3. URL topology and route map + +With default base path `/`, main user-facing URLs are: +- Login: `/` +- Panel pages: `/panel/`, `/panel/inbounds`, `/panel/settings`, `/panel/xray` +- Panel APIs: `/panel/api/...` + +If `webBasePath` changes, the entire panel path is prefixed. + +## 3.1 UI routes + +Code references: +- `web/controller/index.go` +- `web/controller/xui.go` + +- `GET /` login page (or redirects to `panel/` when already logged in). +- `POST /login` +- `GET /logout` +- `POST /getTwoFactorEnable` +- `GET /panel/` +- `GET /panel/inbounds` +- `GET /panel/settings` +- `GET /panel/xray` + +## 3.2 API routes (panel) + +Code references: +- `web/controller/api.go` +- `web/controller/inbound.go` +- `web/controller/server.go` +- `web/controller/setting.go` +- `web/controller/xray_setting.go` + +Main groups: +- `/panel/api/inbounds/*` +- `/panel/api/server/*` +- `/panel/setting/*` +- `/panel/xray/*` +- `/panel/api/backuptotgbot` + +(See sections 8 and 9 for functional behavior per group.) + +## 3.3 Subscription service routes + +Code references: +- `sub/sub.go` +- `sub/subController.go` + +Routes are dynamic based on settings: +- Link path: `{subPath}:subid` +- JSON path (if enabled): `{subJsonPath}:subid` + +Defaults are typically `/sub/` and `/json/` style paths. + +--- + +## 4. Live instance findings (from your panel) + +Observed in your current running panel: +- Version shown: `v2.8.10`. +- Xray shown running. +- Inbounds page has 2 active VLESS+Reality inbounds on ports `443` and `8443`. +- Security warnings active: + - Panel connection not secure (TLS missing). + - Panel path appears default/weak. + - Subscription path appears default/weak. + +This confirms panel behavior matches code/wiki defaults and hardening alerts. + +--- + +## 5. Page-by-page guide + +## 5.1 Overview page + +Purpose: +- Operational dashboard for server + Xray + quick management actions. + +Typical widgets/actions: +- CPU/RAM/Swap/Storage stats. +- Xray state with `Stop` / `Restart` actions. +- Current Xray version and switch/update actions. +- Logs, config, backup shortcuts. +- Uptime and traffic/speed totals. +- IP info, connection stats. + +Backed by: +- `server.status` and related API endpoints. +- WebSocket status broadcasts. + +Code references: +- `web/controller/server.go` +- `web/service/server.go` +- `web/websocket/*` + +## 5.2 Inbounds page + +Purpose: +- Manage listeners and user clients. + +Core capabilities: +- Add/edit/delete inbounds. +- Enable/disable inbound. +- Add/edit/delete clients. +- Bulk client add. +- Reset traffic (single client, per inbound, global). +- Remove depleted clients. +- Import inbound. +- Export URLs/subscription URLs/inbound template. +- Search/filter and online/last-online checks. + +Live menu entries seen in your panel include: +- Edit +- Add Client +- Add Bulk +- Reset Clients Traffic +- Export All URLs +- Export All URLs - Subscription +- Delete Depleted Clients +- Export Inbound +- Reset Traffic +- Clone +- Delete + +Implementation notes: +- Changes are persisted to DB, and for enabled inbounds/clients are mirrored via Xray API when possible. +- For certain changes, `needRestart` path is set and picked up by scheduler. +- Traffic accounting is updated from periodic Xray traffic pulls. + +Code references: +- `web/controller/inbound.go` +- `web/service/inbound.go` +- `web/service/xray.go` + +## 5.3 Panel Settings page + +Top tabs (observed + source): +- General +- Authentication +- Telegram Bot +- Subscription + +### General + +What it controls: +- Listen IP/domain/port for panel. +- Panel URI path (`webBasePath`). +- Session duration. +- Pagination size. +- Language. +- Additional collapsible areas: notifications, certificates, external traffic, date/time, LDAP. + +Why critical: +- Port/path/domain/listen are core attack-surface controls. + +### Authentication + +What it controls: +- Admin credential change (current/new username/password). +- Two-factor authentication section. + +Behavior: +- Update verifies old credentials first. +- Passwords are hashed (bcrypt). + +### Telegram Bot + +What it controls: +- Enable/disable bot. +- Bot token. +- Admin chat IDs. +- Notification cadence/language. +- Additional bot notification/proxy/server settings. + +Capabilities documented and implemented: +- Periodic reports. +- Login notify. +- CPU/load notify. +- Backup delivery. +- Client lookup/report flows. + +### Subscription + +What it controls: +- Subscription service enable. +- JSON subscription endpoint enable. +- Listen IP/domain/port. +- URI paths for link/json endpoints. +- Encryption/show-info/update interval/title/support/announce. +- Routing headers integration settings. + +Behavior notes: +- Subscription server can run with separate certs/keys. +- Headers like `Subscription-Userinfo`, profile metadata, and routing hints can be returned. + +Code references: +- `web/controller/setting.go` +- `web/service/setting.go` +- `sub/sub.go` +- `sub/subController.go` + +## 5.4 Xray Configs page + +Top tabs (observed): +- Basics +- Routing Rules +- Outbounds +- Reverse +- Balancers +- DNS +- Advanced + +### Basics + +Controls global xray behavior such as: +- General runtime strategies. +- Statistics/log/general options. +- Outbound test URL used for test-outbound checks. + +### Routing Rules + +Defines how traffic is routed (domain/ip/network/rule matching, outbound tags). +Used for use-cases like WARP/TOR steering. + +### Outbounds + +Manages outbound objects and stats. +Features include: +- Add/edit/delete outbound. +- WARP creation/registration hooks. +- Outbound traffic reset. +- Outbound connectivity test (using server-controlled test URL). + +### Reverse/Balancers/DNS + +Advanced xray building blocks exposed in UI for complex routing topologies. + +### Advanced + +Raw template-centric advanced xray config editing. +Final generated config derives from template + panel-managed entities. + +Safety note: +- Invalid advanced edits can break xray start; keep recovery path (default/reset) ready. + +Code references: +- `web/controller/xray_setting.go` +- `web/service/xray_setting.go` +- `web/service/outbound.go` +- `web/service/warp.go` +- `web/service/xray.go` + +--- + +## 6. Subscription service deep behavior + +The subscription server: +- Is independent from panel UI server. +- Reads dedicated subscription settings. +- Supports optional domain enforcement. +- Supports link and JSON endpoints. +- Supports base64 response mode for subscription links. +- Can render HTML subscription page when requested by browser/flags. +- Emits metadata headers (`Subscription-Userinfo`, update interval, profile headers, routing headers). + +Code references: +- `sub/sub.go` +- `sub/subController.go` +- `sub/subService.go` +- `sub/subJsonService.go` + +--- + +## 7. Settings catalog (important keys) + +Default key space includes panel, xray, telegram, subscription, ldap, and feature toggles. +Key examples: +- Panel: `webListen`, `webDomain`, `webPort`, `webCertFile`, `webKeyFile`, `webBasePath`, `sessionMaxAge`. +- Security/auth: `secret`, `twoFactorEnable`, `twoFactorToken`. +- Xray: `xrayTemplateConfig`, `xrayOutboundTestUrl`. +- Telegram: `tgBotEnable`, `tgBotToken`, `tgBotChatId`, `tgRunTime`, `tgCpu`, etc. +- Subscription: `subEnable`, `subJsonEnable`, `subPort`, `subPath`, `subJsonPath`, `subEncrypt`, `subUpdates`, etc. +- LDAP: multiple `ldap*` keys. + +Code references: +- `web/service/setting.go` default map and getters/setters. + +--- + +## 8. API behavior guide + +## 8.1 Auth + +- Login endpoint creates session cookie. +- API requires valid session. +- Unauthenticated API calls return 404 by design. + +Code references: +- `web/controller/index.go` +- `web/controller/api.go` + +## 8.2 Inbounds API + +Base path: `/panel/api/inbounds` + +Functions: +- Read inbounds/client traffics. +- CRUD inbound. +- CRUD inbound clients. +- Reset traffic operations. +- Import inbound. +- Online/last-online queries. +- IP tracking/cleanup. + +Code reference: +- `web/controller/inbound.go` + +## 8.3 Server API + +Base path: `/panel/api/server` + +Functions: +- Status and CPU history. +- Xray version listing/install. +- Geofile updates. +- Logs and xray logs retrieval. +- Config and DB export. +- DB import. +- Utility key generators (UUID, X25519, ML-DSA-65, ML-KEM-768, VLESS keys, ECH cert). + +Code reference: +- `web/controller/server.go` + +## 8.4 Xray settings API + +Base path: `/panel/xray` + +Functions: +- Read/update xray template + outbound test URL. +- Get xray result text. +- Get/reset outbound traffic. +- Warp actions (`data`, `del`, `config`, `reg`, `license`). +- Test outbound endpoint. + +Code reference: +- `web/controller/xray_setting.go` + +## 8.5 Panel settings API + +Base path: `/panel/setting` + +Functions: +- Get all settings. +- Get default settings. +- Update settings. +- Update user credentials. +- Restart panel. +- Get default xray JSON config. + +Code reference: +- `web/controller/setting.go` + +--- + +## 9. CLI and admin script operations + +## 9.1 Binary subcommands (`x-ui` binary) + +From `main.go`: +- `run` +- `migrate` +- `setting` (reset/show/port/user/password/basepath/listenIP/cert flags/telegram flags) +- `cert` + +Useful flag examples: +- `x-ui setting -show true` +- `x-ui setting -port 2053` +- `x-ui setting -webBasePath /random-path/` +- `x-ui setting -username -password

` +- `x-ui setting -resetTwoFactor true` +- `x-ui cert -webCert -webCertKey ` + +## 9.2 Menu/admin shell script (`x-ui.sh`) + +Top-level menu includes: +- Install/update/uninstall/legacy. +- Reset credentials/base path/settings. +- Port change and current settings display. +- Start/stop/restart/status/log management. +- Autostart toggles. +- SSL management (ACME, Cloudflare, set cert paths). +- IP limit/Fail2Ban management. +- Firewall management. +- SSH port-forwarding helper. +- BBR, geofile update, speedtest. + +Script subcommands include: +- `x-ui start|stop|restart|status|settings|enable|disable|log|banlog|update|legacy|install|uninstall|update-all-geofiles` + +Code reference: +- `x-ui.sh` + +--- + +## 10. Security and hardening guide (critical) + +Minimum hardening baseline: +1. Change default admin credentials immediately. +2. Enable two-factor authentication. +3. Change panel URI path from default (`/`) to a long random path ending with `/`. +4. Use TLS certs for panel and subscription endpoints. +5. Prefer binding panel to localhost/private interface and use SSH tunnel for admin access. +6. Restrict firewall rules tightly (panel port not globally open if possible). +7. Enable Fail2Ban/IP limit where relevant. +8. Keep geofiles and xray/panel versions updated. +9. Treat Telegram token as secret; rotate if exposed. +10. Export backups regularly and test restore flow. + +Operational warning: +- Many panel settings changes require Save + Restart Panel/Xray to apply. + +--- + +## 11. Common operational workflows + +## 11.1 Add a new inbound safely + +1. Go to `Inbounds` -> `Add Inbound`. +2. Choose protocol/transport/security (e.g., VLESS + TCP + Reality). +3. Set port/tag/stream settings and enable inbound. +4. Add clients with limits (traffic, expiry, IP limit, reset policy). +5. Save and verify on `Overview` (xray running, no config errors). +6. Export URLs/subscription for distribution. + +## 11.2 Rotate admin credentials + +1. `Panel Settings` -> `Authentication`. +2. Fill current and new credentials. +3. Confirm and verify new login. +4. Enable/verify 2FA. + +## 11.3 Enable subscription links + +1. `Panel Settings` -> `Subscription`. +2. Enable Subscription Service and set secure path/domain/port. +3. Optionally enable JSON endpoint and set separate path. +4. Configure TLS cert paths for subscription listener. +5. Save and restart panel/services as required. +6. Validate `/{subPath}{subid}` and JSON endpoint. + +## 11.4 Configure WARP routing + +1. `Xray Configs` -> `Outbounds` -> WARP create/register flow. +2. Add/verify outbound tag. +3. `Routing Rules` add domain/ip/network rules to send selected traffic to WARP outbound. +4. Save and restart xray. + +## 11.5 Restore from DB backup + +1. Export DB first before risky operations. +2. Use server API/UI import DB action. +3. Ensure xray restart path completes. +4. Validate inbounds/clients/settings and login after import. + +--- + +## 12. Known caveats and behavior notes + +- API unauthorized returns 404 (intentional) and may confuse API clients expecting 401. +- Some warning/help text in wiki is version-sensitive; code behavior wins when mismatch appears. +- Access log and fail2ban/IP-limit behavior depend on proper Xray log setup. +- High bandwidth users may continue briefly after limits due to periodic enforcement cadence. +- If DB is slow/locked, traffic/accounting behavior can appear delayed. + +--- + +## 13. High-value file map (for future deep checks) + +- Boot/CLI: + - `main.go` + - `x-ui.sh` +- Web server and middleware wiring: + - `web/web.go` + - `web/middleware/*` +- Controllers (routes): + - `web/controller/index.go` + - `web/controller/xui.go` + - `web/controller/api.go` + - `web/controller/inbound.go` + - `web/controller/server.go` + - `web/controller/setting.go` + - `web/controller/xray_setting.go` +- Services (business logic): + - `web/service/inbound.go` + - `web/service/server.go` + - `web/service/setting.go` + - `web/service/xray.go` + - `web/service/xray_setting.go` + - `web/service/outbound.go` + - `web/service/tgbot.go` + - `web/service/warp.go` +- Subscription: + - `sub/sub.go` + - `sub/subController.go` + - `sub/subService.go` + - `sub/subJsonService.go` +- DB/models: + - `database/db.go` + - `database/model/model.go` + - `xray/client_traffic.go` +- Jobs: + - `web/job/*.go` +- Wiki snapshot used: + - `../3x-ui.wiki/*.md` + +--- + +## 14. Suggested maintenance routine + +Daily: +- Check Overview status and xray health. +- Check logs for abnormal auth attempts/errors. + +Weekly: +- Verify backup export/import viability. +- Review depleted/expired clients and cleanup. +- Review fail2ban and firewall rules. + +Monthly: +- Rotate sensitive secrets where feasible. +- Review panel path/port exposure and TLS validity. +- Re-audit settings after version updates. + +--- + +## 15. User-perspective panel operating guide + +This section is intentionally UI-first: what you see, what to click, and what happens. + +Version context: +- Labels below are based on your observed panel (`v2.8.10`, English language). +- If your language/theme differs, icon+position are usually stable even when text changes. + +## 15.1 Login screen (`/`) + +Visible items: +- `Username` input. +- `Password` input. +- Optional `Code` input (appears when 2FA is enabled). +- `Log In` button. +- Top-right settings button (theme + language). + +How to use: +1. Enter username and password. +2. If 2FA enabled, enter the one-time code. +3. Click `Log In`. +4. On success, panel opens `Overview`. + +Failure behavior: +- Wrong credentials show toast error. +- Login attempts are logged and may notify Telegram (if enabled). + +## 15.2 Sidebar navigation + +Main left menu items: +- `Overview` +- `Inbounds` +- `Panel Settings` +- `Xray Configs` +- `Log Out` + +Top utility item: +- `Theme` switch. + +How to use: +1. Use menu to move between modules. +2. `Log Out` clears your session and returns to login. + +## 15.3 Overview page (`/panel/`) + +What this page is for: +- Quick health check and service control. + +Typical cards/buttons: +- CPU/RAM/Swap/Storage cards. +- Xray status card (`Running`/`Stopped`) with `Stop` and `Restart`. +- Xray version control button. +- Management shortcuts: `Logs`, `Config`, `Backup`. +- System usage, speed, total traffic, connection counts, uptime. + +How to operate safely: +1. Check top warning banners first (security/config warnings). +2. Confirm Xray is `Running`. +3. Use `Restart` after major config edits. +4. Use `Logs` when users report failures. +5. Use `Backup` before risky changes. + +## 15.4 Inbounds page (`/panel/inbounds`) + +This is the main daily operations page. + +Top summary cards: +- Total Sent/Received. +- Total Usage. +- All-time Total Usage. +- Total Inbounds. +- Clients count. + +Toolbar buttons: +- `Add Inbound`: create a new listener. +- `General Actions`: mass operations across inbounds/clients. +- `Sync` icon: refresh table/state. +- Download icon/menu: export-related actions (depends on build/UI state). +- Filter toggle + Search box. + +Inbound row controls: +- Expand button: opens nested client details for that inbound. +- Row `...` menu: per-inbound actions. +- Enable switch: on/off without deleting row. + +Observed row `...` actions and intent: +- `Edit`: modify inbound protocol/stream/security params. +- `Add Client`: add one client under this inbound. +- `Add Bulk`: create many clients in one operation. +- `Reset Clients Traffic`: reset client traffic counters in this inbound. +- `Export All URLs`: copy/generate all client connection URLs. +- `Export All URLs - Subscription`: copy/generate subscription-style URLs. +- `Delete Depleted Clients`: remove clients that expired/exhausted traffic. +- `Export Inbound`: export inbound config object. +- `Reset Traffic`: reset inbound-level traffic usage. +- `Clone`: duplicate inbound config as a new inbound. +- `Delete`: remove the inbound. + +Recommended working pattern: +1. Create inbound with `Add Inbound`. +2. Immediately add at least one client. +3. Verify inbound switch is enabled. +4. Test with exported URL on a client app. +5. Monitor traffic growth and online status. + +## 15.5 Panel Settings page (`/panel/settings`) + +This page controls panel behavior and administration. + +Global buttons at top: +- `Save`: writes pending changes to DB. +- `Restart Panel`: applies panel-side changes. + +Critical rule: +- Save does not always fully apply runtime behavior until restart. + +Top tabs: +- `General` +- `Authentication` +- `Telegram Bot` +- `Subscription` + +### General tab + +Primary fields and what they do: +- `Listen IP`: bind panel server to specific interface. +- `Listen Domain`: optional host/domain validation. +- `Listen Port`: panel TCP port. +- `URI Path`: panel base path (`webBasePath`) must start/end with `/`. +- `Session Duration`: login persistence in minutes. +- `Pagination Size`: rows per page in inbounds table. +- `Language`: panel UI language. + +Common change flow: +1. Update field. +2. Click `Save`. +3. Click `Restart Panel`. +4. Reopen panel at updated URL/path if changed. + +### Authentication tab + +Sections: +- `Admin credentials`: + - Current username/password. + - New username/password. + - `Confirm` button. +- `Two-factor authentication`: + - Enable/disable/setup 2FA token flow. + +Change flow: +1. Fill current and new credentials. +2. Click `Confirm`. +3. Re-login with new credentials to verify. +4. Enable 2FA and test one full logout/login cycle. + +### Telegram Bot tab + +General section includes: +- `Enable Telegram Bot` switch. +- `Telegram Token`. +- `Admin Chat ID` (comma-separated possible). +- Bot language. + +Additional sections: +- Notifications behavior/timing. +- Proxy and API server options. + +Use case flow: +1. Enable switch. +2. Paste token from BotFather. +3. Add your chat ID(s). +4. Save and restart panel. +5. Trigger a test action (e.g., login notification/backup) and verify receipt. + +### Subscription tab + +Core controls: +- `Subscription Service` switch. +- `JSON Subscription` switch. +- `Listen IP`, `Listen Domain`, `Listen Port`. +- `URI Path` (link endpoint path, e.g. `/sub/`). + +Common secure setup: +1. Enable subscription. +2. Set non-default path(s). +3. Configure domain/certificates. +4. Save + restart. +5. Validate link endpoint and (if enabled) JSON endpoint. + +## 15.6 Xray Configs page (`/panel/xray`) + +Global buttons at top: +- `Save`: persist template/config changes. +- `Restart Xray`: apply xray runtime changes. + +Critical rule: +- Most xray config edits need both Save and Restart Xray to be active. + +Top tabs: +- `Basics` +- `Routing Rules` +- `Outbounds` +- `Reverse` +- `Balancers` +- `DNS` +- `Advanced` + +### Basics + +What to change here: +- General runtime strategy fields. +- Log/statistics behavior. +- `Outbound Test URL` used by outbound tests. + +When to use: +- Initial deployment cleanup. +- Debugging route and DNS behavior. + +### Routing Rules + +What it controls: +- Match conditions and outbound target per rule. + +How to use: +1. Add rule. +2. Set match condition (domain/ip/network/etc.). +3. Select outbound tag destination. +4. Save + restart Xray. +5. Validate by testing target domains/services. + +### Outbounds + +Common controls: +- Add outbound. +- WARP creation/registration. +- Test outbound connectivity. +- Outbound traffic table and reset actions. + +How to use: +1. Add outbound with valid protocol details. +2. Use test action to verify connectivity/latency. +3. Attach routing rule to actually send traffic there. + +### Reverse + +Purpose: +- Reverse proxy structures in Xray config. + +Use only when needed: +- More advanced topologies; easy to misconfigure. + +### Balancers + +Purpose: +- Group outbounds and balance traffic by strategy. + +Practical note: +- Set clear tags and test routes before production use. + +### DNS + +Purpose: +- Built-in DNS behavior for Xray. +Practical note: +- DNS changes can impact all traffic patterns; test carefully. + +### Advanced + +Purpose: +- Raw template editing for full-control scenarios. + +Safe editing workflow: +1. Export/backup current config first. +2. Make small incremental changes. +3. Save. +4. Restart Xray. +5. Check logs immediately for parse/runtime errors. + +## 15.7 Security alert banner behavior + +When shown, it is actionable. Common warnings: +- No TLS for panel. +- Default panel port/path. +- Default subscription path. + +Treat these as high-priority hardening tasks, not cosmetic notices. + +## 15.8 Save/Restart behavior quick table + +- Inbounds/client edits: + - Usually immediate DB change. + - Runtime update via API/restart logic; verify with status/logs. +- Panel settings edits: + - Save required. + - Often requires `Restart Panel`. +- Xray config edits: + - Save required. + - Usually requires `Restart Xray`. + +## 15.9 “What to click when” quick recipes + +Add a user to existing inbound: +1. `Inbounds` -> row `...` -> `Add Client`. +2. Fill client limits/expiry. +3. Save. +4. Export URL and test. + +Disable compromised client fast: +1. `Inbounds` -> expand row. +2. Locate client. +3. Disable/delete client. +4. Confirm in online/last-online views. + +Rotate panel URL path: +1. `Panel Settings` -> `General` -> `URI Path`. +2. Enter random path ending `/`. +3. Save -> Restart Panel. +4. Reconnect using new URL. + +Recover from bad xray edit: +1. `Xray Configs` -> use defaults/reset path. +2. Save. +3. Restart Xray. +4. Check logs and overview status. + +## 15.10 User mistakes to avoid + +- Editing many settings at once without intermediate tests. +- Forgetting restart after Save. +- Leaving default path/port. +- Enabling Telegram bot but exposing token carelessly. +- Using Advanced tab without backup. + +--- + +## 16. Revision metadata + +- Document generated: 2026-02-18 (local time). +- Based on repo: `workspace/open-source/3x-ui` (local main). +- Based on wiki commit: `6408b1c` in local clone `workspace/open-source/3x-ui.wiki`. + +--- + +## 17. Live instance addendum (practical operations and standards) + +This section captures validated behavior from hands-on operations in a live 3x-ui panel session. + +### 17.1 Client management reality: “single place” vs “inbound-scoped” + +Important model: +- In 3x-ui, clients are created under inbounds. +- There is no native global user object automatically attached to all inbounds. +- Expiry/traffic/IP-limit are set per client entry inside each inbound. + +Practical way to manage “as one user”: +1. Reuse one stable identifier (`email`) across all inbounds for that user. +2. Optionally reuse same UUID where protocol/client behavior allows (commonly VLESS workflows). +3. Update quota/expiry on each inbound client entry. +4. Use client traffic/search views/API by `email` to track usage consistently. + +### 17.2 API endpoints to automate cross-inbound client ops + +Useful API patterns for centralized tooling: +- `POST /panel/api/inbounds/addClient` +- `POST /panel/api/inbounds/updateClient/:clientId` +- `GET /panel/api/inbounds/getClientTraffics/:email` + +Recommended automation pattern: +- Keep one “master user policy” (days, GB, ip-limit). +- Apply the policy to a list of inbound IDs via API. +- Use `email` as the logical cross-inbound key. + +### 17.3 Inbound naming standard (recommended) + +Use deterministic names: +- `----` + +Examples: +- `vless-reality-tcp-443-main` +- `vless-reality-tcp-8443-alt` +- `vless-tcp-http-18080-test` + +Why this works: +- Immediate readability in crowded tables. +- Faster incident response (role and port visible). +- Lower chance of editing the wrong inbound. + +### 17.4 Safe cleanup order for production panels + +Apply changes in this order: +1. Rename remarks first (zero functional risk). +2. Verify rows after each save (port/protocol/security unchanged). +3. Only then change functional settings (security/transport/sni/etc.) in isolated steps. +4. Keep one known-good main inbound untouched while testing alternatives. + +### 17.5 Current validated inbound organization pattern + +Observed clean structure pattern: +- Main production inbound on 443 with Reality. +- Secondary fallback Reality inbound on alternate TLS-like port (e.g. 8443). +- Separate explicitly-labeled test inbound for experiments. + +Operational guidance: +- Keep test inbound clearly labeled (`-test`) and isolated from production users. +- Remove or disable test inbound when no longer needed. +- Avoid mixing experimental header/obfuscation settings into production remarks. + +### 17.6 Security and control-plane warning handling + +If panel shows connection-security warning (no TLS on panel access): +- Treat as a control-plane hardening task. +- Do not enter sensitive credentials over untrusted links. +- Prefer TLS-terminated panel access path as soon as possible. + +### 17.7 Non-breaking tuning rules for existing inbounds + +For active user inbounds: +- Do not change port/security/transport unexpectedly. +- Do not rotate keys/shortIds without a migration window. +- Do not disable inbounds with active clients before notification. + +For cleanup that is safe anytime: +- Rename remarks. +- Standardize client email/label patterns. +- Review per-client quota/expiry/IP-limit consistency. + +--- + +## 18. Custom feature: centralized client management (implemented) + +This repository now includes a **client-first management layer** that stays compatible with 3x-ui inbound-scoped architecture. + +### 18.1 What was added + +- New panel page: `/panel/clients` +- New sidebar menu item: `Clients Center` +- New authenticated API group: + - `GET /panel/api/clients/list` + - `GET /panel/api/clients/inbounds` + - `POST /panel/api/clients/add` + - `POST /panel/api/clients/update/:id` + - `POST /panel/api/clients/del/:id` +- New database models: + - `master_clients` (central profile: name/quota/expiry/ip-limit/enable/comment) + - `master_client_inbounds` (mapping master client -> assigned inbounds + underlying assignment email/client key) + +### 18.2 Architectural approach + +Why this design: +- Native 3x-ui clients are inbound-scoped. +- Core traffic/ip logic is email-centric and inbound-linked. +- A deep core rewrite is high-risk. + +Implemented solution: +- Keep native inbound clients as the execution layer. +- Add master client profiles as orchestration layer. +- On assignment, create/update/remove corresponding inbound clients automatically. + +### 18.3 User workflow now + +1. Open `Clients Center`. +2. Create a master client with: + - Display name + - Email prefix + - Traffic quota (GB) + - Expiry date/time + - IP limit + - Enabled flag + - Comment +3. Select one or more inbounds. +4. Save. + +Result: +- Assigned inbound client records are created and kept in sync from this master profile. +- Updating a master client syncs limits/expiry/enabled/comment to all assigned inbounds. +- Removing assignments detaches from those inbounds. + +### 18.4 Important behavior details + +- Assignment emails are generated uniquely per inbound to stay compatible with existing uniqueness checks. +- The feature supports multi-client protocols (VLESS/VMESS/Trojan/Shadowsocks). +- If removing a client would leave an inbound with zero clients, detach can fail by design (safety guard inherited from inbound logic). + +### 18.5 Stability improvement included + +A panic-safe guard was added in Xray API client methods (`AddInbound`, `DelInbound`, `AddUser`, `RemoveUser`) to return a clean error when handler service is not initialized, instead of nil-pointer panic. + +### 18.6 Local validation performed + +Environment: +- Local run with SQLite (`XUI_DB_FOLDER` custom path), custom log folder, panel on local port. + +Validated: +- Login works. +- `GET /panel/api/clients/list` works. +- `GET /panel/api/clients/inbounds` works. +- `POST /panel/api/clients/add` works. +- `POST /panel/api/clients/update/:id` works (including inbound assignment sync). +- `POST /panel/api/clients/del/:id` works. +- Browser UI route `/panel/clients` renders. +- UI create flow works (form -> save -> row visible in table). + +### 18.7 Files touched for this feature + +- `database/model/model.go` +- `database/db.go` +- `web/service/client_center.go` +- `web/controller/client_center.go` +- `web/controller/api.go` +- `web/controller/xui.go` +- `web/html/component/aSidebar.html` +- `web/html/clients.html` +- `xray/api.go` + +### 18.8 Future hardening suggestions + +- Add explicit role/permission checks for client-center APIs in multi-admin scenarios. +- Add audit logs for master-client create/update/delete operations. +- Add automated integration tests for add/update/remove assignment scenarios. + +--- + +## 19. Dev workflow additions (implemented) + +This section captures engineering workflow additions made during implementation. + +### 19.1 Air live-reload setup + +Added: +- `.air.toml` + +Behavior: +- Builds dev binary to `tmp/bin/3x-ui-dev`. +- Runs panel with: + - `XUI_DB_FOLDER=$PWD/tmp/db` + - `XUI_LOG_FOLDER=$PWD/tmp/logs` + - `XUI_DEBUG=true` +- Auto-creates `tmp/db`, `tmp/logs`, `tmp/bin`. +- Initializes fresh local DB automatically (admin/admin on port 2099) if DB does not exist. + +Run: +1. `air -c .air.toml` +2. Open `http://127.0.0.1:2099` +3. Login `admin/admin` (fresh dev DB case) + +### 19.2 Justfile command setup + +Added: +- `justfile` + +Common commands: +- `just help` +- `just ensure-tmp` +- `just init-dev` +- `just run` +- `just air` +- `just build` +- `just check` +- `just api-login` +- `just api-clients-inbounds` +- `just api-clients-list` +- `just clean-tmp` + +All commands are scoped to local `tmp/` so production paths are untouched. + +### 19.3 Local test execution summary + +Validated locally after implementation: +- Build success with `go build ./...`. +- App starts with local sqlite paths under `tmp/`. +- New route `/panel/clients` renders. +- New APIs respond correctly with authenticated session. +- Client-center create/update/delete flows work end-to-end. +- Assignment sync between master clients and inbounds works. + +### 19.4 Stability fix included during testing + +In local test conditions where Xray handler client may be unavailable, API operations previously could panic. +Fix applied in `xray/api.go`: +- Guard `AddInbound`, `DelInbound`, `AddUser`, `RemoveUser` against nil handler service client. +- Return explicit error instead of panic. + +--- + +## 20. Guide split map (new focused docs) + +This monolithic document is now complemented by focused files under: +- `docs/panel-guide/` + +Index: +- `docs/panel-guide/README.md` +- `docs/panel-guide/01-overview-and-architecture.md` +- `docs/panel-guide/02-pages-and-operations.md` +- `docs/panel-guide/03-api-and-cli-reference.md` +- `docs/panel-guide/04-security-and-hardening.md` +- `docs/panel-guide/05-client-management-model.md` +- `docs/panel-guide/06-custom-client-center-feature.md` +- `docs/panel-guide/07-dev-and-testing-workflow.md` +- `docs/panel-guide/08-protocols-and-config-analysis.md` +- `docs/panel-guide/09-xray-protocol-reference.md` +- `docs/panel-guide/10-glossary-and-concepts.md` +- `docs/panel-guide/11-troubleshooting-runbook.md` +- `docs/panel-guide/12-change-management-and-rollout.md` +- `docs/panel-guide/13-feature-file-map-and-decision-log.md` +- `docs/panel-guide/99-session-context-transfer-2026-02-18.md` + +Use those files for day-to-day operations and implementation reference. diff --git a/docs/panel-guide/01-overview-and-architecture.md b/docs/panel-guide/01-overview-and-architecture.md new file mode 100644 index 00000000..9a056850 --- /dev/null +++ b/docs/panel-guide/01-overview-and-architecture.md @@ -0,0 +1,81 @@ +# 01. Overview and Architecture + +## What 3x-ui is + +3x-ui is a control panel around Xray-core for: +- Inbound and client management +- Quota/expiry/statistics +- Advanced Xray config/routing editing +- Operational actions (restart, logs, backup/import/export) +- Optional subscription and Telegram integrations + +## Core runtime parts + +- Web panel server: `web/web.go` +- Subscription server: `sub/sub.go` +- Xray integration service: `web/service/xray.go` +- Binary entrypoint: `main.go` + +## Data layer + +Default storage is SQLite via GORM. +Models include: +- `User` +- `Inbound` +- `Setting` +- `OutboundTraffics` +- `InboundClientIps` +- `xray.ClientTraffic` +- `HistoryOfSeeders` +- Custom extension: `MasterClient`, `MasterClientInbound` + +Files: +- `database/db.go` +- `database/model/model.go` +- `xray/client_traffic.go` + +## Auth/session model + +- Cookie session with secret from DB settings +- `/panel/*` requires login +- `/panel/api/*` also requires login +- Unauthorized API requests are intentionally hidden with 404 behavior + +Files: +- `web/controller/base.go` +- `web/controller/api.go` +- `web/session/session.go` + +## Background jobs and periodic logic + +Cron-based tasks include: +- Xray process health checks +- Traffic collection from Xray +- Auto disable/renew logic +- Client IP checks and cleanup +- Optional LDAP and Telegram jobs + +Files: +- `web/web.go` +- `web/job/*.go` +- `web/service/inbound.go` + +## URL topology + +UI: +- `/` +- `/panel/` +- `/panel/inbounds` +- `/panel/clients` (custom) +- `/panel/settings` +- `/panel/xray` + +API: +- `/panel/api/inbounds/*` +- `/panel/api/server/*` +- `/panel/api/clients/*` (custom) +- `/panel/xray/*` +- `/panel/setting/*` + +Subscription: +- Dynamic from settings (`subPath`, `subJsonPath`) diff --git a/docs/panel-guide/02-pages-and-operations.md b/docs/panel-guide/02-pages-and-operations.md new file mode 100644 index 00000000..663f17e9 --- /dev/null +++ b/docs/panel-guide/02-pages-and-operations.md @@ -0,0 +1,92 @@ +# 02. Pages and Operations + +## Overview page (`/panel/`) + +Primary purpose: +- Server and Xray health view +- Quick operational actions + +Typical actions: +- Restart/stop Xray +- View logs +- Check utilization and throughput + +## Inbounds page (`/panel/inbounds`) + +Primary purpose: +- Manage listeners and protocol endpoints +- Manage inbound-scoped clients + +Core operations: +- Add/edit/delete inbound +- Enable/disable inbound +- Add/edit/delete client +- Bulk add clients +- Reset traffic (client/inbound/global) +- Export URLs/subscription data +- Clone inbound + +Operational best practice: +1. Rename/label first. +2. Change one technical setting at a time. +3. Keep one known-good inbound untouched while testing. + +## Clients page (`/panel/clients`) - custom extension + +Primary purpose: +- Master client profile management +- Multi-inbound assignment orchestration + +Core operations: +- Create master client (name, prefix, quota, expiry, ip limit, enabled, comment) +- Assign one or more inbounds +- Update profile and sync assigned inbounds +- Delete master client and remove assignments + +## Panel Settings (`/panel/settings`) + +Tabs: +- General +- Authentication +- Telegram Bot +- Subscription + +Critical controls: +- Listen IP/domain/port +- Base path +- Session duration +- Admin credentials and 2FA + +## Xray Configs (`/panel/xray`) + +Tabs: +- Basics +- Routing Rules +- Outbounds +- Reverse +- Balancers +- DNS +- Advanced + +Safety workflow: +1. Backup/export first. +2. Small changes only. +3. Save and restart Xray when needed. +4. Check logs immediately. + +## Frequent operations checklist + +- Add new inbound safely: + 1. Create inbound with clear remark and tested config + 2. Add one test client + 3. Verify connectivity + 4. Roll out to users + +- Rotate admin credentials: + 1. Change in Authentication tab + 2. Re-login and confirm + +- Recover from bad Xray config: + 1. Restore known-good template + 2. Restart Xray + 3. Verify logs/status diff --git a/docs/panel-guide/03-api-and-cli-reference.md b/docs/panel-guide/03-api-and-cli-reference.md new file mode 100644 index 00000000..54061bc1 --- /dev/null +++ b/docs/panel-guide/03-api-and-cli-reference.md @@ -0,0 +1,73 @@ +# 03. API and CLI Reference + +## API auth + +- Session cookie required. +- API group is mounted under `/panel/api`. +- Unauthenticated API calls are hidden (404 behavior). + +## Inbounds API (main set) + +Examples: +- `GET /panel/api/inbounds/list` +- `GET /panel/api/inbounds/get/:id` +- `POST /panel/api/inbounds/add` +- `POST /panel/api/inbounds/update/:id` +- `POST /panel/api/inbounds/del/:id` +- `POST /panel/api/inbounds/addClient` +- `POST /panel/api/inbounds/updateClient/:clientId` +- `POST /panel/api/inbounds/:id/delClient/:clientId` +- `GET /panel/api/inbounds/getClientTraffics/:email` + +Controller file: +- `web/controller/inbound.go` + +## Server API + +Examples: +- `GET /panel/api/server/status` +- `POST /panel/api/server/restartXrayService` +- `POST /panel/api/server/stopXrayService` +- `POST /panel/api/server/logs/:count` + +Controller file: +- `web/controller/server.go` + +## Custom Clients API (implemented) + +- `GET /panel/api/clients/list` +- `GET /panel/api/clients/inbounds` +- `POST /panel/api/clients/add` +- `POST /panel/api/clients/update/:id` +- `POST /panel/api/clients/del/:id` + +Files: +- `web/controller/client_center.go` +- `web/service/client_center.go` + +## Panel and Xray settings APIs + +- `/panel/setting/*` +- `/panel/xray/*` + +Files: +- `web/controller/setting.go` +- `web/controller/xray_setting.go` + +## CLI usage + +Binary supports: +- `run` +- `setting` +- `migrate` + +Examples: +```bash +go run . setting -port 2099 -username admin -password admin +go run . run +``` + +Admin shell scripts: +- `x-ui.sh` +- `install.sh` +- `update.sh` diff --git a/docs/panel-guide/04-security-and-hardening.md b/docs/panel-guide/04-security-and-hardening.md new file mode 100644 index 00000000..7a69075f --- /dev/null +++ b/docs/panel-guide/04-security-and-hardening.md @@ -0,0 +1,57 @@ +# 04. Security and Hardening + +## Immediate high-priority items + +1. Enable TLS for panel access. +2. Change default/guessable panel base path. +3. Change default subscription paths. +4. Use strong admin password + 2FA. +5. Restrict panel listen IP where possible. + +## Operational hardening + +- Keep backups of DB before major changes. +- Use staged config changes, not bulk edits. +- Keep one known-good inbound active. +- Review logs after each restart. + +## Control-plane warning handling + +If panel shows security warning banner: +- Treat as real risk, not cosmetic. +- Do not expose panel publicly without TLS. + +## Inbound safety rules + +For active user inbounds: +- Avoid sudden port/security/transport changes. +- Avoid key/shortId rotation without migration window. +- Avoid disable/delete on active inbounds without user communication. + +Safe changes anytime: +- Remark/naming cleanup +- Client naming consistency +- Non-functional labeling and grouping + +## Current naming standard recommendation + +Use: +- `----` + +Examples: +- `vless-reality-tcp-443-main` +- `vless-reality-tcp-8443-alt` +- `vless-tcp-http-18080-test` + +## Suggested maintenance cadence + +Daily: +- Check Xray state, error logs, traffic anomalies + +Weekly: +- Review depleted/disabled clients +- Validate backup and restore path + +Monthly: +- Rotate sensitive paths/credentials if needed +- Review exposed interfaces and firewall rules diff --git a/docs/panel-guide/05-client-management-model.md b/docs/panel-guide/05-client-management-model.md new file mode 100644 index 00000000..93187e97 --- /dev/null +++ b/docs/panel-guide/05-client-management-model.md @@ -0,0 +1,46 @@ +# 05. Client Management Model (Native 3x-ui) + +## Native model truth + +3x-ui is inbound-first. +- Clients are stored inside each inbound. +- There is no native global user object that auto-attaches to multiple inbounds. + +## Practical centralized behavior (without custom feature) + +You can simulate central management by: +1. Reusing the same user identifier pattern (email/name). +2. Applying same policy per inbound client (quota/expiry/ip limit). +3. Automating updates with panel APIs. + +## Why model works this way + +Core internals are tied to inbound-scoped records: +- Client traffic links to inbound and email +- Client IP tracking is email-based +- Inbound settings embed client arrays + +Key files: +- `web/service/inbound.go` +- `xray/client_traffic.go` +- `database/model/model.go` + +## Per-client controls + +For each inbound client you can set: +- `totalGB` +- `expiryTime` +- `limitIp` +- `enable` +- `comment` +- (protocol-specific identity fields) + +## Automation endpoints commonly used + +- `POST /panel/api/inbounds/addClient` +- `POST /panel/api/inbounds/updateClient/:clientId` +- `GET /panel/api/inbounds/getClientTraffics/:email` + +## Operational recommendation + +Use policy templates (for example 30d/100GB, 30d/300GB, unlimited) and apply them consistently. diff --git a/docs/panel-guide/06-custom-client-center-feature.md b/docs/panel-guide/06-custom-client-center-feature.md new file mode 100644 index 00000000..20797f68 --- /dev/null +++ b/docs/panel-guide/06-custom-client-center-feature.md @@ -0,0 +1,68 @@ +# 06. Custom Client-Center Feature + +## Goal + +Add a true operator-friendly client-first page while preserving 3x-ui compatibility and minimizing break risk. + +## Implemented design + +A new orchestration layer was added: +- Master client profile table +- Master client <-> inbound assignment mapping table +- Sync logic that creates/updates/removes native inbound clients automatically + +## Added backend pieces + +Models: +- `MasterClient` +- `MasterClientInbound` + +Service: +- `web/service/client_center.go` + +Controller/API: +- `web/controller/client_center.go` +- Mounted in `web/controller/api.go` under `/panel/api/clients/*` + +## Added frontend pieces + +- Route: `/panel/clients` +- Page: `web/html/clients.html` +- Sidebar item: `web/html/component/aSidebar.html` + +## API surface + +- `GET /panel/api/clients/list` +- `GET /panel/api/clients/inbounds` +- `POST /panel/api/clients/add` +- `POST /panel/api/clients/update/:id` +- `POST /panel/api/clients/del/:id` + +## Behavior notes + +- Supports multi-client protocols (vless/vmess/trojan/shadowsocks). +- Assignment email is generated uniquely per inbound. +- Master profile fields are synced to assigned inbound client entries. +- Detach can fail if an inbound would be left with zero clients (inherited safety rule). + +## Stability fix included + +`xray/api.go` now guards nil handler client and returns clear errors in: +- `AddInbound` +- `DelInbound` +- `AddUser` +- `RemoveUser` + +This prevents nil-pointer panics during local/dev conditions. + +## Files touched (feature) + +- `database/model/model.go` +- `database/db.go` +- `web/service/client_center.go` +- `web/controller/client_center.go` +- `web/controller/api.go` +- `web/controller/xui.go` +- `web/html/clients.html` +- `web/html/component/aSidebar.html` +- `xray/api.go` diff --git a/docs/panel-guide/07-dev-and-testing-workflow.md b/docs/panel-guide/07-dev-and-testing-workflow.md new file mode 100644 index 00000000..d276e903 --- /dev/null +++ b/docs/panel-guide/07-dev-and-testing-workflow.md @@ -0,0 +1,66 @@ +# 07. Dev and Testing Workflow + +## Local dev philosophy + +Keep all local mutable state inside repo `tmp/`: +- `tmp/db` +- `tmp/logs` +- `tmp/bin` +- `tmp/cookies` + +## Fast dev run (without air) + +```bash +mkdir -p tmp/db tmp/logs +XUI_DB_FOLDER="$PWD/tmp/db" XUI_LOG_FOLDER="$PWD/tmp/logs" XUI_DEBUG=true \ + go run . setting -port 2099 -username admin -password admin +XUI_DB_FOLDER="$PWD/tmp/db" XUI_LOG_FOLDER="$PWD/tmp/logs" XUI_DEBUG=true \ + go run . run +``` + +Panel: +- URL: `http://127.0.0.1:2099` +- Login: `admin/admin` (fresh DB) + +## Air live-reload + +Config file: +- `.air.toml` + +Run: +```bash +air -c .air.toml +``` + +Behavior: +- Builds to `tmp/bin/3x-ui-dev` +- Runs with tmp db/log env vars +- Bootstraps fresh DB credentials/port when DB absent + +## Justfile commands + +- `just init-dev` +- `just run` +- `just air` +- `just build` +- `just check` +- `just api-login` +- `just api-clients-inbounds` +- `just api-clients-list` +- `just clean-tmp` + +## Validation checklist for custom clients feature + +1. Login and open `/panel/clients`. +2. Create master client with one inbound assignment. +3. Confirm row appears in clients table. +4. Confirm assignment visible in list API. +5. Update policy fields and assignment set. +6. Confirm synced result in list API. +7. Delete master client and confirm list is empty. + +## Notes from local test run + +- Build and startup validated on local SQLite paths. +- API + UI flows for custom clients feature validated. +- Xray API nil-client panic path was fixed and replaced with explicit errors. diff --git a/docs/panel-guide/08-protocols-and-config-analysis.md b/docs/panel-guide/08-protocols-and-config-analysis.md new file mode 100644 index 00000000..d435489c --- /dev/null +++ b/docs/panel-guide/08-protocols-and-config-analysis.md @@ -0,0 +1,93 @@ +# 08. Protocols and Config Analysis (Session Transfer) + +## Scope + +This file captures protocol and configuration understanding gathered during the session, including practical guidance for creating client-similar inbound behavior in 3x-ui. + +## Xray protocol framing + +Common protocols in this panel context: +- `vless` +- `vmess` +- `trojan` +- `shadowsocks` + +Important distinction: +- Protocol defines identity/auth semantics. +- Transport/stream settings define wire behavior (tcp/ws/grpc/http-like headers/reality/tls/etc). + +## Reality summary (operational) + +Reality is used as a TLS-camouflage security layer in modern Xray setups (commonly with VLESS). + +Typical panel representation: +- Protocol: `vless` +- Network: `tcp` +- Security marker: `Reality` + +Operational notes: +- It is sensitive to keypair, shortIds, target/serverName settings. +- Changing Reality material on active inbounds can break all existing clients immediately. +- Use staged migration for key/shortId rotations. + +## XHTTP / HTTP-like obfuscation context + +In practical user terms (for this session), “similar config from client perspective” meant creating an inbound with: +- `vless` + `tcp` +- No TLS/Reality on that specific test inbound +- HTTP header camouflage (request path/host) + +Implemented test-like inbound pattern in panel: +- Remark pattern after cleanup: `vless-tcp-http-18080-test` +- Port: `18080` +- HTTP obfuscation with `Host = speedtest.com`, `Path = /` + +## Analysis of provided sample JSON configs + +Two provided JSON samples were client-side local Xray configs, not panel server-side inbound objects. + +High-level structure observed: +- Local inbounds: + - SOCKS and HTTP on loopback + LAN IP (`10808`, `10809`) + - Additional direct SOCKS inbound (`10820`) for bypass route +- Outbounds: + - Main `vless` outbound with `tcp` + HTTP header disguise + - `direct` (freedom) + - `block` (blackhole) +- Routing: + - Domain/IP direct lists + - Special rules for DNS endpoints and direct inbound tag +- DNS: + - DoH to Cloudflare and Google with domain-based resolver split + +Interpretation: +- These configs are client aggregator profiles routing app traffic through a remote VLESS endpoint. +- To create “similar behavior” on your 3x-ui server, we focused on matching protocol/transport/obfuscation characteristics in inbound settings (not mirroring client local socks/http listener topology). + +## Can similar inbounds be created in your instance? + +Yes. Practical answer from this session: +- Similar client-facing server profile can be created in 3x-ui. +- Exact local client config object is not a server inbound; it must be translated to compatible inbound parameters. + +## Safe conversion rules used + +1. Preserve existing production inbounds (`443/8443 Reality`) to avoid breakage. +2. Add separate test inbound for obfuscated TCP behavior. +3. Use explicit remark naming to avoid accidental edits. +4. Verify saved settings from modal after creation. + +## Naming standard adopted + +- `vless-reality-tcp-443-main` +- `vless-reality-tcp-8443-alt` +- `vless-tcp-http-18080-test` + +Format: +- `---` (or close equivalent used here) + +## Practical recommendations + +- Keep Reality as production path when already stable for clients. +- Keep obfuscation test profiles isolated and clearly marked `-test`. +- Do not mix experimental configs into main inbound until tested and monitored. diff --git a/docs/panel-guide/09-xray-protocol-reference.md b/docs/panel-guide/09-xray-protocol-reference.md new file mode 100644 index 00000000..d5011273 --- /dev/null +++ b/docs/panel-guide/09-xray-protocol-reference.md @@ -0,0 +1,141 @@ +# 09. Xray Protocol Reference for 3x-ui + +## Scope + +This document captures protocol-level understanding relevant to 3x-ui operations and implementation decisions. + +Important: +- It is an operator-focused reference, not full wire-spec replacement for each protocol. +- Always validate against current upstream Xray docs before major production migrations. + +## Protocols supported in current model/constants + +From `database/model/model.go` protocol constants: +- `vmess` +- `vless` +- `trojan` +- `shadowsocks` +- `http` +- `mixed` +- `tunnel` +- `wireguard` + +## Concept model + +In Xray/3x-ui, configuration is split into: +1. Protocol/auth layer (vless/vmess/trojan/ss/etc) +2. Transport/stream layer (`tcp`, `ws`, `grpc`, etc) +3. Security layer (`none`, `tls`, `reality`) +4. Routing/DNS policy layer + +Most operator mistakes happen when these layers are mixed conceptually. + +## VLESS + +Characteristics: +- Modern lightweight protocol (common choice with Reality). +- Client identity via UUID (`id`) and optional `flow` in specific TLS/XTLS contexts. + +Typical production pairings: +- `vless + tcp + reality` +- `vless + ws + tls` +- `vless + grpc + tls` + +Operational notes: +- Treat UUID/flow/security migration as coordinated change. +- Reality key material/shortIds are break-sensitive. + +## VMESS + +Characteristics: +- Legacy/common protocol with UUID identity and security parameters. + +Operational notes: +- Can still work well, but many modern deployments prefer VLESS. +- Migration VMESS->VLESS should be staged as full client profile replacement. + +## Trojan + +Characteristics: +- Password-based identity model. +- Often used with TLS-like camouflage patterns. + +3x-ui key behavior: +- Client key for updates/deletes is password for trojan path in service logic. + +## Shadowsocks + +Characteristics: +- Cipher/password model. +- Includes classic and 2022-style cipher handling paths in Xray integration. + +3x-ui key behavior: +- Email plays tracking role in panel logic even for SS clients. +- For SS, client-key handling differs from UUID-based protocols. + +## WireGuard / Tunnel / HTTP / Mixed + +These exist in model support and can appear in inbound definitions depending on build/version/UI exposure. + +Operational recommendation: +- Use these only when your use-case explicitly requires them. +- Keep your mainstream user path on one well-tested protocol family. + +## Reality + +Reality is a security/camouflage mode (commonly with VLESS TCP). + +Key operator concerns: +- Public key/private key, shortIds, destination/serverName consistency. +- Any mismatch causes hard connect failures. +- Keep a fallback inbound during rotations. + +## XHTTP / HTTP-style obfuscation context + +In this session context, “xhttp-like/client-similar behavior” referred to HTTP header camouflage over TCP-style transport. + +Implemented test pattern: +- `vless-tcp-http-18080-test` +- Request header host and path set for camouflage testing. + +Guidance: +- Keep obfuscation experiments in clearly marked test inbounds. +- Do not blend experimental obfuscation into main production inbound without staged rollout. + +## Routing and DNS interplay (critical) + +Protocol success can still fail at policy layer due to: +- DNS resolver split policies +- Domain/IP route overrides +- Direct/proxy exceptions + +Always validate: +1. Inbound reaches server +2. Auth/security valid +3. DNS route correct +4. Outbound path available + +## Practical compatibility checklist before creating a new inbound type + +1. Confirm protocol support in current panel build. +2. Confirm client app supports same protocol+transport+security combo. +3. Create isolated test inbound first. +4. Add one test client and verify handshake/traffic. +5. Roll out with explicit naming and fallback path. + +## Naming convention reminder + +Use descriptive remarks to prevent operator error: +- `----` + +Examples used in session: +- `vless-reality-tcp-443-main` +- `vless-reality-tcp-8443-alt` +- `vless-tcp-http-18080-test` + +## Where to cross-check in codebase + +- Protocol constants: `database/model/model.go` +- Inbound/client update logic: `web/service/inbound.go` +- Xray add/remove user and inbound operations: `xray/api.go` +- Xray config assembly: `web/service/xray.go` diff --git a/docs/panel-guide/10-glossary-and-concepts.md b/docs/panel-guide/10-glossary-and-concepts.md new file mode 100644 index 00000000..1c2afad5 --- /dev/null +++ b/docs/panel-guide/10-glossary-and-concepts.md @@ -0,0 +1,61 @@ +# 10. Glossary and Concepts + +## Core terms + +- Inbound: + Server-side listener definition (protocol, port, stream/security settings, and clients). + +- Outbound: + Egress route object used by routing policy. + +- Client (native 3x-ui): + Per-inbound user entry embedded under inbound settings. + +- Master Client (custom feature): + Central profile that syncs policy to assigned inbound clients. + +- Assignment: + Link between one master client and one inbound (custom table-backed mapping). + +- Stream/Transport: + Wire transport settings (tcp/ws/grpc/etc) independent from protocol identity. + +- Security layer: + `none`, `tls`, or `reality` depending on stream configuration. + +- Sniffing: + Metadata/domain extraction behavior for routing logic. + +- Traffic reset: + Reset policy cycle for usage counters. + +- `needRestart`: + Service flag indicating runtime API update failed or restart is required for consistency. + +## Data model concepts + +- `inbounds.settings` stores client arrays as JSON. +- `xray.ClientTraffic` stores usage/state counters per tracked client email. +- `InboundClientIps` stores email-to-IP observations. +- Custom extension adds: + - `MasterClient` + - `MasterClientInbound` + +## Control plane vs data plane + +- Control plane: + Panel UI/API, DB, settings, orchestration jobs. + +- Data plane: + Xray runtime handling proxy traffic. + +Operationally: +- A panel save may succeed in DB while runtime application may require restart. +- Always verify both DB state and runtime state for critical changes. + +## Practical mental model + +1. Configure inbound protocol/transport/security. +2. Attach clients (native or via master sync). +3. Validate routing/DNS/outbound path. +4. Confirm runtime apply and traffic counters. diff --git a/docs/panel-guide/11-troubleshooting-runbook.md b/docs/panel-guide/11-troubleshooting-runbook.md new file mode 100644 index 00000000..a72c8de3 --- /dev/null +++ b/docs/panel-guide/11-troubleshooting-runbook.md @@ -0,0 +1,84 @@ +# 11. Troubleshooting Runbook + +## Fast triage order + +1. Confirm panel reachability and login. +2. Check Xray running state on Overview. +3. Check recent panel logs and Xray logs. +4. Verify inbound enable state and port binding. +5. Verify client enabled/quota/expiry/IP limits. +6. Verify routing and DNS policy impact. + +## Common issues + +### Panel loads but auth/session fails + +Checks: +- Session settings and secret availability. +- Cookie persistence and base path correctness. + +Files: +- `web/web.go` +- `web/service/setting.go` + +### Inbound saved but traffic not flowing + +Checks: +- Runtime apply result (`needRestart` scenarios). +- Xray state and error logs. +- Transport/security mismatch with client app. + +Files: +- `web/service/inbound.go` +- `web/service/xray.go` + +### Clients unexpectedly disabled/depleted + +Checks: +- Auto disable/renew logic from periodic jobs. +- `totalGB`, `expiryTime`, reset behavior. + +Files: +- `web/service/inbound.go` +- `web/job/xray_traffic_job.go` + +### Assignment sync errors in custom clients feature + +Checks: +- Inbound protocol supports multi-client. +- Assignment detach is not removing last remaining client from inbound. +- Underlying inbound client key (id/password/email) still valid. + +Files: +- `web/service/client_center.go` +- `web/service/inbound.go` + +### Panic or 500 during Xray API interaction + +Current guard: +- `xray/api.go` now returns explicit error when handler client is nil. + +Action: +- Confirm Xray API availability and startup timing. + +## Local dev troubleshooting + +If app cannot write default paths: +- Use repo-local env: + - `XUI_DB_FOLDER=$PWD/tmp/db` + - `XUI_LOG_FOLDER=$PWD/tmp/logs` + +If dependency proxy blocks build: +- `GOPROXY=direct go build ./...` + +If login fails in fresh local DB: +- Run init: + - `go run . setting -port 2099 -username admin -password admin` + +## Evidence collection checklist + +Collect before major debugging: +1. Active inbounds list JSON. +2. Client traffic record snapshot. +3. Current panel settings export. +4. Recent xray log excerpts around failure time. diff --git a/docs/panel-guide/12-change-management-and-rollout.md b/docs/panel-guide/12-change-management-and-rollout.md new file mode 100644 index 00000000..69e61271 --- /dev/null +++ b/docs/panel-guide/12-change-management-and-rollout.md @@ -0,0 +1,53 @@ +# 12. Change Management and Rollout + +## Goal + +Provide low-risk patterns for introducing protocol/config/UI/backend changes in a running panel. + +## Safe rollout pattern + +1. Backup DB. +2. Add new config in parallel (do not replace old path immediately). +3. Validate with one test client. +4. Migrate a small user slice. +5. Monitor logs/latency/failure rate. +6. Complete migration and decommission old path. + +## For inbound/protocol changes + +Do first: +- Naming cleanup and explicit role labels. +- New test inbound with clear `-test` suffix. + +Do later: +- Security/transport rotations on production inbound. + +## For client policy changes + +- Apply policy in additive way. +- Prefer staged updates by user segment. +- Confirm no accidental disable due to quota/expiry mismatch. + +## For custom feature changes + +- Keep additive APIs; avoid breaking old endpoints. +- Feature-flag or route-gate where possible. +- Maintain backward compatibility with inbound-native operations. + +## Regression checklist + +After any significant change verify: +1. Login and panel navigation. +2. Inbounds list and edit flow. +3. Add/update/delete client flow. +4. Export URL/subscription flow. +5. Xray restart and log health. +6. Custom clients page CRUD + sync. + +## Rollback checklist + +1. Stop rollout. +2. Revert to known-good binary/config. +3. Restore DB backup if data mutation is root cause. +4. Re-validate panel and xray state. +5. Reintroduce change in smaller scope. diff --git a/docs/panel-guide/13-feature-file-map-and-decision-log.md b/docs/panel-guide/13-feature-file-map-and-decision-log.md new file mode 100644 index 00000000..28cfdc8c --- /dev/null +++ b/docs/panel-guide/13-feature-file-map-and-decision-log.md @@ -0,0 +1,61 @@ +# 13. Feature File Map and Decision Log + +## Why this exists + +To preserve implementation intent and reduce rediscovery cost when modifying the custom client-center extension. + +## Decision log (session) + +1. Decision: + Build client-center as orchestration layer instead of replacing inbound-native model. + + Reason: + Lower break risk with existing email/inbound-centric traffic and client logic. + +2. Decision: + Keep existing inbounds/client APIs intact and add new API namespace. + + Reason: + Backward compatibility for existing UI and operational scripts. + +3. Decision: + Add panic guards in Xray API integration points. + + Reason: + Improve resilience in dev/runtime states where handler client may be unavailable. + +## File map (custom extension) + +Data models: +- `database/model/model.go` + - `MasterClient` + - `MasterClientInbound` + +Migration registration: +- `database/db.go` + +Backend service: +- `web/service/client_center.go` + +Controller/API: +- `web/controller/client_center.go` +- `web/controller/api.go` (mounts `/panel/api/clients`) + +UI route and page: +- `web/controller/xui.go` (`/panel/clients`) +- `web/html/clients.html` +- `web/html/component/aSidebar.html` + +Stability fix: +- `xray/api.go` + +Dev tooling: +- `.air.toml` +- `justfile` + +## Future extension points + +1. Add granular permissions for clients API. +2. Add audit logs table for master-client actions. +3. Add integration tests for sync edge-cases. +4. Add i18n keys for custom page labels/messages. diff --git a/docs/panel-guide/99-session-context-transfer-2026-02-18.md b/docs/panel-guide/99-session-context-transfer-2026-02-18.md new file mode 100644 index 00000000..1b3dae62 --- /dev/null +++ b/docs/panel-guide/99-session-context-transfer-2026-02-18.md @@ -0,0 +1,98 @@ +# 99. Session Context Transfer (2026-02-18) + +## Purpose + +This is a handoff snapshot of all major context and decisions from the collaboration session, so future work can continue without re-discovery. + +## Repository and research context + +- Repo analyzed: `MHSanaei/3x-ui` +- Wiki reference used: `MHSanaei/3x-ui/wiki` +- Existing long guide maintained and expanded: `PANEL_GUIDE_SOURCE_OF_TRUTH.md` +- Focused guide set added under: `docs/panel-guide/` + +## Live panel operational context captured + +Panel URL pattern used in session: +- `http://127.0.0.1:2053/panel/` + +Observed production-style inbounds in your panel during cleanup: +- `reality-443` (renamed) +- `reality-8443` (renamed) + +Additional test inbound created by request: +- VLESS TCP with HTTP obfuscation style (`Host speedtest.com`, path `/`) on `18080` + +Final cleaned naming applied in live panel: +- `vless-reality-tcp-443-main` +- `vless-reality-tcp-8443-alt` +- `vless-tcp-http-18080-test` + +## Core product-model conclusion + +Native 3x-ui is inbound-first: +- Clients are managed per inbound. +- There is no built-in global client object with many-to-many inbound assignment UX. + +This drove implementation choice: +- Build a client-center orchestration layer, not a deep replacement of native inbound client model. + +## Custom feature delivered + +Implemented centralized client-management extension: +- New page: `/panel/clients` +- New API group: `/panel/api/clients/*` +- New DB models for master profile + inbound assignments +- Sync engine to create/update/remove underlying inbound clients + +Files created/updated for feature: +- `web/service/client_center.go` +- `web/controller/client_center.go` +- `web/html/clients.html` +- `database/model/model.go` +- `database/db.go` +- `web/controller/api.go` +- `web/controller/xui.go` +- `web/html/component/aSidebar.html` + +## Additional engineering improvements + +1. Air setup: +- Added `.air.toml` for live-reload development. +- Keeps DB/log/bin in `tmp/`. + +2. Justfile setup: +- Added `justfile` with common run/build/air/api helper commands. + +3. Runtime stability guard: +- Added nil-handler checks in `xray/api.go` (`AddInbound`, `DelInbound`, `AddUser`, `RemoveUser`) to avoid panic and return explicit errors. + +## Local validation that was performed + +Local dev run used repo-local paths: +- DB: `tmp/db` +- Logs: `tmp/logs` +- Port: `2099` + +Validated flows: +- Build success (`go build ./...`) +- Panel startup in debug/dev mode +- Login and authenticated API access +- Custom clients API CRUD and assignment sync +- `/panel/clients` UI render and create flow via browser automation + +## Known caveats from session + +- A large set of `.playwright-cli` artifacts exists in working tree; this was intentionally not cleaned to avoid touching unrelated state. +- If Xray handler service is unavailable in dev conditions, inbound operations may return explicit errors (now handled) rather than panic. + +## Recommended next actions + +1. Add automated integration tests for client-center sync scenarios. +2. Add role/audit controls for client-center APIs in multi-admin environments. +3. Decide whether to keep monolithic guide as archive-only and rely on split docs for active maintenance. +4. If desired, add i18n labels for new `Clients` UI text to align with full localization style. + +## Sensitive data handling note + +Credentials used during interactive operations were user-provided in chat and are intentionally not persisted in this file. diff --git a/docs/panel-guide/README.md b/docs/panel-guide/README.md new file mode 100644 index 00000000..47e51181 --- /dev/null +++ b/docs/panel-guide/README.md @@ -0,0 +1,40 @@ +# 3x-ui Guide Index + +This folder is the focused replacement for the monolithic `PANEL_GUIDE_SOURCE_OF_TRUTH.md`. + +## Files + +1. `01-overview-and-architecture.md` +2. `02-pages-and-operations.md` +3. `03-api-and-cli-reference.md` +4. `04-security-and-hardening.md` +5. `05-client-management-model.md` +6. `06-custom-client-center-feature.md` +7. `07-dev-and-testing-workflow.md` +8. `08-protocols-and-config-analysis.md` +9. `09-xray-protocol-reference.md` +10. `10-glossary-and-concepts.md` +11. `11-troubleshooting-runbook.md` +12. `12-change-management-and-rollout.md` +13. `13-feature-file-map-and-decision-log.md` +14. `99-session-context-transfer-2026-02-18.md` + +## Recommended read order + +1. Read `01` for system model. +2. Read `02` for operator actions. +3. Read `04` before internet exposure. +4. Read `05` and `06` for client strategy. +5. Read `07` for local dev/test workflow. +6. Read `08` for protocol conversion and sample-config interpretation. +7. Read `09` for protocol reference and compatibility guidance. +8. Read `10` for shared terminology and mental models. +9. Read `11` for incident/debug operation. +10. Read `12` before any risky rollout/migration. +11. Read `13` before modifying custom feature code. +12. Read `99` for full session handoff context. + +## Scope note + +- These files reflect current repository state and live validation work done on 2026-02-18. +- For historical context and raw long-form notes, keep `PANEL_GUIDE_SOURCE_OF_TRUTH.md` as archive.