> 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.4-authentication-and-authorization.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 12.4 Authentication and Authorization

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~200,000 tokens, Output \~15,000 tokens (chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

Gateway is the front door to the OpenClaw system. Any client—whether it's a local CLI, a remote macOS application, or a Web control console in a browser—must pass Gateway's authentication to access the system. This section will deeply analyze OpenClaw's multi-layered authentication mechanism.

## 12.4.1 Gateway Token Authentication

Token authentication is the most basic authentication method. Its principle is simple: Gateway configures a secret (Token) at startup, and the client provides the same secret when connecting; if they match, authentication passes.

### Authentication Configuration Resolution

The `resolveGatewayAuth()` function in `src/gateway/auth.ts` is responsible for parsing authentication configuration:

```typescript
// src/gateway/auth.ts
export type ResolvedGatewayAuth = {
  mode: "token" | "password";  // Authentication mode
  token?: string;              // Token value
  password?: string;           // Password value
  allowTailscale: boolean;     // Whether to allow Tailscale authentication
};

export function resolveGatewayAuth(params: {
  authConfig?: GatewayAuthConfig | null;
  env?: NodeJS.ProcessEnv;
  tailscaleMode?: GatewayTailscaleMode;
}): ResolvedGatewayAuth {
  const authConfig = params.authConfig ?? {};
  const env = params.env ?? process.env;

  // Token source priority: config file > OPENCLAW env var > CLAWDBOT env var
  const token =
    authConfig.token ??
    env.OPENCLAW_GATEWAY_TOKEN ??
    env.CLAWDBOT_GATEWAY_TOKEN ??
    undefined;

  // Password source priority: same as above
  const password =
    authConfig.password ??
    env.OPENCLAW_GATEWAY_PASSWORD ??
    env.CLAWDBOT_GATEWAY_PASSWORD ??
    undefined;

  // Mode inference: if password is configured but mode is not specified, default to password mode
  const mode = authConfig.mode ?? (password ? "password" : "token");

  return { mode, token, password, allowTailscale };
}
```

Note the `CLAWDBOT_GATEWAY_TOKEN` and similar environment variables—these are backward compatibility with older versions (the project was previously named ClawdBot). In large projects, this kind of compatibility with old configuration names is a very common practice.

### Configuration Validation

At startup, `assertGatewayAuthConfigured()` ensures authentication is properly configured:

```typescript
export function assertGatewayAuthConfigured(auth: ResolvedGatewayAuth): void {
  if (auth.mode === "token" && !auth.token) {
    if (auth.allowTailscale) return; // Tailscale mode doesn't require Token
    throw new Error(
      "gateway auth mode is token, but no token was configured " +
      "(set gateway.auth.token or OPENCLAW_GATEWAY_TOKEN)"
    );
  }
  if (auth.mode === "password" && !auth.password) {
    throw new Error("gateway auth mode is password, but no password was configured");
  }
}
```

If Token is not configured and Tailscale authentication is not allowed, Gateway will refuse to start and provide a clear error message. This is a **Fail-Fast** design—it's better to discover problems at startup than to have security vulnerabilities at runtime.

### Connection Authentication Flow

When a client initiates a WebSocket connection and sends a `connect` message, Gateway calls `authorizeGatewayConnect()` for authentication:

```typescript
export async function authorizeGatewayConnect(params: {
  auth: ResolvedGatewayAuth;
  connectAuth?: ConnectAuth | null;
  req?: IncomingMessage;
  trustedProxies?: string[];
  tailscaleWhois?: TailscaleWhoisLookup;
}): Promise<GatewayAuthResult> {
  const { auth, connectAuth, req, trustedProxies } = params;
  const localDirect = isLocalDirectRequest(req, trustedProxies);

  // 1. Try Tailscale authentication (only for non-local requests)
  if (auth.allowTailscale && !localDirect) {
    const tailscaleCheck = await resolveVerifiedTailscaleUser({ req, ... });
    if (tailscaleCheck.ok) {
      return { ok: true, method: "tailscale", user: tailscaleCheck.user.login };
    }
  }

  // 2. Token authentication
  if (auth.mode === "token") {
    if (!auth.token)         return { ok: false, reason: "token_missing_config" };
    if (!connectAuth?.token)  return { ok: false, reason: "token_missing" };
    if (!safeEqual(connectAuth.token, auth.token))
      return { ok: false, reason: "token_mismatch" };
    return { ok: true, method: "token" };
  }

  // 3. Password authentication
  if (auth.mode === "password") {
    if (!auth.password)       return { ok: false, reason: "password_missing_config" };
    if (!connectAuth?.password) return { ok: false, reason: "password_missing" };
    if (!safeEqual(password, auth.password))
      return { ok: false, reason: "password_mismatch" };
    return { ok: true, method: "password" };
  }

  return { ok: false, reason: "unauthorized" };
}
```

The authentication result `GatewayAuthResult` contains authentication method information:

```typescript
export type GatewayAuthResult = {
  ok: boolean;
  method?: "token" | "password" | "tailscale" | "device-token";
  user?: string;     // For Tailscale authentication, record username
  reason?: string;   // Failure reason
};
```

### Timing-Safe Comparison

Note that Token comparison uses the `safeEqual()` function rather than simple `===`:

```typescript
function safeEqual(a: string, b: string): boolean {
  if (a.length !== b.length) return false;
  return timingSafeEqual(Buffer.from(a), Buffer.from(b));
}
```

> **Sidebar**: `timingSafeEqual` (timing-safe comparison) is a technique to prevent **timing attacks** (Timing Attack). Ordinary string comparison `===` returns `false` as soon as it finds the first mismatched character, meaning comparison time is proportional to "how many characters matched." Attackers can guess the key character by character by precisely measuring comparison time.
>
> `timingSafeEqual` takes **constant time** to complete comparison regardless of string content, eliminating the timing side-channel. This is a standard security primitive provided by Node.js's `crypto` module.

### Local Request Detection

The `isLocalDirectRequest()` function is used to determine if a request comes from the local machine:

```typescript
export function isLocalDirectRequest(
  req?: IncomingMessage,
  trustedProxies?: string[]
): boolean {
  const clientIp = resolveRequestClientIp(req, trustedProxies) ?? "";
  if (!isLoopbackAddress(clientIp)) return false;

  const host = getHostName(req.headers?.host);
  const hostIsLocal = host === "localhost" || host === "127.0.0.1" || host === "::1";
  const hostIsTailscaleServe = host.endsWith(".ts.net");

  const hasForwarded = Boolean(
    req.headers?.["x-forwarded-for"] ||
    req.headers?.["x-real-ip"] ||
    req.headers?.["x-forwarded-host"]
  );

  const remoteIsTrustedProxy = isTrustedProxyAddress(
    req.socket?.remoteAddress, trustedProxies
  );
  return (hostIsLocal || hostIsTailscaleServe) && (!hasForwarded || remoteIsTrustedProxy);
}
```

This function's logic is more complex than it appears because it needs to defend against **spoofing local requests** attacks:

1. **IP Check**: Client IP must be a loopback address (`127.0.0.1`, `::1`, etc.)
2. **Host Header Check**: The request's Host header must point to local (`localhost`, `127.0.0.1`) or Tailscale address
3. **Proxy Detection**: If proxy headers like `X-Forwarded-For` exist, only requests from trusted proxy source IPs are considered local

Why so complex? Consider this attack scenario: a malicious webpage makes a request to `http://localhost:18789` via JavaScript (cross-site request). If Gateway only checks IP without checking Host headers and proxy headers, it might be fooled into thinking it's a "local request" and skip authentication.

## 12.4.2 Device Pairing Mechanism

Token authentication is suitable for trusted environments (CLI, server-side), but for mobile devices (iOS/Android), configuring Token directly on the device is neither safe nor convenient. OpenClaw introduces a **device pairing** mechanism to solve this problem.

> **Sidebar**: Device pairing is a process of establishing a trust relationship between two devices, similar to Bluetooth pairing. The core idea is to verify both parties' identities through an **out-of-band channel**—such as a pairing code displayed on the screen—and then exchange keys to establish a persistent trust relationship.

### Pairing Flow

Device pairing is based on **asymmetric key cryptography** (Public Key Cryptography):

```
┌──────────────────────────────────────────────────────────────┐
│ Step 1: Device generates key pair                             │
│                                                              │
│ iPhone ──→ Generate Ed25519 key pair {publicKey, privateKey}│
│            Save privateKey to Keychain                        │
└──────────────────────────────────────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────┐
│ Step 2: Initiate pairing request                              │
│                                                              │
│ iPhone ──WebSocket──→ Gateway                                │
│   Send device.pair.request:                                   │
│   { deviceId, publicKey, clientId, role, scopes }            │
│                                                              │
│ Gateway ──event──→ Authenticated admin client (macOS app, CLI)│
│   Push device.pair.requested event:                           │
│   { requestId, deviceId, publicKey, platform, remoteIp }     │
└──────────────────────────────────────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────┐
│ Step 3: Admin approval                                        │
│                                                              │
│ macOS app displays pairing request:                           │
│   "iPhone (192.168.1.100) requests connection, approve?"      │
│                                                              │
│ User clicks "Approve" ──→ device.pair.approve({ requestId }) │
│ Gateway generates device token, returns to iPhone             │
└──────────────────────────────────────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────┐
│ Step 4: Subsequent connections use signature authentication   │
│                                                              │
│ iPhone ──→ Build auth payload ──→ Sign with privateKey ──→ Send│
│ Gateway ──→ Verify signature with stored publicKey ──→ Auth OK│
└──────────────────────────────────────────────────────────────┘
```

### Signature Payload Construction

When connecting subsequently, the device needs to sign a standardized payload. The `buildDeviceAuthPayload()` function defines the payload format:

```typescript
// src/gateway/device-auth.ts
export function buildDeviceAuthPayload(params: DeviceAuthPayloadParams): string {
  const version = params.version ?? (params.nonce ? "v2" : "v1");
  const scopes = params.scopes.join(",");
  const token = params.token ?? "";
  const base = [
    version,            // Payload version
    params.deviceId,    // Device ID
    params.clientId,    // Client type
    params.clientMode,  // Client mode
    params.role,        // Role
    scopes,             // Permission scopes
    String(params.signedAtMs), // Signature timestamp
    token,              // Device token
  ];
  if (version === "v2") {
    base.push(params.nonce ?? ""); // v2 version adds nonce for replay prevention
  }
  return base.join("|");
}
```

The payload uses pipe `|` to separate fields, similar to JWT payload format but simpler. Note several security designs:

1. **Signature Timestamp** (`signedAtMs`): Prevents signatures from being reused indefinitely. The server can reject signatures with timestamps that are too old.
2. **Version Evolution**: v2 version adds `nonce` (random number) to prevent **replay attacks**—even if an attacker intercepts a valid signature, they cannot reuse it because the nonce is different for each connection.

> **Sidebar**: Replay attack (Replay Attack) refers to an attacker intercepting a legitimate authentication message and resending it to gain unauthorized access. This is a classic attack class in network security. Countermeasures include timestamps (signature expiration), nonces (different each time), and sequence numbers (detect duplicates).

### Device Authentication in Connection Parameters

Recall the `device` field in `ConnectParams`:

```typescript
device: Type.Optional(Type.Object({
  id: NonEmptyString,          // Device ID
  publicKey: NonEmptyString,   // Public key
  signature: NonEmptyString,   // Signature
  signedAt: Type.Integer(),    // Signature timestamp
  nonce: Type.Optional(NonEmptyString), // Nonce (v2)
}));
```

After receiving this information, Gateway:

1. Looks up `device.id` in the list of paired devices
2. Uses the stored public key to verify if `signature` matches the payload
3. Checks if `signedAt` is within a reasonable time window
4. If verification passes, assigns the corresponding role and permissions

## 12.4.3 Local Connection Auto-Approval vs Remote Connection Challenge Signature

OpenClaw's authentication strategy varies in strictness depending on the connection source:

### Local Connections

When `isLocalDirectRequest()` returns `true` (such as CLI connecting to local Gateway), authentication requirements are relatively relaxed:

* Local CLI can directly use Token from configuration file
* Local Web control console can access without password after Origin check
* Device pairing requests from local machine can be auto-approved

This is because local connection means the attacker has already gained access to the host, at which point Gateway's authentication is no longer the primary security defense.

### Remote Connections

For remote connections from the network, authentication is stricter:

1. **Device must be paired**: Cannot directly use Token (Token might leak during network transmission)
2. **Use challenge-response signature**: Gateway can send a random challenge (nonce), device must sign and return it
3. **Tailscale verification**: If connecting through Tailscale VPN, need to verify Tailscale user identity

> **Sidebar**: Challenge-response authentication (Challenge-Response Authentication) is a classic authentication pattern. The server sends a random number (challenge), the client encrypts or signs the random number with a key and returns it (response). The server verifies if the response is correct. The advantage of this approach is that the key itself is never transmitted over the network. NTLM, CRAM-MD5, and SSH public key authentication all use similar mechanisms.

### Tailscale Authentication

OpenClaw has special integration support for Tailscale VPN. When Gateway is deployed in Tailscale Serve mode, it can leverage Tailscale's identity verification:

```typescript
async function resolveVerifiedTailscaleUser(params: {
  req?: IncomingMessage;
  tailscaleWhois: TailscaleWhoisLookup;
}): Promise<{ ok: true; user: TailscaleUser } | { ok: false; reason: string }> {
  // 1. Check Tailscale-injected user header
  const tailscaleUser = getTailscaleUser(req);
  if (!tailscaleUser) return { ok: false, reason: "tailscale_user_missing" };

  // 2. Verify request truly comes from Tailscale proxy
  if (!isTailscaleProxyRequest(req))
    return { ok: false, reason: "tailscale_proxy_missing" };

  // 3. Verify user identity through Tailscale Whois API
  const clientIp = resolveTailscaleClientIp(req);
  const whois = await tailscaleWhois(clientIp);

  // 4. Cross-verify: username in HTTP header must match Whois result
  if (normalizeLogin(whois.login) !== normalizeLogin(tailscaleUser.login))
    return { ok: false, reason: "tailscale_user_mismatch" };

  return { ok: true, user: { ... } };
}
```

> **Sidebar**: Tailscale is a zero-configuration VPN service based on WireGuard. Its Serve feature allows exposing local services to the Tailscale network and automatically injects user identity information into each request (via HTTP headers). OpenClaw leverages this feature to implement "authenticate Gateway through VPN identity"—if you're in the Tailscale network, you don't need to separately configure Token.

The multi-layered verification in the verification flow (check HTTP header → verify proxy identity → Whois API cross-verification) is to prevent **HTTP header spoofing** attacks—if an attacker can send requests directly to Gateway and spoof the `Tailscale-User-Login` header, without Whois cross-verification it would bypass authentication.

## 12.4.4 Origin Check to Prevent Cross-Site WebSocket Hijacking

WebSocket connections in browsers face a special security threat—**Cross-Site WebSocket Hijacking** (CSWSH).

> **Sidebar**: Cross-site WebSocket hijacking is a variant of CSRF (Cross-Site Request Forgery) in the WebSocket scenario. When a user has both a malicious webpage and OpenClaw control console open in the browser simultaneously, the malicious webpage can try to establish a WebSocket connection to `ws://localhost:18789`. Since the browser automatically carries cookies, if Gateway doesn't check the request source, the malicious webpage might successfully establish a connection and control the user's AI assistant.

### Origin Check Logic

`src/gateway/origin-check.ts` implements Origin checking:

```typescript
export function checkBrowserOrigin(params: {
  requestHost?: string;      // Request Host header
  origin?: string;           // Request Origin header
  allowedOrigins?: string[]; // Configured whitelist
}): OriginCheckResult {
  // 1. Origin header must exist and be valid
  const parsedOrigin = parseOrigin(params.origin);
  if (!parsedOrigin) {
    return { ok: false, reason: "origin missing or invalid" };
  }

  // 2. Check whitelist
  const allowlist = (params.allowedOrigins ?? [])
    .map((value) => value.trim().toLowerCase())
    .filter(Boolean);
  if (allowlist.includes(parsedOrigin.origin)) {
    return { ok: true };
  }

  // 3. Same-origin check: Origin's host must match request's Host header
  const requestHost = normalizeHostHeader(params.requestHost);
  if (requestHost && parsedOrigin.host === requestHost) {
    return { ok: true };
  }

  // 4. Loopback exception: localhost to localhost always allowed
  const requestHostname = resolveHostName(requestHost);
  if (isLoopbackHost(parsedOrigin.hostname) && isLoopbackHost(requestHostname)) {
    return { ok: true };
  }

  return { ok: false, reason: "origin not allowed" };
}
```

The check logic follows the **principle of least privilege**, judging in the following order:

1. **Origin header must exist**: Browsers always attach Origin header when making cross-site requests. If there's no Origin header, it might be a non-browser client (doesn't need Origin check) or Origin was stripped by a proxy.
2. **Whitelist first**: If the request source is in the configured whitelist, pass directly. This allows administrators to explicitly authorize specific external sources.
3. **Same-origin policy**: If the Origin's host part matches the request's Host header (i.e., same domain), allow. This is the standard same-origin policy.
4. **Loopback exception**: If both Origin and request target are local addresses (localhost, 127.0.0.1, etc.), allow. This allows the Web control console to work normally during local development, even if ports differ.

### Helper Functions

Several helper functions used in Origin checking handle various edge cases:

```typescript
// Parse Origin string into structured data
function parseOrigin(originRaw?: string) {
  const trimmed = (originRaw ?? "").trim();
  if (!trimmed || trimmed === "null") return null; // "null" is a special value
  try {
    const url = new URL(trimmed);
    return {
      origin: url.origin.toLowerCase(),
      host: url.host.toLowerCase(),
      hostname: url.hostname.toLowerCase(),
    };
  } catch {
    return null;
  }
}

// Determine if hostname is a loopback address
function isLoopbackHost(hostname: string): boolean {
  return hostname === "localhost"
    || hostname === "::1"
    || hostname === "127.0.0.1"
    || hostname.startsWith("127.");
}
```

Note the handling of `"null"` string in `parseOrigin`—browsers send `Origin: null` (literal string) in some cases (such as `file://` protocol pages), which should not be treated as a valid Origin.

### Authentication Mechanism Summary

Let's summarize OpenClaw's multi-layered authentication mechanism in a table:

| Authentication Method | Applicable Scenario            | Security Level | Complexity |
| --------------------- | ------------------------------ | -------------- | ---------- |
| Token                 | Local CLI, trusted server-side | Medium         | Low        |
| Password              | Password-protected deployment  | Medium         | Low        |
| Device Pairing        | iOS/Android/macOS apps         | High           | High       |
| Tailscale             | VPN deployment environment     | High           | Medium     |
| Origin Check          | Browser WebSocket              | Supplementary  | Low        |
| Local Direct          | Local machine connection       | —              | —          |

These mechanisms are not mutually exclusive but **layered and stacked**:

```
┌─────────────────────────────────┐
│   Origin Check (Browser Layer)   │ ← Prevent CSWSH
├─────────────────────────────────┤
│ Token / Password / Device Sig    │ ← Identity authentication
├─────────────────────────────────┤
│ Local Direct Detection           │ ← Environment awareness
├─────────────────────────────────┤
│ Tailscale Identity Verification  │ ← VPN layer authentication
├─────────────────────────────────┤
│ TLS Encryption (HTTPS/WSS)       │ ← Transport layer security
└─────────────────────────────────┘
```

***

## Summary of This Section

OpenClaw's authentication system design embodies the **defense in depth** security principle:

1. **Multiple authentication methods**: Token, password, device pairing, Tailscale—use the most appropriate method for each scenario
2. **Timing-safe comparison**: Use `timingSafeEqual` to prevent timing attacks
3. **Device pairing's asymmetric key design**: Private key never leaves the device, identity verified through signature
4. **Replay attack protection**: v2 protocol introduces nonce, timestamp limits signature validity period
5. **Origin check**: CSWSH protection for browser environment
6. **Local connection optimization**: Provide convenient authentication path for requests from local machine

***

## Chapter 12 Summary

In this chapter, we started from protocol design philosophy and progressively deepened our understanding of OpenClaw Gateway's protocol and type system:

* **4.1 Protocol Design Philosophy**: Reasons for choosing WebSocket, hybrid frame mode of request-response-event, idempotency key mechanism
* **4.2 TypeBox Type Schema**: Type system with single definition for multi-platform reuse, JSON Schema and Swift code generation pipeline
* **4.3 Core Methods and Events**: Functional families of 80+ methods, core operations like `agent`/`send`/`sessions.*`, 18 event types
* **4.4 Authentication and Authorization**: Multi-layered security mechanisms of Token authentication, device pairing, Tailscale integration, Origin check

This protocol and type system is the foundational communication layer for all upper-level OpenClaw functions (sessions, Agent, tools, channels, etc.). In the following chapters, we will deeply analyze the implementation of various subsystems above Gateway based on these protocol methods.

***

> ### 🔬 Going Deeper: 12.5 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**12.5 Source Deep Dive: Three Frames, the Handshake, and Four Auth Layers**](https://www.openclawbook.xyz/en/ch12-gateway-protocol-and-type-system/12.5-source-deep-dive-frames-handshake-and-auth.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
