Secure Clash Controller API: Automate Proxy Node Switching

Why securing the Clash controller API must come before automation

Automating a proxy-node change sounds small: check which nodes are available, choose one, and tell Clash to use it. The Clash external-controller API makes that workflow possible, but it also exposes control over a running proxy core. A script with access to the controller can inspect proxy groups, switch outbound nodes, and potentially change other runtime settings. If the API is reachable by an untrusted device, an attacker may be able to do the same. The right starting point for Clash API automation is therefore not a clever selection rule. It is a controller that listens only where you intend and requires a strong secret.

This guide focuses on a local workflow using a Mihomo-compatible core. The same general ideas apply when a client such as Clash Verge Rev manages the core, but the location and lifetime of its generated configuration can differ. A GUI may replace runtime files or restart the core after an update, so treat the active configuration—not a remembered example—as the source of truth. Keep automation limited to the controller address and credentials you have deliberately configured.

The examples use loopback on port 9090. That is suitable when the script runs on the same machine as the core. It is not a universal default: clients may choose another port, bind to a Unix socket, or manage their own controller settings. Before testing, confirm the actual listener in your client or active Mihomo configuration. Do not assume that a port is available simply because it appears in a tutorial.

Security boundary: Do not expose an unauthenticated controller to a LAN, public interface, container bridge, or internet-facing reverse proxy. A firewall rule is useful defense in depth, but it does not replace a strong API secret and a carefully chosen bind address.

Configure a local, authenticated external controller

In a standalone Mihomo configuration, the controller settings are top-level YAML keys. Bind to the loopback interface when local scripts are the only intended clients, set a long random secret, and keep the secret out of public repositories and shared screenshots. For example:

external-controller: 127.0.0.1:9090
secret: "REPLACE_WITH_A_LONG_RANDOM_SECRET"

The example is a configuration shape, not a drop-in promise that every GUI will preserve those exact lines. If your client offers an external-controller setting, prefer its supported interface and verify the resulting listener after saving or restarting. Avoid editing a generated file that the application will overwrite. If you need a remote controller, first establish a private network path, restrict source addresses with a firewall, and use an authenticated, encrypted transport at the network boundary. Do not solve a connectivity problem by changing the bind address to 0.0.0.0 and leaving the API unprotected.

A controller secret is a bearer credential: anyone who obtains it can make authorized requests within the controller’s available API. Generate a unique value with a password manager or a cryptographically secure generator. Do not reuse a subscription URL, account password, or token from another service. Store it in an environment variable, operating-system secret store, or a file readable only by the automation account. Never place it directly in a script that is committed to Git, pasted into a public issue, or displayed in an unrestricted CI log.

After changing the configuration, restart or reload the core only through the client’s normal controls, then verify that the listener is local. On systems with command-line networking tools, inspect the listening socket with the platform’s available utility. The expected address should be 127.0.0.1:9090 for this example, not a wildcard address. A failed connection can mean the core is stopped, the port differs, a local firewall blocks access, or the client has not applied the configuration; it does not automatically mean the secret is wrong.

Keep the controller API separate from your traffic proxy ports. A mixed proxy port such as 7890 accepts proxied application traffic; the controller port accepts administrative HTTP requests. Confusing the two produces misleading connection errors and can lead to unsafe troubleshooting changes. Record the controller address, the client/core that owns it, and the configuration location in a private operations note. This small inventory prevents later scripts from quietly targeting an obsolete or unrelated service.

Test authentication and inspect proxy groups before switching

Set the secret in the shell rather than embedding it in the command history or source code. The following request asks the controller for its version and sends the credential in the HTTP Authorization header. Mihomo-compatible controller APIs commonly accept the bearer form shown here:

export CLASH_CONTROLLER="http://127.0.0.1:9090"
export CLASH_SECRET="REPLACE_WITH_A_LONG_RANDOM_SECRET"

curl --fail-with-body --silent --show-error \
  -H "Authorization: Bearer ${CLASH_SECRET}" \
  "${CLASH_CONTROLLER}/version"

A successful response confirms that the address is reachable and that the request passed authentication; it does not prove that a desired group exists or that its nodes are healthy. If the response is unauthorized, check the secret and whether the active core actually loaded it. If the connection is refused, check the listener and port before changing credentials. Avoid sending the secret as a URL query parameter: URLs are more likely to be copied into logs, shell history, monitoring systems, or browser records than headers.

Next, request the runtime proxy inventory. The endpoint returns a JSON object containing named proxies and groups. Use a JSON parser to inspect it instead of grepping raw output, because names, ordering, and available fields vary across profiles.

curl --fail-with-body --silent --show-error \
  -H "Authorization: Bearer ${CLASH_SECRET}" \
  "${CLASH_CONTROLLER}/proxies" | jq '.proxies | keys'

Find the exact name of the selector group you intend to control—for example, a profile might call it Proxy, Auto, or 🌐 Select. These names are profile-defined, not universal API constants. Inspect that group directly, using the actual group name in the URL:

curl --fail-with-body --silent --show-error \
  -H "Authorization: Bearer ${CLASH_SECRET}" \
  "${CLASH_CONTROLLER}/proxies/Proxy" |
  jq '{type, now, all}'

The group response commonly includes its type, current selection, and available members. A selector group may allow a direct choice, while a URL-test or fallback group may manage its active member according to its own policy. Do not assume every group is manually selectable. Confirm that the target is the intended group type, that the candidate appears in its available members, and that your selection policy will not fight the group’s automatic behavior.

Profiles often include nested groups and special entries such as DIRECT or REJECT. A candidate’s presence in the global inventory does not mean it is a valid member of the specific group you are changing. Validate membership against the group response. That distinction is central to safe node selection: a script should choose only from the group’s advertised options, rather than accepting arbitrary text from a user, a notification, or an external service.

Select a node with validation and a controlled API request

For a selector group, Mihomo-compatible APIs generally accept a PUT request to the group endpoint with a JSON body containing the desired member name. The following example illustrates the request shape:

GROUP="Proxy"
NODE="Example Node"

curl --fail-with-body --silent --show-error \
  -X PUT \
  -H "Authorization: Bearer ${CLASH_SECRET}" \
  -H "Content-Type: application/json" \
  --data-raw "{\"name\":\"${NODE}\"}" \
  "${CLASH_CONTROLLER}/proxies/${GROUP}"

For production automation, do not pass untrusted strings into shell variables without validation. A group or node name containing spaces or punctuation may also need URL encoding when used in the path. A safer implementation encodes path components with a URL library, serializes JSON with a JSON library, and checks that the requested node is one of the group’s current members before issuing the change. This prevents malformed requests and reduces the risk of a script acting on an unintended endpoint.

Selection should be a deliberate policy, not “pick the first name returned.” The API inventory is not necessarily a quality ranking, and a node that worked yesterday may be slow, unavailable, or inappropriate for a particular application today. A practical workflow can filter candidates by an explicit allowlist, inspect available health or delay data where supported, and apply a minimum threshold. If no candidate passes the policy, leave the current selection unchanged and report the reason instead of switching to a random fallback.

Make the change observable and reversible. Record the group, previous selection, requested selection, timestamp, and result in a local log that does not include the secret. After the request, query the group again and verify that its current selection matches the requested node. If the API reports an error or the current selection does not change, stop and surface that state rather than repeatedly submitting requests. Repeated retries can create noise, mask a profile mismatch, or trigger a rapid sequence of unwanted changes.

A useful automation design separates discovery from action. First read the group and candidate list; then apply a documented decision rule; then request one change; finally verify the result. Add a cooldown so that transient latency measurements do not cause constant switching. For scheduled scripts, use a lock or equivalent mechanism to prevent overlapping runs. When multiple tools can change the same group—such as a GUI user and a background script—define which one has authority, or accept that concurrent choices can overwrite one another.

Start with a read-only script that reports the current group, candidate members, and proposed choice. Run it for several days before enabling automatic PUT requests. This exposes bad assumptions about names, availability, and measurement noise without changing live traffic.

Troubleshoot common API failures and maintain a safe workflow

When a controller request fails, classify the failure before changing configuration. A connection refusal points toward the listener, port, address, or core lifecycle. An HTTP unauthorized response points toward the credential or authentication format. A not-found response often means a typo in the group name, a URL path that was not encoded correctly, or a profile that does not expose the expected endpoint. A bad-request response commonly indicates invalid JSON, an unsupported group operation, or a node that is not a member of that group. Inspect the response body where safe; it can identify the category without requiring repeated guesses.

Use explicit curl error handling. --fail-with-body returns a non-zero status for HTTP error responses while preserving the body for diagnosis; --silent --show-error avoids progress noise but still displays transport errors. In automation, check the process exit status and parse the response as JSON before trusting it. Set a reasonable connection and total timeout so a script cannot hang indefinitely, and use bounded retries only for transient network errors. Authentication errors and invalid requests are not transient and should not be retried in a tight loop.

Keep credentials out of diagnostic output. Shell tracing can print expanded environment variables, and verbose HTTP debugging can reveal authorization headers. Disable tracing around authenticated requests, redact headers before sharing logs, and rotate the secret promptly if it has been exposed. If the controller is managed by a desktop client, remember that a client update, profile switch, service restart, or configuration regeneration may change the address or secret. A script should fail closed when its expected endpoint is unavailable rather than silently discovering and controlling a different service.

Do not mistake a successful API selection for proof that all applications are using the selected route. Routing mode, rules, DNS behavior, TUN settings, application-level proxy settings, and cached connections can affect what traffic actually does. Verify the result in the client’s connection view or logs, then test the specific application and destination relevant to your workflow. A node change can affect new connections while existing sessions remain alive until they reconnect, so allow time for a clean test and avoid claiming that the controller response alone proves end-to-end connectivity.

For a LAN-based controller, treat access as an administrative service. Restrict it to trusted source addresses, use a strong secret, and protect the network path with an appropriate private tunnel or authenticated TLS gateway. Do not forward the controller port on a home router, expose it through a public cloud security group, or rely on an obscure port number as protection. If a reverse proxy is involved, ensure it does not log authorization headers and that only the intended API paths are reachable. Reassess these controls whenever the machine moves between networks or the automation host changes.

Compared with some all-in-one proxy clients and VPN tools, controller automation may be hidden behind a narrow GUI, require repetitive manual node changes, or provide little visibility into the exact group and current choice. Clash and Mihomo offer a structured API that lets an operator inspect the active profile, validate a group’s members, and automate a specific selector while preserving an auditable workflow; that flexibility is useful only when the controller is kept private and authenticated. If you are ready to set up a compatible client before building your script, visit the download page for available builds. Compare the client’s core and controller settings with your intended environment, then proceed with a local, read-first test before enabling node changes.

→ Download Clash for free and enjoy a better internet experience

Go to Download Page