# Others > Misc options, modules, HTTP API, panels, CLI [← Back to index](/llms.txt) --- ## Cli # Surge Mac CLI Surge Mac includes a command-line interface tool located at `/Applications/Surge.app/Contents/Applications/surge-cli`. Use the `--help` flag to access the complete manual. ## Available Commands **Profile Management:** - `reload` - Reload the main profile - `switch-profile ` - Switch to another profile **System Control:** - `stop` - Shutdown Surge - `unattended-upgrade` - Perform an unattended Surge upgrade if available **Diagnostic Commands:** - `dump active` - Show all active connections - `dump request` - Show recent connections - `dump rule` - Show all effective rules - `dump policy` - Show all proxies and policy groups - `dump dns` - Show DNS caches - `dump profile [original / effective]` - Display original or module-modified profiles - `dump event` - Show events - `watch request` - Keep tracing new requests **Testing Commands:** - `test-network` - Test the network delay - `test-policy ` - Test a proxy - `test-all-policies` - Test all proxies - `test-group ` - Immediately retest a policy group **Maintenance Commands:** - `kill ` - Kill an active connection - `flush dns` - Flush DNS cache - `diagnostics` - Run network diagnostics - `set-log-level ` - Change log level without writing to the profile **Environment & Scripting:** - `environment` - Show environment settings - `set ` - Modify environment settings - `script evaluate [mock-script-type] [timeout]` - Load and evaluate scripts ## Available Parameters - `--raw` - Output results in raw JSON format - `--remote/-r` - Connect to a remote Surge instance (e.g., `--remote password@192.168.2.2:6170`) ## Enhanced mode # Enhanced Mode ## Enhanced Mode (Surge Virtual Network Interface, VIF) Some applications don't respect system proxy settings. Surge's enhanced mode solves this by creating a virtual network interface (VIF) that intercepts all traffic. **How it works:** - Surge creates a virtual network interface (VIF) and registers it as the default route - DNS queries receive responses using virtual IPs from the 198.18.0.0/15 range - The VIF handles TCP, UDP, and ICMP traffic only - ICMP cannot be proxied, so responses return directly from the VIF **Important considerations:** - Enable only when necessary - Enabled by default on Surge for iOS - Must be manually started on Surge for Mac - Starting with Surge Mac 5.8.0, the Network Extension framework replaced the legacy utun driver (legacy parameters remain for compatibility) ## Surge VM Gateway ### UDP Fast Path (Mac 6.4.0+) High-volume UDP traffic can overwhelm the standard proxy engine. The UDP Fast Path feature automatically downgrades clients creating excessive short-lived UDP connections to lightweight L3 forwarding mode. **Activation thresholds:** - 10+ connections within 1 second, or - 30+ connections within 10 seconds **Key behaviors:** - Packets forwarded via the fast path bypass the proxy engine entirely and therefore cannot be matched by rules or MITM - Destination ports below 1024 remain in standard mode for service compatibility - Individual device behavior can be toggled via Dashboard/Device list ## Host list # Host List Parameter Type In Surge, many parameters use the Host List type to handle complex requirements, including `force-http-engine-hosts`, `always-raw-tcp-hosts`, and MITM's `hostname` parameter. ## Format Rules The Host List parameter is comma-separated and follows these conventions: - **Exclusions**: Prefix with `-` to exclude a hostname - **Wildcards**: Supports `*` and `?` characters - **Matching order**: Items are matched sequentially; first match wins. Exclusions should appear first for priority - **Default ports**: If no port is specified, Surge applies the standard port for that parameter (port 80 for `force-http-engine-hosts`, port 443 for MITM) - **Specific ports**: Use `:port` suffix to target other ports - **All ports**: Use `:0` suffix to match all ports - **IP addresses**: Use `` for IPv4/IPv6 matching - **IPv4 only**: Use `` for IPv4-specific matching - **IPv6 only**: Use `` for IPv6-specific matching ## Examples Using `force-http-engine-hosts`: - `-*.apple.com` — Excludes all requests to *.apple.com on port 80 - `www.google.com` — Forces HTTP processing for www.google.com on port 80 - `www.google.com:8080` — Forces HTTP processing for www.google.com on port 8080 - `www.google.com:0` — Forces HTTP processing across all ports - `*:0` — Applies to all hostnames on all ports - `-` — Excludes direct IP address requests ## MITM Configuration Example To decrypt all HTTPS while excluding certificate-pinned services: ``` [MITM] hostname = -*icloud*, -*.mzstatic.com, -*.facebook.com, -*.instagram.com, -*.twitter.com, -*dropbox*, -*apple*, -*.amazonaws.com, -, * ``` ## Http api # HTTP API Documentation ## Overview The HTTP API allows you to control Surge (iOS 4.4.0+, Mac 4.0.0+). ## Configuration ``` [General] http-api = examplekey@0.0.0.0:6171 http-api-tls = false ``` ## Authentication Include the API key in the `X-Key` header for all requests: ``` GET /v1/events X-Key: examplekey Accept: */* ``` Alternatively, pass the key via URL query for convenience (e.g., certificate downloads): ``` http://127.0.0.1:6171/v1/mitm/ca?x-key=examplekey ``` ## HTTPS/TLS Support Enable HTTPS by setting `http-api-tls = true`. Surge will use the MITM CA certificate to generate the server certificate. ## Basic Constraints - Only HTTP without TLS is currently supported - Uses GET and POST methods only - GET parameters via URL queries; POST uses JSON body - All responses are JSON ## API Endpoints ### Feature Toggles GET/POST endpoints for: `/v1/features/mitm`, `/v1/features/capture`, `/v1/features/rewrite`, `/v1/features/scripting`, and Mac-only: `system_proxy`, `enhanced_mode` ### Outbound Management - `GET/POST /v1/outbound` — retrieve/change outbound mode (direct, proxy, rule) - `GET/POST /v1/outbound/global` — manage default policy ### Policies & Groups - List policies: `GET /v1/policies` - Test policies: `POST /v1/policies/test` - List groups: `GET /v1/policy_groups` - Select group option: `GET/POST /v1/policy_groups/select` ### Requests - Recent requests: `GET /v1/requests/recent` - Active requests: `GET /v1/requests/active` - Kill request: `POST /v1/requests/kill` ### Profiles - Current profile: `GET /v1/profiles/current?sensitive=0` - Reload: `POST /v1/profiles/reload` - Switch (Mac): `POST /v1/profiles/switch` ### DNS - Flush cache: `POST /v1/dns/flush` - View cache: `GET /v1/dns` - Test delay: `POST /v1/test/dns_delay` ### Modules, Scripts, Devices, & Misc Additional endpoints for module management, scripting evaluation, device management (Mac), traffic monitoring, logging, and CA certificate retrieval. ## Managed profile # Managed Profile Surge can automatically update a profile from a URL. A managed profile begins with: ``` #!MANAGED-CONFIG http://test.com/surge.conf interval=60 strict=true ``` The remote profile must also include the `#!MANAGED-CONFIG` line, or it reverts to a standard profile. Updates only occur when the main Surge app is running. ## Parameters **interval** (Optional, seconds; default: 86400s) Sets the minimum time between update checks. Surge doesn't necessarily trigger immediately after this period expires. **strict** (true/false; default: false) When enabled, Surge requires a forced update after the interval. If updates fail with strict mode off, users can continue using outdated configurations. Users can still start Surge via widget or VPN settings regardless. ## REQUIREMENT Statement Limit configuration lines to specific environments using `!REQUIREMENT` at the line beginning or end: ``` #!REQUIREMENT CORE_VERSION>=22 Group = smart, policyA, policyB ``` Supported variables: `CORE_VERSION, SYSTEM, SYSTEM_VERSION, DEVICE_MODEL, LANGUAGE` Operators: `=, ==, >=, =>, <=, =<, >, <, !, <>, AND, &&, OR, ||, NOT, BEGINSWITH, CONTAINS, ENDSWITH, LIKE, MATCHES` Wrap strings in single quotes; expressions with spaces need double quotes: ``` #!REQUIREMENT "CORE_VERSION>=22 AND SYSTEM=='iOS'" ``` ## FORBIDDEN-AUTO-UPGRADE Statement Prevent automatic profile optimizations (Surge iOS 5.11.0+, Mac 5.7.0+): ``` #!FORBIDDEN-AUTO-UPGRADE smart-group ``` Available keywords: `smart-group` (upgrades url-test/load-balance groups to smart groups) ## Misc options # Misc Options ## Miscellaneous Options in [General] Section The options in this section change frequently. For the most current explanations, consult: - **Surge Mac**: Main Window Menu → Help → Profile Syntax - **Surge iOS**: More Tab → Help → Profile Syntax ### Core Options **loglevel** Sets verbosity: verbose, info, notify, or warning. Avoid verbose in daily use due to performance impact. **ipv6** Enables full IPv6 support, including AAAA record queries for domain access. **ipv6-vif** Controls IPv6 handling through Surge VIF: - `off`: Never set up IPv6 - `auto`: Only if local network has valid IPv6 - `always`: Always enabled **dns-server** Specifies upstream DNS server IP addresses. ### Network Routing **skip-proxy** Forces connections to specified domains/IPs to bypass the proxy. Supports domain names (apple.com), wildcards (*apple.com), and CIDR notation (192.168.2.0/24). **exclude-simple-hostnames** Similar to skip-proxy but for hostnames without dots. **tun-excluded-routes** Bypasses specific IP ranges from the Surge VIF for all traffic types. **tun-included-routes** Adds smaller routes to override default routing behavior. ### Control & API **external-controller-access** Enables external controllers (e.g., Surge Dashboard). Example: `key@0.0.0.0:6165` **http-api** Enables HTTP API control. Example: `key@0.0.0.0:6166` **http-api-tls** Uses HTTPS for API communication (requires MitM CA certificate). **http-api-web-dashboard** Enables web browser control interface. ### HTTP Processing **show-error-page** (Mac 5.8.0+) Controls whether Surge displays its built-in HTTP error page when a request fails (enabled by default). **show-error-page-for-reject** Displays error webpage for rejected plain HTTP requests. **full-header-mode** Exposes complete HTTP header arrays including duplicate fields to rewrite rules and scripts. ### DNS & Testing **internet-test-url** URL for connectivity testing and DIRECT policy tests. **proxy-test-url** Default testing URL for proxy policies. **test-timeout** Connectivity testing timeout duration. **always-real-ip** Returns real IP addresses instead of fake ones for DNS queries. Supports Host List parameter type. **hijack-dns** Hijacks DNS queries to return fake addresses. Use `hijack-dns = *:53` for all queries. **allow-dns-svcb** By default, SVCB record lookups are forbidden to force A record lookups (iOS system compatibility). ### Advanced Features **force-http-engine-hosts** Treats TCP connections as HTTP requests for advanced features (capturing, rewriting, scripting). Uses Host List parameter type. **use-local-host-item-for-proxy** Uses IP addresses from local DNS mapping instead of domain names for proxy connections. **always-raw-tcp-hosts** (iOS 5.8.0+, Mac 5.4.0+) Prevents protocol sniffing for specified hosts. Uses Host List parameter type. **always-raw-tcp-keywords** (Mac 5.5.0+) Skips protocol sniffing for hostnames containing specified substrings. ### Encrypted DNS **encrypted-dns-follow-outbound-mode** Makes DOH (DNS over HTTPS) follow outbound mode settings and rules. **encrypted-dns-server** Specifies encrypted DNS URLs: - DNS over HTTPS: `https://example.com` - DNS over HTTP/3: `h3://example.com` - DNS over QUIC: `quic://example.com` **encrypted-dns-skip-cert-verification** Skips certificate verification (insecure). ### Security & Restrictions **proxy-restricted-to-lan** (iOS 5.13.1+, Mac 5.8.1+) Restricts proxy services to current subnet (enabled by default). **gateway-restricted-to-lan** (iOS 5.13.1+, Mac 5.8.1+) Restricts gateway services to current subnet (enabled by default). **icmp-forwarding** (iOS 5.14.3+, Mac 5.10.0+) Directly forwards ICMP packets in enhanced mode (enabled by default). **block-quic** (iOS 5.14.6+, Mac 5.10.3+) Global QUIC blocking behavior: - `per-policy`: Policy-determined (default) - `all-proxy`: Block all except DIRECT - `all`: Block everything - `always-allow`: Allow all ### UDP & Performance **udp-policy-not-supported-behaviour** Fallback behavior when UDP matches unsupported policies: `DIRECT` or `REJECT` (default in Mac 6.0.0+). **proxy-test-udp** Default UDP test parameter. Example: `apple.com@8.8.8.8` **udp-priority** Prioritizes UDP packets under high system load (game mode). ### GeoIP **geoip-maxmind-url** URL for GeoIP database updates. **disable-geoip-db-auto-update** Disables automatic GeoIP database updates. --- ## Surge iOS Only Parameters **allow-wifi-access** Permits LAN access to Surge proxy services. **wifi-access-http-port** HTTP proxy service port number. **wifi-access-socks5-port** SOCKS5 proxy service port number. **wifi-access-http-auth** Requires authentication: `username:password` **wifi-assist** Enables Wi-Fi assist feature. **hide-vpn-icon** Hides VPN status bar icon. **all-hybrid** Simultaneously uses Wi-Fi and cellular data for connections and DNS (requires unlimited cellular plan). **allow-hotspot-access** Permits access to Surge proxy from tethered devices. **include-all-networks** Makes Surge VIF handle all requests without leakage (iOS 14.0+). Caution: May cause AirDrop, Xcode debugging, and Surge Dashboard USB issues. **include-local-networks** Handles LAN requests via Surge VIF (iOS 14.2+, requires `include-all-networks=true`). **include-apns** Handles Apple Push Notification service traffic (requires `include-all-networks=true`). **include-cellular-services** Handles cellular service traffic: VoLTE, Wi-Fi Calling, IMS, MMS, etc. (requires `include-all-networks=true`). **compatibility-mode** Controls Surge iOS working mode: - `0`: Auto - `1`: Proxy Takeover + VIF (best performance) - `2`: Proxy Takeover Only - `3`: VIF Takeover Only (default) - `4`: Proxy Takeover + VIF with VIF address - `5`: VIF Takeover with multiple smaller routes **auto-suspend** (iOS 5.11.0+) Automatically suspends Surge iOS when Surge Mac network detected (enabled by default). --- ## Surge Mac Only Parameters **use-default-policy-if-wifi-not-primary** When disabled, SSID/BSSID patterns match even when Wi-Fi isn't primary. **read-etc-hosts** Follows local DNS mapping from /etc/hosts. **http-listen** HTTP proxy service listen parameter. Example: `0.0.0.0:6152` **socks5-listen** SOCKS5 proxy service listen parameter. Example: `0.0.0.0:6153` **debug-cpu-usage** Enables CPU debug mode (performance impact). **debug-memory-usage** Enables memory debug mode (performance impact). ## Module # Module ## Overview A module functions as a patch to your current profile, with higher priority than existing profile settings. There are three module types: - **Internal Modules**: Built-in by Surge - **Local Modules**: `.sgmodule` files in the profile directory - **Installed Modules**: Modules installed via URL ## Use Cases Modules enable you to: - Modify settings in non-editable profiles (managed or enterprise) - Toggle specific settings temporarily with a single action - Apply community-created solutions for particular tasks - Customize settings per device without syncing changes across devices ## Module Syntax Module syntax mirrors profile syntax. Overridable sections include: **General & MITM sections** - Override: `key = value` - Append: `key = %APPEND% value` - Insert at front: `key = %INSERT% value` Only `hostname`, `skip-server-cert-verify`, and `tcp-connection` fields can be manipulated in MITM sections. **WireGuard sections** - Override or append keys within `[WireGuard *]` sections **Ruleset sections** - Patch inline rulesets defined within profiles **Rule, Script, URL Rewrite, Header Rewrite, Host** - New lines insert at the top of original content - Module rules limited to: DIRECT, REJECT, REJECT-TINYGIF ## Metadata Add metadata headers to modules: ``` #!name=Name Here #!desc=Description Here #!system=mac ``` ## Parameter Tables (Mac 5.5.0+) Enable user customization via `#!arguments`: ``` #!arguments=hostname=example.com&enable_mitm=true ``` Placeholders like `%hostname%` become available for text replacement. ## Requirements (iOS 5.10.0+ / Mac 5.6.0+) Restrict module usage with `#!requirement=`: ``` #!requirement=CORE_VERSION>=20 && (SYSTEM='iOS' || SYSTEM='tvOS') ``` Available variables: CORE_VERSION, SYSTEM, SYSTEM_VERSION, DEVICE_MODEL, LANGUAGE ## Panel # Information Panel ## Overview Surge iOS 4.9.3+ introduced an experimental feature for customizing information panels to display related information. This requires an active subscription expiring after September 22, 2021. If the subscription expires, panels won't display but other features remain unaffected. ## Basic Configuration ``` [Panel] PanelA = title="Panel Title",content="Panel Content\nSecondLine",style=info ``` The panel name (e.g., `PanelA`) gets passed to scripts in script mode. Supported style parameters include: good, info, alert, and error. ## Static Mode Panels created with basic configuration are static. This works well with managed or enterprise profiles to update content during profile updates and provide operational guidelines to end-users. ## Dynamic Mode Script-driven panels update their contents automatically: ``` [Panel] PanelB = title="Panel Title",content="Panel Content\nSecondLine",style=info,script-name=panel [Script] panel = script-path=panel.js,type=generic ``` When users tap refresh, scripts receive parameters: `$input: { purpose: "panel", position: "policy-selection", panelName: "PanelB" }` and `$trigger: "button"` or `"auto-interval"`. Scripts should return title, content, and style fields via `$done()`. Before first execution, static content displays. Surge caches results and displays the previous output before refreshing. ### Example Script ```javascript $httpClient.get("https://api.my-ip.io/ip", function(error, response, data){ $done({ title: "External IP Address", content: data, }); }); ``` ### Auto-Updating Panels ``` [Panel] PanelB = title="Panel Title",content="Panel Content\nSecondLine",style=info,script-name=panel,update-interval=60 ``` Auto-updates only occur when viewing the policy selection screen. ## Advanced Customization - Omitting the style field displays text-only cards without icons - Use the icon field with SF Symbol Names (e.g., `bolt.horizontal.circle.fill`) for custom icons - Use icon-color with HEX color codes to control icon appearance ## Port forwarding # Port Forwarding **Availability:** iOS 5.14.3+ | Mac 5.10.0+ ## Overview Surge has the capability to listen on a designated local port and direct TCP requests from that port to a specific destination host. This functionality operates independently, meaning it works even when Surge's standard request handling mechanisms (system proxy or enhanced mode) are disabled. ## Usage ### Configuration Syntax Add entries to the `[Port Forwarding]` section of your profile: ``` [Port Forwarding] 0.0.0.0:6841 localhost:3306 policy=SQL-Server-Proxy ``` ### Parameters - **Local address and port** (e.g., `0.0.0.0:6841`): The listening endpoint - **Target host and port** (e.g., `localhost:3306`): Where traffic gets forwarded - **policy parameter** (optional): Specifies which proxy policy to apply. When omitted, standard proxy matching rules determine the policy instead. ## Common Use Cases This feature proves particularly valuable for development and debugging workflows, such as establishing connections to database servers (like MariaDB) through SSH tunneling. ## Subnet settings # Subnet Settings You can use subnet expressions to match specified networks and apply particular settings. Note that subnet settings are named [SSID Setting] in profiles for compatibility. ## Suspend Temporarily suspend Surge on specified networks: ``` [SSID Setting] SSID:MyHome suspend=true ``` ## Cellular Fallback (iOS Only) Control Wi-Fi assist and Hybrid Network behavior for specific Wi-Fi networks: ``` [SSID Setting] SSID:MyHome cellular-fallback=off ``` Options: - `cellular-fallback=default` - Use global Wi-Fi assist and Hybrid Network settings - `cellular-fallback=off` - Disable Wi-Fi assist and Hybrid Network for the network - `cellular-fallback=hybrid` - Enable Hybrid Network for the network - `cellular-fallback=wifi-assist` - Enable Wi-Fi assist for the network ## TCP Fast Open Behaviour ``` [SSID Setting] SSID:MyHome tfo-behaviour=force-enabled ``` Options: - `tfo-behaviour=auto` - Use default TFO behavior - `tfo-behaviour=force-disabled` - Disable TFO completely for the network - `tfo-behaviour=force-enabled` - Enable TFO, overriding system blackhole detection ## DNS Override Override DNS settings for specified networks: ``` [SSID Setting] SSID:MyHome dns-server=8.8.8.8,encrypted-dns-server=https://1.1.1.1/ ``` When encrypted DNS is configured globally, explicitly use `off` to revert to traditional DNS: ``` [SSID Setting] SSID:MyHome dns-server=8.8.8.8,encrypted-dns-server=off ``` ## Url scheme # URL Scheme ## URL Scheme for Surge iOS Surge iOS supports 4 actions and one option. ### Actions - **surge:///start** — Start with selected configuration. - **surge:///stop** — Stop current session. - **surge:///toggle** — Start or stop with selected configuration. - **surge:///install-config?url=x** — Install a configuration from a URL. The URL should be encoded in percent encoding. ### Options - **autoclose=true** — Auto close Surge after action completed. (Cannot be used with install-config) Example: `surge:///toggle?autoclose=true` ## x-callback-url Surge supports x-callback-url specification from v3.4. The URL scheme is 'surge' and the available actions are 'start', 'stop' and 'toggle'.