> 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/appendices/appendix-g-gateway-network-model-reference.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# Appendix G: Gateway Network Model and Protocol Reference

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~200,000 tokens, Output \~11,000 tokens **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

This appendix is an **operations quick reference for deployment and access** — it answers *how do I actually configure this*. Chapters 11–12 answer *how is it implemented in code*. Read them together.

The content is compiled from 13 official documents under `docs/gateway/` and `docs/concepts/architecture.md`, cross-checked against the source.

## G.1 Six Things People Most Often Get Wrong

Read these six and you'll skip most deployment confusion.

**1. Default port 18789, with WS + HTTP + canvas host multiplexed on it.** Bound to loopback only by default (`ws://127.0.0.1:18789`). It is not one port per feature.

**2. Gateway handshake authentication has exactly two modes.** `gateway.auth.mode = "token"` (the default when `OPENCLAW_GATEWAY_TOKEN` is set) or `"password"`. A third special path is Tailscale Serve's credential-free identity header (`gateway.auth.allowTailscale: true`), which applies **only to the Control UI / WS surface**.

**3. `docs/gateway/authentication.md` is not about Gateway handshake auth.** It documents **model provider authentication** (OAuth / API key / setup-token). The two are extremely easy to confuse. The authoritative definition of gateway auth lives in `tailscale.md` and the two HTTP API documents.

**4. "bridge" is a legacy concept.** The old TCP JSONL transport for device nodes (port 18790). **The current build no longer starts it, and `bridge.*` config keys have been removed from the schema.** Nodes and operator clients now share one WS. (§44.1 cites this decisive removal as evidence for the "converged network surface" theme.)

**5. There is exactly one mDNS service type: `_openclaw-gw._tcp`, and only the Gateway advertises.** Nodes do not advertise.

**6. There are two pairing systems — don't confuse them.**

| Mechanism                                                    | Role                                                             |
| ------------------------------------------------------------ | ---------------------------------------------------------------- |
| **Device pairing** (in the `connect` handshake, role `node`) | **Gates the WS handshake**                                       |
| The `node.pair.*` method family                              | A separate pairing store that **does not** gate the WS handshake |

The official documentation warns about this specifically. The second exists for managing pairing lists in the UI — don't assume configuring it controls access.

## G.2 WS Protocol Essentials

Protocol positioning, in the docs' own words: *"the single control plane + node transport."*

**Source of truth and generation chain**:

```
src/gateway/protocol/schema/protocol-schemas.ts   (TypeBox, PROTOCOL_VERSION = 3)
                    │
        ┌───────────┴───────────┐
        ↓                       ↓
   JSON Schema              Swift models
   (runtime inbound          (pnpm protocol:gen)
    frame validation)
```

### The three-step handshake

```
① Gateway → client    connect.challenge  (nonce + ts)
② client → Gateway    connect            (min/maxProtocol, client info, role,
                                          scopes, caps, commands, auth, device signature)
③ Gateway → client    hello-ok           (protocol version + tick policy + possibly a deviceToken)
```

**If the first frame isn't `connect`, or isn't JSON, the connection is hard-closed.** There is no lenient handling.

### Roles and scopes

Two roles:

| Role       | Purpose         | Typical clients                  |
| ---------- | --------------- | -------------------------------- |
| `operator` | Control plane   | CLI, macOS app, Web UI, TUI      |
| `node`     | Capability host | iOS/Android apps, headless nodes |

Operators have five scopes: `read` / `write` / `admin` / `approvals` / `pairing`.

**Two important reminders**:

* The docs stress **"Method scope is only the first gate"** — slash commands inside `chat.send` face stricter command-level checks (e.g. `/config set` requires `operator.admin`).
* A node's declared caps / commands / permissions are **claims only**; the server enforces an allowlist. Declaring a capability doesn't grant it.

### Reliability semantics

| Mechanism            | Rule                                                                                                                              |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| **Idempotency keys** | **Required** on side-effecting methods (`send`, `agent`); the server keeps a short-lived dedup cache, so clients can retry safely |
| **No event replay**  | On a `seq` gap, the client **must proactively refresh its snapshot**                                                              |

This is the classic "structured RPC + best-effort event stream" combination: it pushes disconnect-recovery complexity into client snapshot logic, in exchange for the server not maintaining an event replay buffer.

### Six device-auth failures and structured errors

| Error code                       |
| -------------------------------- |
| `DEVICE_AUTH_NONCE_REQUIRED`     |
| `DEVICE_AUTH_NONCE_MISMATCH`     |
| `DEVICE_AUTH_SIGNATURE_INVALID`  |
| `DEVICE_AUTH_SIGNATURE_EXPIRED`  |
| `DEVICE_AUTH_DEVICE_ID_MISMATCH` |
| `DEVICE_AUTH_PUBLIC_KEY_INVALID` |

Each carries structured `details.code` / `details.reason`, and the error response also includes **`recommendedNextStep`** (e.g. `retry_with_device_token`).

**Errors as navigation** — this is OpenClaw's answer in §45.3's "who is the error message for" contrast: it teaches the **client program** how to recover.

Anti-storm measure: on `AUTH_TOKEN_MISMATCH`, a trusted client may make exactly **one** bounded retry using its cached device token.

### Two explicit downgrade switches

| Switch                                | Consequence                                                                  |
| ------------------------------------- | ---------------------------------------------------------------------------- |
| `gateway.controlUi.allowInsecureAuth` | localhost HTTP compatibility only                                            |
| `dangerouslyDisableDeviceAuth`        | A break-glass flag the docs themselves label **"severe security downgrade"** |

Note the naming — the `dangerously` prefix is §44.4's "naming is a contract" in practice.

## G.3 Discovery and Remote Access

### Four-level transport fallback (client side)

```
① Paired direct endpoint
      ↓ unavailable
② Bonjour LAN discovery ("Use this gateway" one-click save)
      ↓ unavailable
③ Configured tailnet DNS / IP direct connection
      ↓ unavailable
④ SSH tunnel fallback
   ssh -N -L 18789:127.0.0.1:18789 user@host
```

Another degradation chain (§44.2).

### Bonjour is a LAN-only convenience layer, not a trust carrier

TXT records carry `lanHost` / `gatewayPort` / `gatewayTls` / `gatewayTlsSha256` / `sshPort` / `tailnetDns` / `cliPath` and similar.

**But the docs are explicit: mDNS TXT records are unauthenticated.** Three hard rules:

1. Routing must trust the **SRV + A/AAAA resolution**, not addresses in TXT;
2. **A TLS pin must never be overridden by a broadcast fingerprint** — otherwise anyone on the LAN can machine-in-the-middle you;
3. A mobile client's first pin requires **out-of-band confirmation**.

**Wide-area DNS-SD**: `openclaw dns setup --apply` installs CoreDNS (**listening on port 53 on the Tailscale interface only**); with split DNS configured, iOS and Android can browse `local.` and a custom domain simultaneously.

### Three Tailscale modes

`gateway.tailscale.mode`:

| Mode     | Behavior                                                                                                                                                                                                                                         |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `serve`  | Reachable only within the tailnet. The Gateway itself still binds loopback; Tailscale injects a `tailscale-user-login` identity header, and **OpenClaw accepts it only after reverse-verifying `x-forwarded-for` via a local `tailscale whois`** |
| `funnel` | Public HTTPS. **Refuses to start unless auth mode is password**; only ports 443 / 8443 / 10000; **no identity header injected**                                                                                                                  |
| `off`    | Disabled                                                                                                                                                                                                                                         |

Note how `serve` handles the identity header: not "trust it because it's present," but take it and reverse-verify with a local `tailscale whois`. **Trusting a header field without verification is the most common vulnerability in reverse-proxy setups.**

**The HTTP API (`/v1/*`) still requires token/password in every mode.** The identity-header path covers only Control UI / WS.

### Credential precedence (the finest-grained part of the docs)

A few hard rules that cause confusion when misconfigured:

| Scenario                   | Rule                                                                                              |
| -------------------------- | ------------------------------------------------------------------------------------------------- |
| CLI passes `--url`         | **Never** falls back to implicit credentials from config/env — you must pass `--token` explicitly |
| local mode token chain     | env → `gateway.auth.token` → `gateway.remote.token`                                               |
| remote mode token chain    | `gateway.remote.token` takes precedence                                                           |
| node-host in local mode    | **Ignores `gateway.remote.*`** (so device-token fallback isn't suppressed)                        |
| SecretRef fails to resolve | Always fail-closed                                                                                |

The fourth rule corroborates the source-level finding in Appendix F.5.1 — documentation and implementation agree.

The first rule's intent is worth internalizing: **if you named the target explicitly, you must name the credential explicitly** — preventing "I thought I was connecting to the test box, but I carried the production token over."

### Multi-instance isolation

`--profile` isolates config / state / service names in one flag (implementation in Appendix F.1).

**Derived port conventions**:

```
browser control = base + 2
CDP             = browser.controlPort + 9 .. +108 (auto-allocated)
```

Hence the documented recommendation: **leave at least 20 ports between base ports of multiple instances.**

## G.4 Node Pairing

The Gateway is the single source of truth for admission (the docs call it "Option B"):

```
node requests
   ↓
pending (auto-expires after 5 minutes)
   ↓
approved via CLI / UI
   ↓
approval always issues a new token (re-pairing rotates)
   ↓
node reconnects with the token
```

**`node.pair.request` never returns a token** — tokens are issued only by the approval action.

Storage: `~/.openclaw/nodes/paired.json` and `pending.json`. **The transport layer is completely stateless.**

**The macOS app's silent approval has two conditions**: the request is marked `silent` **and** the app can SSH-verify to the gateway host as the same user.

That design is clever: it uses **"can SSH into this machine"** as a proxy proof of physical trust. Someone who can SSH in could already change the config and read the keys, so auto-approving their pairing doesn't lower the security bar.

## G.5 OpenAI-Compatible HTTP API

Two endpoints, same port, **both disabled by default**:

| Endpoint                             | Switch                                           |
| ------------------------------------ | ------------------------------------------------ |
| `POST /v1/chat/completions`          | `gateway.http.endpoints.chatCompletions.enabled` |
| `POST /v1/responses` (OpenResponses) | `gateway.http.endpoints.responses.enabled`       |

**Shared semantics**:

* Underneath it's an **ordinary agent run** (same code path as `openclaw agent`);
* Select the agent via `model: "openclaw:<agentId>"` or a header;
* Stateless by default; when OpenAI's `user` field is present, a stable session key is derived from it.

**The security boundary is stated bluntly**:

> Treat this endpoint as a full operator-access surface.

Meaning: **there is no per-user scope — past auth, you are a trusted operator.** These endpoints belong behind loopback / tailnet / private ingress only. Consistent with the trust model in §44.4.

**Limits and defenses**:

| Item          | Limit                                                                                  |
| ------------- | -------------------------------------------------------------------------------------- |
| Body          | 20 MB                                                                                  |
| Images        | 10 MB (HEIC normalized to JPEG)                                                        |
| Files         | 5 MB (contents go into the system prompt as ephemeral, **never into session history**) |
| PDFs          | At most 4 pages rasterized (worker-less pdfjs-dist)                                    |
| URL allowlist | Wildcards supported, but **does not match the apex domain**                            |

Note the last one especially: **"the allowlist does not exempt private-IP blocking"** — even an allowlisted domain is blocked if it resolves to a private IP.

**SSRF defenses are orthogonal to the allowlist**, not "allowlisted therefore permitted." That conflation is the root of many SSRF vulnerabilities.

## G.6 Port and Config Key Quick Reference

| Port / config key             | Value / notes                                                                                               |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------- |
| Gateway WS + HTTP + canvas    | **18789** (single-port multiplex)                                                                           |
| browser control               | base + 2 (loopback only)                                                                                    |
| CDP                           | auto-allocated base+9 .. +108                                                                               |
| legacy TCP bridge             | 18790 (**removed**)                                                                                         |
| CoreDNS (wide-area discovery) | 53, Tailscale interface only                                                                                |
| Funnel-permitted ports        | 443 / 8443 / 10000 only                                                                                     |
| `gateway.bind`                | `loopback` (default) / `lan` / `tailnet` / `custom` / `auto`; **non-loopback requires a token or password** |
| `gateway.auth.mode`           | `token` / `password` (+ `allowTailscale` identity-header path)                                              |
| `gateway.remote.*`            | **Client-side** credentials — does **not** configure server-side auth                                       |
| `gateway.controlUi.*`         | Two explicit downgrade switches (insecure auth / disable device auth)                                       |

**Key environment variables**:

```
OPENCLAW_GATEWAY_TOKEN
OPENCLAW_GATEWAY_PASSWORD
OPENCLAW_GATEWAY_URL
OPENCLAW_GATEWAY_PORT
OPENCLAW_CONFIG_PATH
OPENCLAW_STATE_DIR
OPENCLAW_PROFILE
OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1     ← break-glass
```

Note the `gateway.remote.*` row: these are the credentials **your client uses to connect to someone else**, not the authentication of your own server. It's the single most common misreading in the config.

## G.7 Appendix Summary

Read across all of these documents, the strategy is remarkably consistent:

> **Shrink the network surface to a minimum, then go deep at the one remaining entrance.**

* **Shrinking**: one port, one transport (WS), two auth modes; the legacy bridge deleted outright rather than maintained in parallel.
* **Discovery mechanisms are all positioned as a convenience layer that carries no trust**: TXT records untrusted, TLS pins never overridable, Bonjour a LAN convenience only.
* **Trust decisions concentrate in two places**: device pairing (challenge signature + metadata pinning + token rotation) and the scope system.

Reading this alongside the source analysis in Chapters 11–12, you'll find **documentation promises and implementation match closely** — uncommon in a fast-iterating open-source project.

It also explains why `SECURITY.md` feels comfortable declaring "usage outside documented recommendations" entirely out of scope (§44.4): because what the docs say is genuinely what the code does.
