> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch37-deployment/37.3-remote-access.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 37.3 Remote Access

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~210k tokens, Output \~6k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Local Gateway deployment binds to `127.0.0.1` (loopback) by default, allowing only clients on the same machine to connect. However, in real-world scenarios, users frequently need to access Gateway at home or office from laptops, phones, or remote servers. OpenClaw provides four remote access solutions: **Tailscale Serve/Funnel**, **SSH Tunneling**, **Service Discovery (mDNS/Bonjour)**, and **Wide-Area DNS-SD**. These solutions can be combined — for example, using Tailscale for the secure transport layer while using Bonjour for automatic LAN discovery.

## 37.3.1 Tailscale Serve / Funnel

### Tailscale Introduction

> **Sidebar**: Tailscale is a zero-configuration VPN based on the WireGuard protocol. It assigns each device an IPv4 address in the 100.64.0.0/10 range and a DNS name in the format `<hostname>.<tailnet>.ts.net`. Traffic between devices is end-to-end encrypted, requiring no manual firewall configuration or port forwarding. **Tailscale Serve** allows exposing a local port to other devices within the same tailnet; **Tailscale Funnel** further exposes the port to the public internet (requires permission enabled in the management console).

### Three Modes

OpenClaw Gateway's Tailscale integration is controlled by the configuration item `gateway.tailscale.mode`, supporting three modes:

| Mode     | Accessible Range | Authentication             | Typical Scenario                        |
| -------- | ---------------- | -------------------------- | --------------------------------------- |
| `off`    | Local only       | token/password             | Default, Tailscale disabled             |
| `serve`  | Within tailnet   | Tailscale identity + token | Multiple devices at home/office         |
| `funnel` | Public internet  | password (mandatory)       | Public webhooks, external collaboration |

### Source Code Implementation

The core Tailscale logic is located in `src/gateway/server-tailscale.ts` (59 lines) and `src/infra/tailscale.ts` (496 lines). Gateway calls `startGatewayTailscaleExposure()` on startup:

```typescript
// src/gateway/server-tailscale.ts (simplified)
export async function startGatewayTailscaleExposure(params: {
  tailscaleMode: "off" | "serve" | "funnel";
  resetOnExit?: boolean;
  port: number;
  controlUiBasePath?: string;
}) {
  if (params.tailscaleMode === "off") return null;

  // Call different Tailscale CLI commands based on mode
  if (params.tailscaleMode === "serve") {
    await enableTailscaleServe(params.port);    // tailscale serve --bg --yes <port>
  } else {
    await enableTailscaleFunnel(params.port);   // tailscale funnel --bg --yes <port>
  }

  // Get tailnet hostname for logging
  const host = await getTailnetHostname().catch(() => null);
  // Output: "serve enabled: https://myhost.tail12345.ts.net/ (WS via wss://...)"

  // Return cleanup function (called on process exit)
  if (!params.resetOnExit) return null;
  return async () => {
    if (params.tailscaleMode === "serve") {
      await disableTailscaleServe();    // tailscale serve reset
    } else {
      await disableTailscaleFunnel();   // tailscale funnel reset
    }
  };
}
```

The underlying `enableTailscaleServe()` / `enableTailscaleFunnel()` actually execute the Tailscale CLI on the system:

```typescript
// src/infra/tailscale.ts (simplified)
export async function enableTailscaleServe(port: number) {
  const bin = await getTailscaleBinary();
  await execWithSudoFallback(bin, ["serve", "--bg", "--yes", String(port)], {
    maxBuffer: 200_000,
    timeoutMs: 15_000,
  });
}
```

### Tailscale Binary Location

`findTailscaleBinary()` uses a four-level fallback strategy to locate the `tailscale` executable:

1. **PATH lookup**: `which tailscale`
2. **macOS known paths**: `/Applications/Tailscale.app/Contents/MacOS/Tailscale`
3. **find search**: Search for `Tailscale.app` under `/Applications`
4. **locate database**: Use `locate Tailscale.app` as last resort

Once found, the result is cached to avoid repeated searches.

### Permission Elevation and Sudo Fallback

Some Tailscale operations (like `serve`, `funnel`) may require root privileges. OpenClaw implements automatic sudo fallback:

```typescript
async function execWithSudoFallback(bin, args, opts) {
  try {
    return await exec(bin, args, opts);           // Try direct execution first
  } catch (err) {
    if (!isPermissionDeniedError(err)) throw err;
    return await exec("sudo", ["-n", bin, ...args], opts);  // Retry with sudo -n
  }
}
```

The `-n` (non-interactive) flag ensures sudo won't block waiting for password input — if the user hasn't configured passwordless sudo, it fails immediately and throws the original error.

### Tailscale Whois Authentication

When Gateway runs in Serve mode, Tailscale's reverse proxy injects identity headers:

| HTTP Header                  | Content                     |
| ---------------------------- | --------------------------- |
| `tailscale-user-login`       | User's Tailscale login name |
| `tailscale-user-name`        | User's display name         |
| `tailscale-user-profile-pic` | Avatar URL                  |

Gateway verifies these headers through `readTailscaleWhoisIdentity()` — it calls `tailscale whois --json <ip>` to query the real Tailscale identity of the connector, then cross-checks with the login in the HTTP header. Verification results use LRU cache (success TTL 60 seconds, failure TTL 5 seconds), avoiding system calls for every request.

### Security Constraints

Runtime configuration checks (`server-runtime-config.ts`) enforce two security rules:

1. **Funnel requires password authentication**: In `funnel` mode, `gateway.auth.mode = "password"` must be set, because Funnel exposes to the public internet and token alone isn't secure enough.
2. **Serve/Funnel requires loopback binding**: Tailscale proxy forwards traffic through `127.0.0.1`, Gateway shouldn't listen on external interfaces simultaneously.

```
if (tailscaleMode === "funnel" && authMode !== "password") {
  throw new Error("tailscale funnel requires gateway auth mode=password");
}
if (tailscaleMode !== "off" && !isLoopbackHost(bindHost)) {
  throw new Error("tailscale serve/funnel requires gateway bind=loopback");
}
```

## 37.3.2 SSH Tunneling

SSH tunneling is the most universal remote access method — it doesn't depend on any third-party services, only requiring the remote machine to have SSH port open.

### Tunnel Establishment Flow

OpenClaw's SSH tunnel implementation is in `src/infra/ssh-tunnel.ts` (214 lines). The core function `startSshPortForward()` completes the following steps:

```
┌─────────────┐     SSH -L Forward     ┌─────────────┐
│ Local Client │ ──127.0.0.1:LocalPort── │ Remote Gateway │
│ (CLI/macOS) │                      │ 127.0.0.1:18789│
└─────────────┘                      └─────────────┘
```

1. **Parse target**: `parseSshTarget()` supports multiple formats: `user@host`, `user@host:port`, `host:port`, even with `ssh` prefix. Default port 22.
2. **Port allocation**: Prefer the preferred port (usually 18789), allocate temporary port if occupied.
3. **Start SSH process**: Use `spawn("/usr/bin/ssh", args)` to create tunnel.
4. **Wait for readiness**: Poll `127.0.0.1:LocalPort` until TCP connection can be established.

### SSH Parameter Details

The SSH command constructed by `startSshPortForward()` contains carefully chosen parameters:

```typescript
const args = [
  "-N",                              // Don't execute remote command
  "-L", `${localPort}:127.0.0.1:${remotePort}`,  // Local port forward
  "-p", String(parsed.port),         // Remote SSH port
  "-o", "ExitOnForwardFailure=yes",  // Exit immediately on forward failure
  "-o", "BatchMode=yes",             // Disable interactive password prompt
  "-o", "StrictHostKeyChecking=accept-new",  // Auto-accept host key on first connection
  "-o", "UpdateHostKeys=yes",        // Auto-update known host keys
  "-o", "ConnectTimeout=5",          // Connection timeout 5 seconds
  "-o", "ServerAliveInterval=15",    // Send heartbeat every 15 seconds
  "-o", "ServerAliveCountMax=3",     // Disconnect after 3 heartbeats without response
  "--", userHost,                    // '--' prevents hostname from being parsed as option
];
```

> **Sidebar**: `-L localPort:host:remotePort` is the standard syntax for SSH local port forwarding. It listens on `localPort` on the local machine and forwards received data through encrypted SSH tunnel to `host:remotePort` on the remote machine. Since Gateway only listens on `127.0.0.1`, the host here is also `127.0.0.1`, the loopback of the remote machine.

### Security Protection

The SSH tunnel implementation includes two important security measures:

1. **Hostname injection prevention**: `parseSshTarget()` rejects hostnames starting with `-`, preventing malicious input from being interpreted as SSH command-line options.
2. **`--` parameter terminator**: Insert `--` before hostname, ensuring even if hostname contains special characters it won't be misparsed.

### Lifecycle Management

The tunnel process's stop function implements graceful shutdown: first send `SIGTERM`, wait up to 1.5 seconds, if process still hasn't exited send `SIGKILL` to force terminate.

```typescript
const stop = async () => {
  child.kill("SIGTERM");
  await new Promise<void>((resolve) => {
    const t = setTimeout(() => {
      child.kill("SIGKILL");
      resolve();
    }, 1500);
    child.once("exit", () => { clearTimeout(t); resolve(); });
  });
};
```

### Configuration Integration

Users can configure SSH connection parameters for remote Gateway in `~/.openclaw/config.yaml`:

```yaml
gateway:
  mode: remote
  remote:
    url: ws://127.0.0.1:18789
    transport: ssh           # Use SSH tunnel
    sshTarget: user@myserver.local
    sshIdentity: ~/.ssh/id_ed25519
    token: <gateway-token>
```

CLI also supports establishing tunnel directly via command-line parameter `--ssh <target>`.

## 37.3.3 Service Discovery — mDNS/Bonjour

When Gateway and clients are on the same LAN, users shouldn't need to manually enter IP addresses and ports. OpenClaw uses **mDNS/Bonjour** (also called DNS-SD, DNS-based Service Discovery) to implement zero-configuration service discovery.

> **Sidebar**: mDNS (Multicast DNS) is a protocol for implementing DNS resolution within a LAN (RFC 6762), without requiring a central DNS server. Devices discover other devices by sending multicast queries to 224.0.0.251:5353. DNS-SD (DNS-based Service Discovery, RFC 6763) defines standard formats for service registration and discovery on top of mDNS. Apple's Bonjour is an implementation of mDNS + DNS-SD.

### Broadcast Side — Bonjour Advertiser

When Gateway starts, it broadcasts its presence to the LAN through `startGatewayBonjourAdvertiser()` (`src/infra/bonjour.ts`). The underlying implementation uses the `@homebridge/ciao` library — a pure JavaScript mDNS implementation maintained by the Homebridge project.

#### Service Registration

```typescript
const gateway = responder.createService({
  name: safeServiceName(instanceName),  // e.g., "myhost (OpenClaw)"
  type: "openclaw-gw",                  // Service type
  protocol: Protocol.TCP,
  port: opts.gatewayPort,               // e.g., 18789
  domain: "local",
  hostname,                             // e.g., "myhost"
  txt: gatewayTxt,                      // TXT records
});
```

The registered DNS-SD service type is `_openclaw-gw._tcp`, and TXT records contain metadata needed for client connection:

| TXT Key       | Content              | minimal mode       |
| ------------- | -------------------- | ------------------ |
| `role`        | `gateway`            | ✓                  |
| `gatewayPort` | Port number          | ✓                  |
| `lanHost`     | `hostname.local`     | ✓                  |
| `displayName` | Human-readable name  | ✓                  |
| `transport`   | `gateway`            | ✓                  |
| `gatewayTls`  | `1` (if TLS enabled) | ✓                  |
| `tailnetDns`  | Tailscale DNS name   | ✓                  |
| `sshPort`     | SSH port             | ✗ (full mode only) |
| `cliPath`     | CLI path             | ✗ (full mode only) |

### Three Broadcast Modes

mDNS broadcast is controlled by `discovery.mdns.mode`:

* **`minimal`** (default): Omit `sshPort` and `cliPath`, reduce information exposure
* **`full`**: Broadcast all metadata completely
* **`off`**: Completely disable mDNS

### Watchdog Mechanism

Network interface changes (like WiFi reconnection, sleep wake) can cause mDNS broadcast to fail. Bonjour Advertiser has a built-in watchdog at 60-second intervals that checks if service status is still `announced`, and attempts to re-broadcast if not:

```typescript
const watchdog = setInterval(() => {
  for (const { label, svc } of services) {
    if (svc.serviceState === "announced" || svc.serviceState === "announcing") continue;
    // Status abnormal, attempt to re-broadcast
    svc.advertise().catch(/* ... */);
  }
}, 60_000);
watchdog.unref();  // Don't prevent process exit
```

### Discovery Side — Beacon Discovery

Clients discover Gateway through `discoverGatewayBeacons()` (`src/infra/bonjour-discovery.ts`, 604 lines). This function chooses different discovery tools based on platform:

| Platform | Tool                       | Command                              |
| -------- | -------------------------- | ------------------------------------ |
| macOS    | `dns-sd` (system built-in) | `dns-sd -B _openclaw-gw._tcp local.` |
| Linux    | `avahi-browse`             | `avahi-browse -rt _openclaw-gw._tcp` |

Discovery process:

1. **Browse**: First list all `_openclaw-gw._tcp` instances in specified domain
2. **Resolve**: Query complete information (host, port, TXT records) for each discovered instance
3. **Decode**: Handle DNS-SD specific octal escaping (e.g., Chinese names)

The returned `GatewayBonjourBeacon` object contains all information needed for client connection. The pairing process of macOS and iOS applications is based on this implementation (see Chapter 36).

## 37.3.4 Wide-Area DNS-SD (Wide-Area Discovery)

Standard mDNS only works within LAN — multicast packets don't cross routers. OpenClaw supports **Wide-Area DNS-SD** (also called Unicast DNS-SD), implementing cross-network service discovery through regular DNS records (non-multicast).

### How It Works

The core idea of Wide-Area DNS-SD is writing mDNS records to a real DNS domain:

```
; Domain: openclaw.internal.
_openclaw-gw._tcp.openclaw.internal.  IN PTR  myhost-gateway._openclaw-gw._tcp.openclaw.internal.
myhost-gateway._openclaw-gw._tcp.openclaw.internal.  IN SRV  0 0 18789 myhost.openclaw.internal.
myhost-gateway._openclaw-gw._tcp.openclaw.internal.  IN TXT  "displayName=My Host" "role=gateway" ...
myhost.openclaw.internal.  IN A   100.64.1.42
```

### Zone File Generation

`startGatewayDiscovery()` (`src/gateway/server-discovery-runtime.ts`) checks on startup whether wide-area discovery is enabled:

```typescript
if (params.wideAreaDiscoveryEnabled) {
  const wideAreaDomain = resolveWideAreaDiscoveryDomain(/* ... */);
  const tailnetIPv4 = pickPrimaryTailnetIPv4();
  await writeWideAreaGatewayZone({
    domain: wideAreaDomain,
    gatewayPort: params.port,
    displayName: formatBonjourInstanceName(params.machineDisplayName),
    tailnetIPv4,
    tailnetIPv6: pickPrimaryTailnetIPv6() ?? undefined,
    // ...
  });
}
```

`writeWideAreaGatewayZone()` (`src/infra/widearea-dns.ts`, 200 lines) generates standard BIND format zone files and implements idempotent writes using **content hash** (FNV-1a) — only updates files and increments SOA serial when records actually change.

### Wide-Area Fallback on Discovery Side

When clients discover, if standard mDNS doesn't find instances in wide-area domain (like `openclaw.internal.`), it triggers `discoverWideAreaViaTailnetDns()` fallback:

1. Get IPv4 addresses of all nodes in tailnet via `tailscale status --json`
2. Send `dig PTR` queries to each IP with 6-way concurrency
3. After finding responsive node, continue querying SRV and TXT records
4. Assemble into `GatewayBonjourBeacon` with same format as mDNS

This approach combines Tailscale's device list with DNS-SD's standard protocol, enabling cross-network discovery without setting up a centralized DNS server.

### Configuration Example

```yaml
discovery:
  mdns:
    mode: minimal          # or full / off
  wideArea:
    enabled: true
    domain: openclaw.internal
```

Corresponding environment variables:

| Environment Variable         | Function                            |
| ---------------------------- | ----------------------------------- |
| `OPENCLAW_DISABLE_BONJOUR=1` | Completely disable Bonjour          |
| `OPENCLAW_MDNS_HOSTNAME`     | Custom mDNS hostname                |
| `OPENCLAW_WIDE_AREA_DOMAIN`  | Wide-area discovery domain          |
| `OPENCLAW_TAILNET_DNS`       | Manually specify Tailscale DNS name |
| `OPENCLAW_SSH_PORT`          | SSH port in mDNS TXT (full mode)    |
| `OPENCLAW_CLI_PATH`          | Manually specify CLI path           |

***

## Section Summary

1. **Tailscale Serve/Funnel** provides zero-configuration secure remote access. Serve mode limits to within tailnet, Funnel exposes to public internet (mandatory password authentication + loopback binding). Implemented by calling Tailscale CLI, supports sudo fallback and Whois identity verification.
2. **SSH Tunneling** is the most universal solution. `startSshPortForward()` automatically allocates local port, sets secure parameters (heartbeat, timeout, injection prevention), polls for tunnel readiness, and provides graceful shutdown.
3. **mDNS/Bonjour** implements zero-configuration LAN discovery. Gateway broadcasts `_openclaw-gw._tcp` service via `@homebridge/ciao`, clients discover via `dns-sd` (macOS) or `avahi-browse` (Linux). Watchdog ensures automatic recovery after sleep wake.
4. **Wide-Area DNS-SD** breaks LAN limitations, implementing cross-network discovery through generating standard DNS zone files + Tailscale node scanning, without needing centralized DNS infrastructure.
5. These four solutions can be flexibly combined: Tailscale for transport layer + Bonjour for discovery layer is the most common pairing.
