How CFnew's Subscription System Connects Users to the Nearest Proxy

CFnew's subscription system detects the user's Cloudflare Worker edge location and applies a region-aware selection algorithm that prioritizes geographically adjacent proxy nodes, ensuring the generated subscription file routes traffic through the lowest-latency endpoint.

The CFnew subscription system, implemented in the byJoey/cfnew repository, automatically optimizes proxy selection based on geographic proximity. When a user requests a subscription from the /sub endpoint, the system analyzes the incoming request's Cloudflare data center region and builds a prioritized list of nearby proxy nodes. This approach ensures that clients receive a configuration pointing to the healthiest, nearest proxy without manual intervention.

How CFnew Routes Subscription Traffic by Geography

The core logic resides in the main Workers script 明文源吗. When a request arrives at the /sub endpoint, CFnew executes a four-step region-aware selection algorithm to determine the optimal proxy.

Detecting the Worker's Edge Location

The process begins with detectWorkerRegion(request) at line 283, which reads the Cloudflare data center location from the incoming request headers. This function identifies the geographic region code (e.g., HK, US, SG) where the worker is executing, establishing the baseline for proximity calculations.

Fetching the Healthy Proxy Pool

Simultaneously, fetchDynamicIPs() at line 2931 queries the health-check endpoint to retrieve a live list of available proxy IPs. Each entry in this pool includes a regionCode field indicating its geographic location, creating a filtered map of healthy nodes across all available regions.

Building the Geographic Priority List

The algorithm constructs a tiered priority list using two helper functions:

  • getNearbyRegions(region) at line 345 returns a predefined array of regions geographically adjacent to the detected edge location.
  • getAllRegionsByPriority(region) at line 361 concatenates these into a sorted hierarchy: current region first, followed by nearby regions, then the remaining global regions.

This ensures the system attempts to match the closest geographic candidates before falling back to distant proxies.

Selecting the Optimal Proxy

Finally, getSmartRegionSelection() at line 368 iterates through this priority list, filtering the available proxy IPs by each regionCode until it finds a match. The first healthy proxy from the nearest region is selected and embedded into the subscription response. If region matching is disabled via the rm=no query parameter, this filtering step is bypassed and any healthy proxy may be chosen regardless of location.

Implementation in the CFnew Source Code

The subscription handler handleSubscriptionRequest at line 2586 orchestrates the entire process. Below is a simplified view of how the nearest proxy is selected before generating the final configuration:

async function getBestBackupIP(workerRegion = '') {
  const availableIPs = await fetchDynamicIPs();               // Retrieve all healthy proxies
  const priority = getAllRegionsByPriority(workerRegion);    // Current → nearby → rest
  
  for (const region of priority) {
    const matches = availableIPs.filter(ip => ip.regionCode === region);
    if (matches.length) return matches[0];                    // First match in nearest region
  }
  
  return availableIPs[0]; // Fallback to any available proxy
}

The /sub endpoint implementation wraps this logic:

addEventListener('fetch', event => {
  if (event.request.url.endsWith('/sub')) {
    event.respondWith(handleSubscriptionRequest(event.request));
  }
});

Once selected, the proxy address (e.g., ProxyIP.HK.CMLiussss.net:443) is injected into the generated Clash, Surge, or Loon configuration files returned to the client.

Customizing Proxy Selection Behavior

By default, the CFnew subscription system enforces geographic proximity to minimize latency. However, power users can override this behavior using query parameters. Appending rm=no to the subscription URL disables the region-matching logic in getSmartRegionSelection(), causing the system to return any healthy proxy from the global pool regardless of geographic location.

Summary

  • CFnew automatically detects the Cloudflare Worker edge region using detectWorkerRegion() in 明文源吗 (line 283).
  • The system maintains a health-checked pool of proxy IPs with geographic metadata via fetchDynamicIPs() at line 2931.
  • getAllRegionsByPriority() at line 361 creates a sorted list of regions starting with the closest to the user.
  • getSmartRegionSelection() at line 368 filters available proxies against this priority list to find the nearest healthy node.
  • The /sub endpoint (line 2586) returns a configuration file containing the optimal proxy address, ensuring minimal latency connections.
  • Users can disable region matching by setting rm=no to receive random proxy assignments from the global pool.

Frequently Asked Questions

How does CFnew determine which region is closest to the user?

CFnew reads the Cloudflare data center identifier from the request headers using detectWorkerRegion() at line 283 of 明文源吗. It then references a predefined mapping in getNearbyRegions() (line 345) that returns geographically adjacent regions, creating a priority list that prioritizes the current region followed by its neighbors before considering distant locations.

Can I force CFnew to use a specific region instead of the nearest one?

While there is no query parameter to force a specific region code, you can disable the automatic region matching entirely by adding rm=no to your subscription URL. This prevents getSmartRegionSelection() from filtering by geography, allowing the system to select any healthy proxy from the global pool regardless of its regionCode field.

What happens if there are no healthy proxies in my nearest region?

If getSmartRegionSelection() cannot find a healthy proxy matching the current or nearby regions, it continues iterating through the entire priority list established by getAllRegionsByPriority(). If all regional filters are exhausted and no match is found, the function falls back to returning any available healthy proxy from the global pool to ensure connectivity is maintained.

Where is the subscription generation logic located in the source code?

The subscription handler is implemented in 明文源吗 at line 2586 within handleSubscriptionRequest. This function coordinates the region detection, proxy selection via getSmartRegionSelection(), and configuration generation for all supported client formats including Clash YAML and Surge INI files.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →