[PR #3735] [MERGED] feat: implement 'last IP wins' policy for IP limitation #5517

Closed
opened 2026-10-31 20:47:30 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/3735
Author: @AungYeZawDev
Created: 2/2/2026
Status: ✅ Merged
Merged: 2/3/2026
Merged by: @MHSanaei

Base: main ← Head: feat/last-ip-wins-limitation


📝 Commits (2)

  • 430e644 feat: implement 'last IP wins' policy for IP limitation
  • cd90174 Merge branch 'main' into feat/last-ip-wins-limitation

📊 Changes

2 files changed (+325 additions, -38 deletions)

View changed files

➕ .github/copilot-instructions.md (+155 -0)
📝 web/job/check_client_ip_job.go (+170 -38)

📄 Description

Implement "last IP wins" policy for IP limitation

What is the pull request?

This PR implements a "last IP wins" policy for the IP limitation feature. When a client exceeds their configured IP limit, the system now automatically disconnects connections from the oldest IPs and keeps only the most recent connections active.

Key improvements:

  • Timestamp-based tracking: Each IP address is stored with its last-seen connection timestamp
  • Smart sorting: IPs are sorted by connection time (newest first) instead of alphabetically
  • Active enforcement: Old connections are forcibly disconnected via Xray API (RemoveUser + AddUser pattern)
  • Network switching support: Users can seamlessly switch between mobile data, WiFi, and VPN without manual intervention
  • Enhanced logging: Detailed logs show which IPs are being disconnected and when

Previous behavior:

  • Only tracked cumulative unique IPs without actual disconnection
  • Used alphabetical sorting to determine "excess" IPs (arbitrary and ineffective)
  • Relied solely on fail2ban for enforcement
  • No support for legitimate network switching scenarios

New behavior:

  • When user connects from new IP exceeding limit, oldest connection automatically drops
  • User can reconnect from previously-used IP and it becomes "newest" again
  • Perfect for VPN providers selling "1 client = 1 IP" licenses
  • Prevents account sharing while supporting legitimate use cases

Which part of the application is affected by the change?

  • Frontend
  • Backend

Files modified:

  • web/job/check_client_ip_job.go - Complete rewrite of IP limitation logic
  • .github/copilot-instructions.md - Added (new documentation for AI coding assistants)

Type of Changes

  • Bug fix
  • New feature
  • Refactoring
  • Other

This is both a new feature (active disconnection mechanism) and a refactoring (improved IP tracking logic)

Technical Details

Database Format Change

Old format (simple IP array):

["1.2.3.4", "5.6.7.8"]

New format (IP with timestamp):

[
  {"ip":"1.2.3.4","timestamp":1738521234},
  {"ip":"5.6.7.8","timestamp":1738521250}
]

Disconnection Mechanism

When limit exceeded:

  1. xrayAPI.RemoveUser(tag, email) - Disconnect ALL connections
  2. time.Sleep(100ms) - Wait for cleanup
  3. xrayAPI.AddUser(tag, config) - Re-add user (allows new IPs only)

Implementation Changes

Added:

  • IPWithTimestamp struct for tracking IPs with timestamps
  • disconnectClientTemporarily() function for active connection termination
  • Timestamp extraction from Xray access logs using regex
  • IP merging logic that preserves latest timestamp per IP
  • Sorting by timestamp (descending) instead of alphabetical

Modified:

  • processLogFile() - Now extracts and stores timestamps
  • addInboundClientIps() - Accepts []IPWithTimestamp instead of []string
  • updateInboundClientIps() - Complete rewrite with active disconnection logic

Log Output Example

2026/02/02 15:30:45 [LIMIT_IP] Email = user@example.com || Disconnecting OLD IP = 1.2.3.4 || Timestamp = 1738521234
2026/02/02 15:30:45 [LIMIT_IP] Client user@example.com: Kept 2 newest IPs, disconnected 1 old IPs

Use Cases

Perfect for VPN Providers

  • ✅ Sell "1 client = 1 IP" licenses
  • ✅ Prevent account sharing between different locations
  • ✅ Allow legitimate reconnections from same location
  • ✅ Support switching between mobile/WiFi/VPN networks

Example Scenarios

Scenario 1: Account Sharing Prevention

  • User connects from home (IP: 1.2.3.4)
  • Friend tries to connect from different location (IP: 5.6.7.8)
  • With LimitIP=1: Friend's connection succeeds, user disconnects
  • If user reconnects: Friend disconnects (last connected wins)

Scenario 2: Network Switching (Legitimate Use)

  • User connects from WiFi (IP: 1.2.3.4)
  • User switches to mobile data (IP: 5.6.7.8)
  • With LimitIP=1: WiFi connection drops, mobile stays active
  • User returns home to WiFi: Mobile drops, WiFi reconnects seamlessly

Scenario 3: Same ISP Reconnection

  • User connects from home (IP: 1.2.3.4)
  • User disconnects and reconnects → same IP
  • Database only has 1 unique IP
  • With LimitIP=1: No problem, no disconnection

Testing Recommendations

  1. Basic Test:

    # Set LimitIP=1 on test client via web panel
    # Connect from IP A → Check success
    # Connect from IP B → Check IP A disconnects, B active
    # Reconnect from IP A → Check IP B disconnects, A active
    
  2. Log Verification:

    tail -f /var/log/x-ui/3xipl.log
    # Should show: [LIMIT_IP] Email = ... || Disconnecting OLD IP = ...
    
  3. Database Inspection:

    sqlite3 /etc/x-ui/x-ui.db "SELECT * FROM inbound_client_ips;"
    # Verify JSON contains timestamp field
    
  4. Edge Cases:

    • Multiple rapid reconnections (stress test)
    • Xray restart during active enforcement
    • Different protocols (VLESS, VMess, Trojan, etc.)

Backward Compatibility

✅ Fully backward compatible

  • Old IP records without timestamps will automatically get current timestamp on first processing
  • Database migration is automatic and transparent
  • No manual intervention required for existing installations
  • Fail2ban integration still works as before (complementary)

Performance Considerations

  • Job runs every 10 seconds (unchanged)
  • Additional regex for timestamp extraction (minimal overhead)
  • IP sorting O(n log n) where n = number of IPs per client (typically < 10)
  • API calls only when disconnection needed (not every check)
  • 100ms sleep per disconnection (prevents API race conditions)

Security Implications

✅ Improves Security:

  • Actively prevents account sharing
  • Real-time enforcement (was passive before)
  • Clear audit trail in logs

⚠️ Considerations:

  • Temporary user removal during disconnection (100ms window)
  • Requires Xray API access (uses existing xrayApiPort setting)

Breaking Changes

None - This is a pure enhancement. The feature:

  • Works with existing LimitIP configuration
  • Maintains same database table structure (just JSON content format change)
  • Doesn't affect clients without LimitIP set
  • Falls back gracefully if Xray API unavailable

Documentation Updates

  • Added .github/copilot-instructions.md with comprehensive development guide
  • Updated "Common Gotchas" section with IP limitation behavior
  • Inline code comments explain the "last IP wins" logic

Future Enhancements (Not in This PR)

  • Optional time-based IP expiration (remove IPs not seen for X hours)
  • Web UI to view currently active IPs per client
  • Configurable disconnection delay (currently 100ms hardcoded)
  • Webhook/notification when disconnection occurs
  • Statistics on disconnection frequency per client

Screenshots

Not applicable - Backend functionality only (log-based verification)


Summary

This PR transforms IP limitation from a passive logging system into an active enforcement mechanism that benefits both VPN providers and end users. It prevents account sharing while gracefully handling legitimate network switching scenarios.

Ready for Review ✅


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/MHSanaei/3x-ui/pull/3735 **Author:** [@AungYeZawDev](https://github.com/AungYeZawDev) **Created:** 2/2/2026 **Status:** ✅ Merged **Merged:** 2/3/2026 **Merged by:** [@MHSanaei](https://github.com/MHSanaei) **Base:** `main` ← **Head:** `feat/last-ip-wins-limitation` --- ### 📝 Commits (2) - [`430e644`](https://github.com/MHSanaei/3x-ui/commit/430e6447e07a90b52f0047fe09f771a67fc92afc) feat: implement 'last IP wins' policy for IP limitation - [`cd90174`](https://github.com/MHSanaei/3x-ui/commit/cd90174a64ec086e3a32635a9b30eef94c98a15f) Merge branch 'main' into feat/last-ip-wins-limitation ### 📊 Changes **2 files changed** (+325 additions, -38 deletions) <details> <summary>View changed files</summary> ➕ `.github/copilot-instructions.md` (+155 -0) 📝 `web/job/check_client_ip_job.go` (+170 -38) </details> ### 📄 Description # Implement "last IP wins" policy for IP limitation ## What is the pull request? This PR implements a **"last IP wins"** policy for the IP limitation feature. When a client exceeds their configured IP limit, the system now automatically disconnects connections from the oldest IPs and keeps only the most recent connections active. **Key improvements:** - **Timestamp-based tracking**: Each IP address is stored with its last-seen connection timestamp - **Smart sorting**: IPs are sorted by connection time (newest first) instead of alphabetically - **Active enforcement**: Old connections are forcibly disconnected via Xray API (RemoveUser + AddUser pattern) - **Network switching support**: Users can seamlessly switch between mobile data, WiFi, and VPN without manual intervention - **Enhanced logging**: Detailed logs show which IPs are being disconnected and when **Previous behavior:** - Only tracked cumulative unique IPs without actual disconnection - Used alphabetical sorting to determine "excess" IPs (arbitrary and ineffective) - Relied solely on fail2ban for enforcement - No support for legitimate network switching scenarios **New behavior:** - When user connects from new IP exceeding limit, oldest connection automatically drops - User can reconnect from previously-used IP and it becomes "newest" again - Perfect for VPN providers selling "1 client = 1 IP" licenses - Prevents account sharing while supporting legitimate use cases ## Which part of the application is affected by the change? - [ ] Frontend - [x] Backend **Files modified:** - `web/job/check_client_ip_job.go` - Complete rewrite of IP limitation logic - `.github/copilot-instructions.md` - Added (new documentation for AI coding assistants) ## Type of Changes - [ ] Bug fix - [x] New feature - [x] Refactoring - [ ] Other *This is both a new feature (active disconnection mechanism) and a refactoring (improved IP tracking logic)* ## Technical Details ### Database Format Change **Old format (simple IP array):** ```json ["1.2.3.4", "5.6.7.8"] ``` **New format (IP with timestamp):** ```json [ {"ip":"1.2.3.4","timestamp":1738521234}, {"ip":"5.6.7.8","timestamp":1738521250} ] ``` ### Disconnection Mechanism When limit exceeded: 1. `xrayAPI.RemoveUser(tag, email)` - Disconnect ALL connections 2. `time.Sleep(100ms)` - Wait for cleanup 3. `xrayAPI.AddUser(tag, config)` - Re-add user (allows new IPs only) ### Implementation Changes **Added:** - `IPWithTimestamp` struct for tracking IPs with timestamps - `disconnectClientTemporarily()` function for active connection termination - Timestamp extraction from Xray access logs using regex - IP merging logic that preserves latest timestamp per IP - Sorting by timestamp (descending) instead of alphabetical **Modified:** - `processLogFile()` - Now extracts and stores timestamps - `addInboundClientIps()` - Accepts `[]IPWithTimestamp` instead of `[]string` - `updateInboundClientIps()` - Complete rewrite with active disconnection logic ### Log Output Example ```log 2026/02/02 15:30:45 [LIMIT_IP] Email = user@example.com || Disconnecting OLD IP = 1.2.3.4 || Timestamp = 1738521234 2026/02/02 15:30:45 [LIMIT_IP] Client user@example.com: Kept 2 newest IPs, disconnected 1 old IPs ``` ## Use Cases ### Perfect for VPN Providers - ✅ Sell "1 client = 1 IP" licenses - ✅ Prevent account sharing between different locations - ✅ Allow legitimate reconnections from same location - ✅ Support switching between mobile/WiFi/VPN networks ### Example Scenarios **Scenario 1: Account Sharing Prevention** - User connects from home (IP: 1.2.3.4) - Friend tries to connect from different location (IP: 5.6.7.8) - With `LimitIP=1`: Friend's connection succeeds, user disconnects - If user reconnects: Friend disconnects (last connected wins) **Scenario 2: Network Switching (Legitimate Use)** - User connects from WiFi (IP: 1.2.3.4) - User switches to mobile data (IP: 5.6.7.8) - With `LimitIP=1`: WiFi connection drops, mobile stays active - User returns home to WiFi: Mobile drops, WiFi reconnects seamlessly **Scenario 3: Same ISP Reconnection** - User connects from home (IP: 1.2.3.4) - User disconnects and reconnects → same IP - Database only has 1 unique IP - With `LimitIP=1`: No problem, no disconnection ## Testing Recommendations 1. **Basic Test:** ```bash # Set LimitIP=1 on test client via web panel # Connect from IP A → Check success # Connect from IP B → Check IP A disconnects, B active # Reconnect from IP A → Check IP B disconnects, A active ``` 2. **Log Verification:** ```bash tail -f /var/log/x-ui/3xipl.log # Should show: [LIMIT_IP] Email = ... || Disconnecting OLD IP = ... ``` 3. **Database Inspection:** ```bash sqlite3 /etc/x-ui/x-ui.db "SELECT * FROM inbound_client_ips;" # Verify JSON contains timestamp field ``` 4. **Edge Cases:** - Multiple rapid reconnections (stress test) - Xray restart during active enforcement - Different protocols (VLESS, VMess, Trojan, etc.) ## Backward Compatibility ✅ **Fully backward compatible** - Old IP records without timestamps will automatically get current timestamp on first processing - Database migration is automatic and transparent - No manual intervention required for existing installations - Fail2ban integration still works as before (complementary) ## Performance Considerations - Job runs every 10 seconds (unchanged) - Additional regex for timestamp extraction (minimal overhead) - IP sorting O(n log n) where n = number of IPs per client (typically < 10) - API calls only when disconnection needed (not every check) - 100ms sleep per disconnection (prevents API race conditions) ## Security Implications ✅ **Improves Security:** - Actively prevents account sharing - Real-time enforcement (was passive before) - Clear audit trail in logs ⚠️ **Considerations:** - Temporary user removal during disconnection (100ms window) - Requires Xray API access (uses existing `xrayApiPort` setting) ## Breaking Changes **None** - This is a pure enhancement. The feature: - Works with existing `LimitIP` configuration - Maintains same database table structure (just JSON content format change) - Doesn't affect clients without `LimitIP` set - Falls back gracefully if Xray API unavailable ## Documentation Updates - Added `.github/copilot-instructions.md` with comprehensive development guide - Updated "Common Gotchas" section with IP limitation behavior - Inline code comments explain the "last IP wins" logic ## Future Enhancements (Not in This PR) - [ ] Optional time-based IP expiration (remove IPs not seen for X hours) - [ ] Web UI to view currently active IPs per client - [ ] Configurable disconnection delay (currently 100ms hardcoded) - [ ] Webhook/notification when disconnection occurs - [ ] Statistics on disconnection frequency per client ## Screenshots *Not applicable - Backend functionality only (log-based verification)* --- ## Summary This PR transforms IP limitation from a passive logging system into an active enforcement mechanism that benefits both VPN providers and end users. It prevents account sharing while gracefully handling legitimate network switching scenarios. **Ready for Review** ✅ --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-31 20:47:30 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#5517
No description provided.