> 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/ch12-gateway-protocol-and-type-system/12.5-source-deep-dive-frames-handshake-and-auth.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 12.5 Source Deep Dive: Three Frames, the Handshake, and Four Auth Layers

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~275,000 tokens, Output \~15,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

§12.1–12.4 covered protocol philosophy, TypeBox schemas, core methods, and authentication concepts. This section goes to the source: **what the frames look like, how the handshake proceeds, and how four authentication layers stack.**

§44.4 calls OpenClaw's authentication "layered, textbook-grade." This section is the evidence.

## 12.5.1 There Are Exactly Three Frame Types

The protocol lives under `src/gateway/protocol/schema/`, written in TypeBox and compiled to validators with AJV (`protocol/index.ts:253-262`):

```ts
// src/gateway/protocol/schema/frames.ts:125-163
export const RequestFrameSchema = Type.Object(
  { type: Type.Literal("req"), id: NonEmptyString, method: NonEmptyString,
    params: Type.Optional(Type.Unknown()) },
  { additionalProperties: false },
);
export const ResponseFrameSchema = Type.Object(
  { type: Type.Literal("res"), id: NonEmptyString, ok: Type.Boolean(),
    payload: Type.Optional(Type.Unknown()), error: Type.Optional(ErrorShapeSchema) },
  { additionalProperties: false },
);
export const EventFrameSchema = Type.Object(
  { type: Type.Literal("event"), event: NonEmptyString, payload: Type.Optional(Type.Unknown()),
    seq: Type.Optional(Type.Integer({ minimum: 0 })),
    stateVersion: Type.Optional(StateVersionSchema) },
  { additionalProperties: false },
);
// A discriminated union, so downstream codegen emits tight types for Swift/Kotlin clients
export const GatewayFrameSchema = Type.Union([...], { discriminator: "type" });
```

**This is not standard JSON-RPC 2.0** but a leaner custom framing:

* Request/response correlate through a string `id`;
* The server may push `event` frames at any time;
* `event.seq` and `stateVersion` (two monotonic version numbers for presence and health) let a client detect whether it missed a broadcast.

### Why a discriminated union

The design comment states the motive (`frames.ts:157-159`): a discriminated union lets downstream codegen emit **"tight types instead of all-optional blobs."**

That's a consideration only a protocol consumed simultaneously by TypeScript, Swift, and Kotlin would have.

Without a discriminator, the generated Swift type is one big struct with every field optional — every use site needs `if let`, and the compiler can't help. With it, Swift can generate a real enum where pattern matching is exhaustively checked.

`additionalProperties: false` is deliberate too: **unknown fields are rejected outright**, not tolerantly ignored. Protocol evolution goes through version numbers, not through "a few extra fields won't hurt."

### The type pipeline: one schema, three consumers

```
TypeBox schema (source of truth)
      │
      ├──→ JSON Schema  ──→ AJV validates inbound frames at runtime
      ├──→ Swift models ──→ pnpm protocol:gen:swift
      └──→ Kotlin models──→ pnpm protocol:gen
```

The Web UI simply **imports the main repo's protocol module across directories** (`ui/src/ui/gateway.ts:1-12`) — one source of truth front to back, skipping generation entirely.

### Idempotency keys

Side-effecting methods (`send`, `agent`, `chat.send`) **must carry an `idempotencyKey`**; the server keeps a short-lived dedup cache.

```
no event replay  +  idempotent requests  =  correctness basis for reconnecting over a flaky link
```

That combination deserves separate attention: the server caches no event history (saving memory and complexity), at the cost that a disconnected client may miss events — so the client must **proactively refresh its snapshot** after reconnecting. On the write side, clients may retry freely because the idempotency key prevents duplicate execution.

**Reads rely on snapshots; writes rely on idempotency.** A classic combination in flaky-network protocol design.

## 12.5.2 The Handshake: `connect` Is the First and Only Permitted Opening Frame

`PROTOCOL_VERSION = 3` (`protocol/schema/protocol-schemas.ts:301`).

Once the TCP connection is up, **the server immediately pushes a `connect.challenge` event** carrying a random nonce (`src/gateway/server/ws-connection.ts:174-179`) and starts a handshake timeout.

The client must answer with `{type:"req", method:"connect", params: ConnectParams}` — **otherwise the connection is closed with 1008** (`message-handler.ts:393-434`).

`ConnectParams` (`frames.ts:20-69`) contains:

| Field                         | Contents                                            |
| ----------------------------- | --------------------------------------------------- |
| `minProtocol` / `maxProtocol` | Acceptable protocol version range                   |
| `client`                      | id / mode / platform / deviceFamily / instanceId    |
| `caps` / `commands`           | Capability and command declarations (used by nodes) |
| `role` / `scopes`             | Role and scopes                                     |
| `device`                      | Public key + signature + nonce                      |
| `auth`                        | One of three: token / deviceToken / password        |

### What it looks like on the wire

```jsonc
// ← Gateway pushes the challenge
{ "type": "event", "event": "connect.challenge",
  "payload": { "nonce": "…", "ts": 1737264000000 } }

// → Client handshake (must be the first frame)
{ "type": "req", "id": "c1", "method": "connect", "params": {
    "minProtocol": 3, "maxProtocol": 3,
    "client": { "id": "openclaw-control-ui", "version": "…",
                "platform": "web", "mode": "webchat" },
    "role": "operator", "scopes": ["operator.read", "operator.write"],
    "device": { "id": "…", "publicKey": "…", "signature": "…",
                "signedAt": 1737264001000, "nonce": "…" },
    "auth": { "token": "…" } } }

// ← Handshake accepted
{ "type": "res", "id": "c1", "ok": true, "payload": {
    "type": "hello-ok", "protocol": 3,
    "auth": { "deviceToken": "…", "role": "operator", "scopes": ["…"] },
    "policy": { "maxPayload": …, "maxBufferedBytes": …, "tickIntervalMs": 15000 } } }
```

### `hello-ok` does four jobs in one frame

`hello-ok` (`message-handler.ts:1058-1081`) returns:

1. The negotiated protocol number, server version, and connection ID;
2. **The complete method and event lists** (`features.methods` / `events`);
3. **A state snapshot** (presence, health, `stateVersion`);
4. An optional canvas host URL, **a freshly issued device token**, and flow-control policy.

> **One round trip completes service discovery, state sync, and credential rotation.**
>
> This is worth copying. Compare the common approach: connect, then call `getCapabilities()`, then `getState()`, then `refreshToken()` — three round trips, three failure points, and a window of inconsistency between them.

Node handshakes differ only in parameters: `role: "node"`, `caps: ["camera", "canvas", "screen", …]`, `commands: ["camera.snap", "canvas.navigate", …]`, `permissions: {"camera.capture": true, …}`.

## 12.5.3 The Four Authentication Layers

### Layer 1: Shared credential (who you are)

`resolveGatewayAuth()` (`src/gateway/auth.ts:217-292`) normalizes config into four modes:

| Mode            | Notes                                                                                                               |
| --------------- | ------------------------------------------------------------------------------------------------------------------- |
| `token`         | **Default.** If missing at startup, one is **auto-generated and written back to config** (`server.impl.ts:433-441`) |
| `password`      | Password mode                                                                                                       |
| `trusted-proxy` | Trust user headers injected by a reverse proxy, **and only from addresses listed in `gateway.trustedProxies`**      |
| `none`          | No authentication                                                                                                   |

The verification entry point `authorizeGatewayConnect()` (`auth.ts:378-485`) has several details worth learning from:

```ts
// src/gateway/auth.ts:448-463
if (auth.mode === "token") {
  if (!auth.token) return { ok: false, reason: "token_missing_config" };
  if (!connectAuth?.token) {
    // Don't burn rate-limit slots for missing credentials — the client
    // simply hasn't provided a token yet (e.g. bare browser open).
    return { ok: false, reason: "token_missing" };
  }
  if (!safeEqualSecret(connectAuth.token, auth.token)) {
    limiter?.recordFailure(ip, rateLimitScope);
    return { ok: false, reason: "token_mismatch" };
  }
  limiter?.reset(ip, rateLimitScope);
  return { ok: true, method: "token" };
}
```

Three standard moves:

| Practice                                                                                | Defends against                                                    |
| --------------------------------------------------------------------------------------- | ------------------------------------------------------------------ |
| `safeEqualSecret` constant-time comparison                                              | Timing side channels                                               |
| **Missing credentials don't count toward rate limiting; wrong ones do**                 | Penalizing the normal case of "user hasn't typed the password yet" |
| Rate limiting keyed by IP + scope (shared-secret and device-token accounted separately) | One credential type being brute-forced affecting the other         |

### The special handling for browser origins

This part is clever.

**Any connection carrying an `Origin` header switches to a second rate limiter that does not exempt loopback**, and loopback browser requests are all accounted to the sentinel IP `198.18.0.1` (`message-handler.ts:92,105-127`).

**What does that defend against?** You open a malicious web page in your browser; it can attempt connections to `ws://127.0.0.1:18789`. If loopback were exempt from rate limiting, that page could brute-force tokens in the background indefinitely.

Bucketing all local browser requests under a sentinel IP puts this path back under rate limiting.

> **General lesson: a `localhost` exemption must distinguish "process direct connection" from "browser-originated."** The former requires local code execution; the latter only requires the user to visit a web page.

Browser connections also face an **Origin allowlist** check, and Host-header fallback matching emits a security metrics log (`message-handler.ts:499-532`).

### Tailscale identity: a fourth path

With `tailscale.mode=serve`, the Gateway trusts the `tailscale-user-login` header injected by the local tailscaled reverse proxy —

**but only after reverse-verifying it with a local `tailscale whois <ip>`** (`auth.ts:184-215`).

And it applies **only to the `ws-control-ui` surface** (`auth.ts:374-376`) — the HTTP API surface (`/v1/*`, `/tools/invoke`) deliberately does not accept this credential-free login.

`funnel` mode (public exposure) **refuses to start** when auth mode isn't password.

> **"Trust the header but verify it" is the correct posture for reverse-proxy setups.** Directly trusting `X-Forwarded-User` is a classic vulnerability — anyone who can reach the backend directly can forge it.

### Layer 2: Device identity (which device)

`ConnectParams.device` carries `{id, publicKey, signature, signedAt, nonce}`, verified item by item (`message-handler.ts:688-751`):

| Check                                                                          | Defends against                  |
| ------------------------------------------------------------------------------ | -------------------------------- |
| `deviceId` must be derived from the public key (`deriveDeviceIdFromPublicKey`) | Claiming someone else's deviceId |
| Signature timestamp skew within **2 minutes**                                  | Replaying old signatures         |
| **The nonce must equal the challenge nonce issued on this connection**         | Replay / cross-connection theft  |
| Signature verification                                                         | Forgery without the private key  |

The signature payload **binds every important claim**:

```ts
// src/gateway/device-auth.ts:36-54
export function buildDeviceAuthPayloadV3(params): string {
  return ["v3", params.deviceId, params.clientId, params.clientMode,
    params.role, scopes, String(params.signedAtMs), token, params.nonce,
    platform, deviceFamily].join("|");
}
```

**v3 additionally binds `platform` and `deviceFamily`** relative to v2 (the server tries v3 then v2, `message-handler.ts:176-207`).

Combined with metadata pinning on the pairing record: if a paired device reports a platform or device family different from what was approved, a `metadata-upgrade` re-pairing is triggered and a security audit log written (`message-handler.ts:905-931`).

> **A paired iPhone cannot quietly present itself as a Mac to obtain a broader command allowlist.**
>
> That's the value of binding claims into the signature: it proves not only *I am this device* but *the role, scopes, and platform I claim are these*.

### Layer 3: Pairing approval (are you allowed)

Passing credential checks is only step one. A connection with device identity must also clear pairing, and **four situations** trigger re-approval:

```
not paired / role upgrade / scope upgrade / metadata change
        ↓
requestDevicePairing creates a pending request
        ↓
broadcast device.pair.requested to all online operators
        ↓
close the connection with NOT_PAIRED
        ↓
reconnect after a human approves
```

(`message-handler.ts:835-895`)

**First-time pairing over a local direct connection (loopback + no browser Origin) may be silently auto-approved** (`message-handler.ts:129-141`).

> **Zero friction for the local CLI; explicit review for remote devices.** That line lets security and experience each have what they need — and note the "no browser Origin" condition, which denies malicious web pages the exemption.

### Layer 4: Device token

After approval the server issues a device token (`ensureDeviceToken`, `message-handler.ts:986-988`) in `hello-ok`'s `auth` field.

Thereafter the device can reconnect **presenting only the deviceToken** (`auth-context.ts:156-218`: after shared-credential failure, fall back to device token verification, with separate rate-limit accounting).

Three benefits:

1. **Rotating the global token doesn't affect already-paired devices**;
2. A single device can be **revoked independently** via `device.token.rotate/revoke`;
3. Phones don't have to store a long-lived master token that unlocks everything.

**Scopes are deny-by-default**: a connection with no device-identity binding has its self-declared scopes **cleared outright** (`message-handler.ts:490-495,628-633`).

Operator scopes come in five levels: `operator.read` / `write` / `admin` / `approvals` / `pairing`.

### The full handshake sequence

```mermaid
sequenceDiagram
    participant C as Client (app/CLI/UI/node)
    participant G as Gateway WS
    participant P as Pairing store
    participant O as Online operators

    G->>C: event connect.challenge {nonce}
    C->>G: req connect {minProtocol..maxProtocol, client, role, scopes,<br/>device{pubkey,sig(nonce)}, auth{token|deviceToken|password}}
    G->>G: protocol negotiation (PROTOCOL_VERSION=3)
    G->>G: Origin check (browsers) + scoped rate limiting
    G->>G: shared credential check (token/password/tailscale/trusted-proxy)
    G->>G: device signature check (id from pubkey, ±2min, nonce echo, v3→v2)
    alt not paired / role·scope·metadata upgrade
        G->>P: requestDevicePairing(silent = local direct?)
        alt not silent
            G->>O: event device.pair.requested
            G-->>C: res ok=false NOT_PAIRED {requestId} + close(1008)
            O->>G: req device.pair.approve
            C->>G: (reconnect, full handshake again)
        end
    end
    G->>P: ensureDeviceToken(deviceId, role, scopes)
    G-->>C: res hello-ok {snapshot, methods/events, deviceToken, policy}
    Note over C,G: from here only req frames accepted; server pushes events (tick/presence/agent/chat/...)
```

## 12.5.4 One Piece of Evolutionary Baggage: Two Pairing Stores

The repository contains **two pairing stores**:

| Store                                                                     | Purpose                  | Gates the WS handshake? |
| ------------------------------------------------------------------------- | ------------------------ | ----------------------- |
| Device pairing                                                            | Used in the WS handshake | **Yes**                 |
| The `node.pair.*` method family's store (`~/.openclaw/nodes/paired.json`) | Node pairing management  | **No**                  |

`docs/gateway/pairing.md` warns explicitly that the latter doesn't gate the WS handshake (Appendix G.1, item 6, repeats the warning).

**This is a dual track left by evolution.** The docs paper over it with a bolded warning, but merging would be better — §45.2 lists it under maintainability risks.

> The transferable lesson: **two mechanisms with similar semantics but different effects are among the most dangerous forms of technical debt.** A user will naturally assume "I configured pairing, so access is controlled," when what they configured was the other one. A documentation warning saves some people, not all of them.

***

## Section Summary

1. **Exactly three frame types** (req / res / event), not standard JSON-RPC; the discriminated union exists so Swift/Kotlin codegen emits **tight types instead of all-optional blobs**; `additionalProperties: false` rejects unknown fields.
2. **"No event replay + idempotent requests" is the correctness basis for flaky-network reconnection** — reads rely on snapshots, writes rely on idempotency, so the server needs no event replay buffer.
3. **`connect` is the only permitted opening frame**, preceded by a server-pushed `connect.challenge`; **`hello-ok` completes service discovery, state snapshot, and credential rotation in one frame** — one round trip instead of three calls.
4. **Layer 1, shared credential**: constant-time comparison, **missing credentials don't count toward rate limiting but wrong ones do**, IP+scope accounting; **connections with an `Origin` header lose the loopback exemption** and are bucketed under a sentinel IP — defending against malicious web pages brute-forcing tokens.
5. **The Tailscale identity header must be reverse-verified with a local `tailscale whois`**, and applies only to the Control UI / WS surface — **trust the proxy header but verify it** is the correct posture.
6. **Layer 2, device identity**: deviceId derived from the public key, ±2-minute window, nonce must be echoed, and **the signature payload binds role/scopes/platform/deviceFamily** — a paired iPhone can't present itself as a Mac for a wider command allowlist.
7. **Layer 3, pairing approval**: re-approval on not-paired / role upgrade / scope upgrade / metadata change; **local direct connections (loopback + no browser Origin) are silently approved, remote requires explicit review**.
8. **Layer 4, device token**: global token rotation doesn't affect paired devices, and devices can be revoked individually; **a connection with no device-identity binding has its self-declared scopes cleared** (deny by default).
9. **Two coexisting pairing stores are evolutionary baggage** — mechanisms with similar semantics but different effects are the most dangerous technical debt, and a documentation warning won't save everyone.
