Skip to content

WebSocket 服务

Gateway 的核心是一个基于 ws 库的 WebSocket 服务器,采用请求-响应-事件三种帧类型的协议进行通信。

协议帧

Source: src/gateway/protocol/index.ts

Gateway 定义了三种帧类型,所有帧都通过 AJV 进行 JSON Schema 校验:

typescript
// RequestFrame - Client → Server
interface RequestFrame {
  id: string;           // Request correlation ID
  method: string;       // e.g. "chat.send", "config.patch"
  params?: unknown;     // Method-specific parameters
}

// ResponseFrame - Server → Client
interface ResponseFrame {
  id: string;           // Matches request ID
  ok: boolean;          // Success flag
  result?: unknown;     // Response payload
  error?: string;       // Error message
  meta?: unknown;       // Additional metadata
}

// EventFrame - Server → Client (push)
interface EventFrame {
  event: string;        // Event name
  data?: unknown;       // Event payload
}

协议支持版本化(PROTOCOL_VERSION),确保客户端和服务器版本兼容。

服务器实现

Source: src/gateway/server.impl.ts

GatewayServer 是 Gateway 的核心运行时类型,管理所有连接和状态:

typescript
// src/gateway/server.impl.ts (simplified)
interface GatewayServer {
  config: GatewayConfig;
  channels: ChannelRegistry;
  agents: AgentRegistry;
  plugins: PluginRegistry;
  runtimeState: RuntimeState;
  // Health snapshots, presence versions, agent run sequences...
}

客户端 SDK

Source: src/gateway/client.ts

GatewayClient 类封装了客户端到 Gateway 的 WebSocket 连接:

typescript
// src/gateway/client.ts (simplified)
interface GatewayClientOptions {
  url: string;                    // ws://127.0.0.1:18789
  credentials: {
    token?: string;
    password?: string;
  };
  instance: string;              // Client instance identifier
  mode: "operator" | "node";    // Connection role
  scopes: string[];             // Permission scopes
  capabilities: string[];       // Feature capabilities
}

class GatewayClient {
  constructor(options: GatewayClientOptions);
  // Protocol version negotiation
  // Token/password auth
  // TLS fingerprint validation
  // Auto-reconnection handling
}

客户端特性:

  • 协议版本协商
  • Token / Password / Tailscale 认证
  • TLS 指纹验证
  • 自动重连

方法派发

Source: src/gateway/server-methods.ts

handleGatewayRequest() 是所有请求的入口点。它负责路由到对应的 handler 模块:

typescript
// src/gateway/server-methods.ts (simplified)
async function handleGatewayRequest(
  method: string,
  params: unknown,
  options: GatewayRequestOptions
): Promise<void> {
  // 1. Authorize the method call
  const authResult = authorizeGatewayMethod(method, options);
  if (!authResult.ok) {
    return respond(false, null, authResult.error);
  }

  // 2. Look up handler in registry
  const handler = coreGatewayHandlers[method];
  if (!handler) {
    return respond(false, null, `Unknown method: ${method}`);
  }

  // 3. Execute handler
  await handler(params, options);
}

授权检查

授权维度:

维度说明示例
角色operator(管理者)vs node(设备节点)operator 可以修改配置
作用域admin, read, write, approvals, pairingwrite scope 才能发消息
方法级每个方法声明所需 scopeconfig.patch 需要 admin

Handler 模块

Source: src/gateway/server-methods/ (43 个模块)

每个 handler 模块导出 GatewayRequestHandlers 类型的方法映射:

server-methods/
├── agent.ts         # Agent 管理
├── agents.ts        # 多 Agent 操作
├── browser.ts       # 浏览器控制
├── channels.ts      # 通道状态和生命周期
├── chat.ts          # 聊天交互
├── config.ts        # 配置读写
├── connect.ts       # 连接管理
├── cron.ts          # 定时任务
├── device.ts        # 设备管理
├── exec-approvals.ts # 执行审批
├── health.ts        # 健康检查
├── logs.ts          # 日志查询
├── models.ts        # 模型管理
├── nodes.ts         # 节点管理
├── send.ts          # 消息发送
├── sessions.ts      # 会话操作
├── skills.ts        # 技能管理
├── system.ts        # 系统信息
├── talk.ts          # 语音对话
├── tts.ts           # 文本转语音
├── update.ts        # 版本更新
├── usage.ts         # 使用统计
├── voicewake.ts     # 语音唤醒
├── web.ts           # Web UI
└── wizard.ts        # 向导

消息发送 Handler

Source: src/gateway/server-methods/send.ts

send handler 支持幂等性去重:

typescript
// src/gateway/server-methods/send.ts (simplified)
const sendHandlers = {
  async send(params, options) {
    // 1. Validate params (to, message, channel, idempotencyKey)
    // 2. Check idempotency deduplication
    if (idempotencyKey && seen.has(idempotencyKey)) {
      return respond(true, seen.get(idempotencyKey));
    }
    // 3. Resolve channel and outbound adapter
    // 4. Deliver message via outbound pipeline
    // 5. Cache result for idempotency
  }
};

认证实现

Source: src/gateway/auth.ts

关键安全措施:

  • Token 比较使用 timing-safe comparison,防止时间侧信道攻击
  • 本地直连检测(loopback + localhost 验证)
  • Tailscale 集成通过 whois 查询验证设备身份
typescript
// src/gateway/auth.ts (simplified)
interface ResolvedGatewayAuth {
  mode: "token" | "password";
  // ...
}

async function authorizeGatewayConnect(
  credentials: unknown,
  auth: ResolvedGatewayAuth
): Promise<AuthResult> {
  // Timing-safe token comparison
  // Tailscale user verification via whois
  // Fallback to token/password modes
}

小结

  • Gateway 基于 ws 库,使用 RequestFrame / ResponseFrame / EventFrame 三种帧类型
  • handleGatewayRequest() 是请求的统一入口,执行角色 → 作用域 → 方法级三层授权
  • 43 个 handler 模块覆盖所有功能:chat、send、config、sessions、channels 等
  • 认证支持 Token、Password、Tailscale 三种模式,使用 timing-safe 比较
  • 客户端 SDK (GatewayClient) 封装了连接管理、协议协商和自动重连

下一章:会话管理

OpenClaw 源码学习教程