Nyk commited on
Commit
395fc60
·
1 Parent(s): f99c465

fix(gateway): use stored token for websocket connect payload

Browse files
README.md CHANGED
@@ -289,6 +289,7 @@ All endpoints require authentication unless noted. Full reference below.
289
  | `GET` | `/api/webhooks/deliveries` | admin | Delivery history |
290
  | `GET/POST/PUT/DELETE` | `/api/alerts` | admin | Alert rules |
291
  | `GET/POST/PUT/DELETE` | `/api/gateways` | admin | Gateway connections |
 
292
  | `GET/PUT/DELETE/POST` | `/api/integrations` | admin | Integration management |
293
  | `POST` | `/api/github` | admin | Trigger GitHub Issues sync |
294
 
@@ -381,7 +382,7 @@ See [`.env.example`](.env.example) for the complete list. Key variables:
381
  | `OPENCLAW_GATEWAY_TOKEN` | No | Server-side gateway auth token |
382
  | `OPENCLAW_TOOLS_PROFILE` | No | Tools profile for `sessions_spawn` (recommended: `coding`) |
383
  | `NEXT_PUBLIC_GATEWAY_TOKEN` | No | Browser-side gateway auth token (must use `NEXT_PUBLIC_` prefix) |
384
- | `NEXT_PUBLIC_GATEWAY_CLIENT_ID` | No | Gateway UI client ID for websocket handshake (default: `control-ui`) |
385
  | `OPENCLAW_MEMORY_DIR` | No | Memory browser root (see note below) |
386
  | `MC_CLAUDE_HOME` | No | Path to `~/.claude` directory (default: `~/.claude`) |
387
  | `MC_TRUSTED_PROXIES` | No | Comma-separated trusted proxy IPs for XFF parsing |
 
289
  | `GET` | `/api/webhooks/deliveries` | admin | Delivery history |
290
  | `GET/POST/PUT/DELETE` | `/api/alerts` | admin | Alert rules |
291
  | `GET/POST/PUT/DELETE` | `/api/gateways` | admin | Gateway connections |
292
+ | `POST` | `/api/gateways/connect` | operator | Resolve websocket URL + token for selected gateway |
293
  | `GET/PUT/DELETE/POST` | `/api/integrations` | admin | Integration management |
294
  | `POST` | `/api/github` | admin | Trigger GitHub Issues sync |
295
 
 
382
  | `OPENCLAW_GATEWAY_TOKEN` | No | Server-side gateway auth token |
383
  | `OPENCLAW_TOOLS_PROFILE` | No | Tools profile for `sessions_spawn` (recommended: `coding`) |
384
  | `NEXT_PUBLIC_GATEWAY_TOKEN` | No | Browser-side gateway auth token (must use `NEXT_PUBLIC_` prefix) |
385
+ | `NEXT_PUBLIC_GATEWAY_CLIENT_ID` | No | Gateway UI client ID for websocket handshake (default: `openclaw-control-ui`) |
386
  | `OPENCLAW_MEMORY_DIR` | No | Memory browser root (see note below) |
387
  | `MC_CLAUDE_HOME` | No | Path to `~/.claude` directory (default: `~/.claude`) |
388
  | `MC_TRUSTED_PROXIES` | No | Comma-separated trusted proxy IPs for XFF parsing |
openapi.json CHANGED
@@ -3408,6 +3408,63 @@
3408
  }
3409
  }
3410
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3411
  "/api/github": {
3412
  "get": {
3413
  "tags": [
 
3408
  }
3409
  }
3410
  },
3411
+ "/api/gateways/connect": {
3412
+ "post": {
3413
+ "tags": [
3414
+ "Admin"
3415
+ ],
3416
+ "summary": "Resolve websocket connect payload for a gateway",
3417
+ "operationId": "connectGateway",
3418
+ "requestBody": {
3419
+ "required": true,
3420
+ "content": {
3421
+ "application/json": {
3422
+ "schema": {
3423
+ "type": "object",
3424
+ "required": [
3425
+ "id"
3426
+ ],
3427
+ "properties": {
3428
+ "id": {
3429
+ "type": "integer"
3430
+ }
3431
+ }
3432
+ }
3433
+ }
3434
+ }
3435
+ },
3436
+ "responses": {
3437
+ "200": {
3438
+ "description": "Resolved websocket URL and token metadata",
3439
+ "content": {
3440
+ "application/json": {
3441
+ "schema": {
3442
+ "type": "object",
3443
+ "properties": {
3444
+ "id": { "type": "integer" },
3445
+ "ws_url": { "type": "string" },
3446
+ "token": { "type": "string" },
3447
+ "token_set": { "type": "boolean" }
3448
+ }
3449
+ }
3450
+ }
3451
+ }
3452
+ },
3453
+ "400": {
3454
+ "$ref": "#/components/responses/BadRequest"
3455
+ },
3456
+ "401": {
3457
+ "$ref": "#/components/responses/Unauthorized"
3458
+ },
3459
+ "403": {
3460
+ "$ref": "#/components/responses/Forbidden"
3461
+ },
3462
+ "404": {
3463
+ "$ref": "#/components/responses/NotFound"
3464
+ }
3465
+ }
3466
+ }
3467
+ },
3468
  "/api/github": {
3469
  "get": {
3470
  "tags": [
src/app/api/gateways/connect/route.ts ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { requireRole } from '@/lib/auth'
3
+ import { getDatabase } from '@/lib/db'
4
+ import { buildGatewayWebSocketUrl } from '@/lib/gateway-url'
5
+
6
+ interface GatewayEntry {
7
+ id: number
8
+ host: string
9
+ port: number
10
+ token: string
11
+ }
12
+
13
+ function ensureTable(db: ReturnType<typeof getDatabase>) {
14
+ db.exec(`
15
+ CREATE TABLE IF NOT EXISTS gateways (
16
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
17
+ name TEXT NOT NULL UNIQUE,
18
+ host TEXT NOT NULL DEFAULT '127.0.0.1',
19
+ port INTEGER NOT NULL DEFAULT 18789,
20
+ token TEXT NOT NULL DEFAULT '',
21
+ is_primary INTEGER NOT NULL DEFAULT 0,
22
+ status TEXT NOT NULL DEFAULT 'unknown',
23
+ last_seen INTEGER,
24
+ latency INTEGER,
25
+ sessions_count INTEGER NOT NULL DEFAULT 0,
26
+ agents_count INTEGER NOT NULL DEFAULT 0,
27
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
28
+ updated_at INTEGER NOT NULL DEFAULT (unixepoch())
29
+ )
30
+ `)
31
+ }
32
+
33
+ /**
34
+ * POST /api/gateways/connect
35
+ * Resolves websocket URL and token for a selected gateway without exposing tokens in list payloads.
36
+ */
37
+ export async function POST(request: NextRequest) {
38
+ const auth = requireRole(request, 'operator')
39
+ if ('error' in auth) return NextResponse.json({ error: auth.error }, { status: auth.status })
40
+
41
+ const db = getDatabase()
42
+ ensureTable(db)
43
+
44
+ let id: number | null = null
45
+ try {
46
+ const body = await request.json()
47
+ id = Number(body?.id)
48
+ } catch {
49
+ return NextResponse.json({ error: 'Invalid request body' }, { status: 400 })
50
+ }
51
+
52
+ if (!id || !Number.isInteger(id) || id < 1) {
53
+ return NextResponse.json({ error: 'id is required' }, { status: 400 })
54
+ }
55
+
56
+ const gateway = db.prepare('SELECT id, host, port, token FROM gateways WHERE id = ?').get(id) as GatewayEntry | undefined
57
+ if (!gateway) {
58
+ return NextResponse.json({ error: 'Gateway not found' }, { status: 404 })
59
+ }
60
+
61
+ const ws_url = buildGatewayWebSocketUrl({
62
+ host: gateway.host,
63
+ port: gateway.port,
64
+ browserProtocol: request.nextUrl.protocol,
65
+ })
66
+
67
+ const envToken = (process.env.NEXT_PUBLIC_GATEWAY_TOKEN || process.env.NEXT_PUBLIC_WS_TOKEN || '').trim()
68
+ const token = (gateway.token || '').trim() || envToken
69
+
70
+ return NextResponse.json({
71
+ id: gateway.id,
72
+ ws_url,
73
+ token,
74
+ token_set: token.length > 0,
75
+ })
76
+ }
src/components/panels/multi-gateway-panel.tsx CHANGED
@@ -93,13 +93,26 @@ export function MultiGatewayPanel() {
93
  fetchGateways()
94
  }
95
 
96
- const connectTo = (gw: Gateway) => {
97
- const wsUrl = buildGatewayWebSocketUrl({
98
- host: gw.host,
99
- port: gw.port,
100
- browserProtocol: window.location.protocol,
101
- })
102
- connect(wsUrl, '') // token is handled by the gateway entry, not passed to frontend
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  }
104
 
105
  const probeAll = async () => {
 
93
  fetchGateways()
94
  }
95
 
96
+ const connectTo = async (gw: Gateway) => {
97
+ try {
98
+ const res = await fetch('/api/gateways/connect', {
99
+ method: 'POST',
100
+ headers: { 'Content-Type': 'application/json' },
101
+ body: JSON.stringify({ id: gw.id }),
102
+ })
103
+ if (!res.ok) return
104
+ const payload = await res.json()
105
+
106
+ const wsUrl = String(payload?.ws_url || buildGatewayWebSocketUrl({
107
+ host: gw.host,
108
+ port: gw.port,
109
+ browserProtocol: window.location.protocol,
110
+ }))
111
+ const token = String(payload?.token || '')
112
+ connect(wsUrl, token)
113
+ } catch {
114
+ // ignore: connection status will remain disconnected
115
+ }
116
  }
117
 
118
  const probeAll = async () => {
src/lib/__tests__/gateway-url.test.ts CHANGED
@@ -33,4 +33,12 @@ describe('buildGatewayWebSocketUrl', () => {
33
  browserProtocol: 'https:',
34
  })).toBe('wss://gateway.example.com:8443')
35
  })
 
 
 
 
 
 
 
 
36
  })
 
33
  browserProtocol: 'https:',
34
  })).toBe('wss://gateway.example.com:8443')
35
  })
36
+
37
+ it('drops path/query/hash when full dashboard URL is pasted', () => {
38
+ expect(buildGatewayWebSocketUrl({
39
+ host: 'https://bill.tail8b4599.ts.net:4443/sessions?foo=bar#frag',
40
+ port: 18789,
41
+ browserProtocol: 'https:',
42
+ })).toBe('wss://bill.tail8b4599.ts.net:4443')
43
+ })
44
  })
src/lib/gateway-url.ts CHANGED
@@ -38,6 +38,10 @@ export function buildGatewayWebSocketUrl(input: {
38
  try {
39
  const parsed = new URL(prefixed)
40
  parsed.protocol = normalizeProtocol(parsed.protocol)
 
 
 
 
41
  return parsed.toString().replace(/\/$/, '')
42
  } catch {
43
  return prefixed
 
38
  try {
39
  const parsed = new URL(prefixed)
40
  parsed.protocol = normalizeProtocol(parsed.protocol)
41
+ // Users often paste dashboard/session URLs; websocket connect should target gateway root.
42
+ parsed.pathname = '/'
43
+ parsed.search = ''
44
+ parsed.hash = ''
45
  return parsed.toString().replace(/\/$/, '')
46
  } catch {
47
  return prefixed
tests/gateway-connect.spec.ts ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { expect, test } from '@playwright/test'
2
+ import { API_KEY_HEADER } from './helpers'
3
+
4
+ test.describe('Gateway Connect API', () => {
5
+ const cleanup: number[] = []
6
+
7
+ test.afterEach(async ({ request }) => {
8
+ for (const id of cleanup) {
9
+ await request.delete('/api/gateways', {
10
+ headers: API_KEY_HEADER,
11
+ data: { id },
12
+ }).catch(() => {})
13
+ }
14
+ cleanup.length = 0
15
+ })
16
+
17
+ test('returns ws_url and token for selected gateway', async ({ request }) => {
18
+ const createRes = await request.post('/api/gateways', {
19
+ headers: API_KEY_HEADER,
20
+ data: {
21
+ name: `e2e-gw-${Date.now()}`,
22
+ host: 'https://example.tailnet.ts.net:4443/sessions',
23
+ port: 18789,
24
+ token: 'gw-token-123',
25
+ },
26
+ })
27
+ expect(createRes.status()).toBe(201)
28
+ const createBody = await createRes.json()
29
+ const gatewayId = createBody.gateway?.id as number
30
+ cleanup.push(gatewayId)
31
+
32
+ const connectRes = await request.post('/api/gateways/connect', {
33
+ headers: API_KEY_HEADER,
34
+ data: { id: gatewayId },
35
+ })
36
+ expect(connectRes.status()).toBe(200)
37
+ const connectBody = await connectRes.json()
38
+
39
+ expect(connectBody.ws_url).toBe('wss://example.tailnet.ts.net:4443')
40
+ expect(connectBody.token).toBe('gw-token-123')
41
+ expect(connectBody.token_set).toBe(true)
42
+ })
43
+
44
+ test('returns 404 for unknown gateway', async ({ request }) => {
45
+ const res = await request.post('/api/gateways/connect', {
46
+ headers: API_KEY_HEADER,
47
+ data: { id: 999999 },
48
+ })
49
+ expect(res.status()).toBe(404)
50
+ })
51
+ })