Stabilize OpenClaw dashboard websocket sidecar
This commit is contained in:
@@ -19,8 +19,12 @@ function buildBrowserGatewayUrl(request: Request, requestUrl: URL, proxiedUrl: s
|
|||||||
const forwardedHost = firstHeaderValue(request.headers.get('x-forwarded-host'))
|
const forwardedHost = firstHeaderValue(request.headers.get('x-forwarded-host'))
|
||||||
const host = forwardedHost || request.headers.get('host') || requestUrl.host
|
const host = forwardedHost || request.headers.get('host') || requestUrl.host
|
||||||
const protocol = (forwardedProtocol || requestUrl.protocol.replace(/:$/, '')) === 'https' ? 'wss:' : 'ws:'
|
const protocol = (forwardedProtocol || requestUrl.protocol.replace(/:$/, '')) === 'https' ? 'wss:' : 'ws:'
|
||||||
|
const wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || '3001'
|
||||||
|
const gatewayHost = wsProxyPort
|
||||||
|
? new URL(`${requestUrl.protocol}//${host}`).hostname + `:${wsProxyPort}`
|
||||||
|
: host
|
||||||
|
|
||||||
return `${protocol}//${host}${proxiedUrl}`
|
return `${protocol}//${gatewayHost}${proxiedUrl}`
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildLaunchUrl(request: Request, requestUrl: URL, proxiedUrl: string, bootstrapUrl: string | null) {
|
function buildLaunchUrl(request: Request, requestUrl: URL, proxiedUrl: string, bootstrapUrl: string | null) {
|
||||||
|
|||||||
@@ -140,8 +140,37 @@ function isBootstrapScriptRequest(requestUrl: URL, proxyPrefix: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function bootstrapScriptResponse(proxyPrefix: string) {
|
function bootstrapScriptResponse(proxyPrefix: string) {
|
||||||
|
const wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || '3001'
|
||||||
|
const script = `
|
||||||
|
(() => {
|
||||||
|
const proxyPrefix = ${JSON.stringify(proxyPrefix)};
|
||||||
|
const wsProxyPort = ${JSON.stringify(wsProxyPort)};
|
||||||
|
window.__OPENCLAW_CONTROL_UI_BASE_PATH__ = proxyPrefix;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||||
|
const gatewayHost = wsProxyPort ? window.location.hostname + ':' + wsProxyPort : window.location.host;
|
||||||
|
const gatewayUrl = protocol + '//' + gatewayHost + proxyPrefix;
|
||||||
|
const settingsKey = 'openclaw.control.settings.v1';
|
||||||
|
const tokenPrefix = 'openclaw.control.token.v1:';
|
||||||
|
const tokenScope = gatewayUrl;
|
||||||
|
const hashParams = new URLSearchParams(window.location.hash.startsWith('#') ? window.location.hash.slice(1) : window.location.hash);
|
||||||
|
const token = (hashParams.get('token') || '').trim();
|
||||||
|
const rawSettings = window.localStorage.getItem(settingsKey);
|
||||||
|
const settings = rawSettings ? JSON.parse(rawSettings) : {};
|
||||||
|
|
||||||
|
settings.gatewayUrl = gatewayUrl;
|
||||||
|
window.localStorage.setItem(settingsKey, JSON.stringify(settings));
|
||||||
|
window.sessionStorage.removeItem('openclaw.control.token.v1');
|
||||||
|
if (token) window.sessionStorage.setItem(tokenPrefix + tokenScope, token);
|
||||||
|
} catch {
|
||||||
|
// Best-effort compatibility bridge for OpenClaw's persisted UI settings.
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
`
|
||||||
|
|
||||||
return new NextResponse(
|
return new NextResponse(
|
||||||
`window.__OPENCLAW_CONTROL_UI_BASE_PATH__=${JSON.stringify(proxyPrefix)};\n`,
|
script,
|
||||||
{
|
{
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: {
|
headers: {
|
||||||
|
|||||||
+110
-42
@@ -1,11 +1,14 @@
|
|||||||
import http from 'node:http'
|
import http from 'node:http'
|
||||||
import crypto from 'node:crypto'
|
import crypto from 'node:crypto'
|
||||||
|
import net from 'node:net'
|
||||||
|
import tls from 'node:tls'
|
||||||
import next from 'next'
|
import next from 'next'
|
||||||
import { WebSocketServer, WebSocket } from 'ws'
|
import { WebSocketServer, WebSocket } from 'ws'
|
||||||
|
|
||||||
const dev = process.env.NODE_ENV !== 'production'
|
const dev = process.env.NODE_ENV !== 'production'
|
||||||
const hostname = process.env.HOSTNAME || process.env.HOST || '0.0.0.0'
|
const hostname = process.env.HOSTNAME || process.env.HOST || '0.0.0.0'
|
||||||
const port = Number(process.env.PORT || 3000)
|
const port = Number(process.env.PORT || 3000)
|
||||||
|
const dashboardWsProxyPort = Number(process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT || 3001)
|
||||||
const terminalServerUrl = new URL(process.env.TERMINAL_SERVER_URL || 'http://127.0.0.1:3011')
|
const terminalServerUrl = new URL(process.env.TERMINAL_SERVER_URL || 'http://127.0.0.1:3011')
|
||||||
const terminalWsProtocol = terminalServerUrl.protocol === 'https:' ? 'wss:' : 'ws:'
|
const terminalWsProtocol = terminalServerUrl.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||||
const terminalProxyPath = '/api/openshell/terminal/live/ws'
|
const terminalProxyPath = '/api/openshell/terminal/live/ws'
|
||||||
@@ -196,58 +199,63 @@ const handleUpgrade = typeof app.getUpgradeHandler === 'function'
|
|||||||
await app.prepare()
|
await app.prepare()
|
||||||
|
|
||||||
const server = http.createServer((req, res) => handle(req, res))
|
const server = http.createServer((req, res) => handle(req, res))
|
||||||
|
const dashboardWsProxyServer = http.createServer((_, res) => {
|
||||||
|
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
||||||
|
res.end('OpenClaw dashboard websocket proxy only')
|
||||||
|
})
|
||||||
const clientWss = new WebSocketServer({ noServer: true })
|
const clientWss = new WebSocketServer({ noServer: true })
|
||||||
|
|
||||||
function buildRawDashboardUpgradeHeaders(req, upstreamWsUrl) {
|
function buildRawDashboardUpgradeHeaders(req, upstreamWsUrl) {
|
||||||
const headers = { ...req.headers }
|
|
||||||
const upstreamOrigin = new URL(upstreamWsUrl.toString())
|
const upstreamOrigin = new URL(upstreamWsUrl.toString())
|
||||||
upstreamOrigin.protocol = upstreamOrigin.protocol === 'wss:' ? 'https:' : 'http:'
|
upstreamOrigin.protocol = upstreamOrigin.protocol === 'wss:' ? 'https:' : 'http:'
|
||||||
upstreamOrigin.pathname = '/'
|
upstreamOrigin.pathname = '/'
|
||||||
upstreamOrigin.search = ''
|
upstreamOrigin.search = ''
|
||||||
upstreamOrigin.hash = ''
|
upstreamOrigin.hash = ''
|
||||||
headers.host = upstreamWsUrl.host
|
const headers = []
|
||||||
headers.origin = upstreamOrigin.origin
|
const seen = new Set()
|
||||||
|
|
||||||
|
for (let i = 0; i < req.rawHeaders.length; i += 2) {
|
||||||
|
const name = req.rawHeaders[i]
|
||||||
|
const value = req.rawHeaders[i + 1]
|
||||||
|
const lowerName = name.toLowerCase()
|
||||||
|
seen.add(lowerName)
|
||||||
|
if (lowerName === 'host') {
|
||||||
|
headers.push(`Host: ${upstreamWsUrl.host}`)
|
||||||
|
} else if (lowerName === 'origin') {
|
||||||
|
headers.push(`Origin: ${upstreamOrigin.origin}`)
|
||||||
|
} else {
|
||||||
|
headers.push(`${name}: ${value}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!seen.has('host')) headers.push(`Host: ${upstreamWsUrl.host}`)
|
||||||
|
if (!seen.has('origin')) headers.push(`Origin: ${upstreamOrigin.origin}`)
|
||||||
return headers
|
return headers
|
||||||
}
|
}
|
||||||
|
|
||||||
function writeBadGateway(socket, reason) {
|
|
||||||
if (socket.destroyed) return
|
|
||||||
socket.write(
|
|
||||||
'HTTP/1.1 502 Bad Gateway\r\n' +
|
|
||||||
'Connection: close\r\n' +
|
|
||||||
'Content-Type: text/plain; charset=utf-8\r\n' +
|
|
||||||
`Content-Length: ${Buffer.byteLength(reason)}\r\n` +
|
|
||||||
'\r\n' +
|
|
||||||
reason
|
|
||||||
)
|
|
||||||
socket.destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
function tunnelDashboardUpgrade(req, socket, head, upstreamWsUrl, instanceId) {
|
function tunnelDashboardUpgrade(req, socket, head, upstreamWsUrl, instanceId) {
|
||||||
const upstreamReq = http.request({
|
const isSecure = upstreamWsUrl.protocol === 'wss:'
|
||||||
hostname: upstreamWsUrl.hostname,
|
const port = Number(upstreamWsUrl.port || (isSecure ? 443 : 80))
|
||||||
port: upstreamWsUrl.port || '80',
|
const upstreamSocket = isSecure
|
||||||
path: `${upstreamWsUrl.pathname}${upstreamWsUrl.search}`,
|
? tls.connect({ host: upstreamWsUrl.hostname, port, servername: upstreamWsUrl.hostname })
|
||||||
method: 'GET',
|
: net.connect({ host: upstreamWsUrl.hostname, port })
|
||||||
headers: buildRawDashboardUpgradeHeaders(req, upstreamWsUrl),
|
const upstreamPath = `${upstreamWsUrl.pathname || '/'}${upstreamWsUrl.search || ''}`
|
||||||
})
|
const requestHead = [
|
||||||
|
`GET ${upstreamPath} HTTP/1.1`,
|
||||||
upstreamReq.on('upgrade', (upstreamRes, upstreamSocket, upstreamHead) => {
|
...buildRawDashboardUpgradeHeaders(req, upstreamWsUrl),
|
||||||
const responseHead = [
|
|
||||||
'HTTP/1.1 101 Switching Protocols',
|
|
||||||
...Object.entries(upstreamRes.headers).flatMap(([key, value]) => {
|
|
||||||
if (Array.isArray(value)) return value.map((entry) => `${key}: ${entry}`)
|
|
||||||
return typeof value === 'undefined' ? [] : [`${key}: ${value}`]
|
|
||||||
}),
|
|
||||||
'',
|
'',
|
||||||
'',
|
'',
|
||||||
].join('\r\n')
|
].join('\r\n')
|
||||||
|
let opened = false
|
||||||
|
let upstreamBytes = 0
|
||||||
|
let clientBytes = 0
|
||||||
|
|
||||||
socket.write(responseHead)
|
upstreamSocket.once(isSecure ? 'secureConnect' : 'connect', () => {
|
||||||
if (upstreamHead?.length) socket.write(upstreamHead)
|
opened = true
|
||||||
|
upstreamSocket.write(requestHead)
|
||||||
if (head?.length) upstreamSocket.write(head)
|
if (head?.length) upstreamSocket.write(head)
|
||||||
upstreamSocket.pipe(socket)
|
upstreamSocket.resume()
|
||||||
socket.pipe(upstreamSocket)
|
socket.resume()
|
||||||
logBridge('dashboard-tunnel-open', {
|
logBridge('dashboard-tunnel-open', {
|
||||||
path: req.url || '/',
|
path: req.url || '/',
|
||||||
upstreamUrl: upstreamWsUrl.toString(),
|
upstreamUrl: upstreamWsUrl.toString(),
|
||||||
@@ -256,23 +264,53 @@ function tunnelDashboardUpgrade(req, socket, head, upstreamWsUrl, instanceId) {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
upstreamReq.on('response', (upstreamRes) => {
|
upstreamSocket.on('data', (chunk) => {
|
||||||
writeBadGateway(socket, `OpenClaw dashboard websocket upgrade rejected: ${upstreamRes.statusCode || 502}`)
|
upstreamBytes += chunk.length
|
||||||
upstreamRes.resume()
|
if (!socket.destroyed) socket.write(chunk)
|
||||||
})
|
})
|
||||||
|
|
||||||
upstreamReq.on('error', (error) => {
|
socket.on('data', (chunk) => {
|
||||||
|
clientBytes += chunk.length
|
||||||
|
if (!upstreamSocket.destroyed) upstreamSocket.write(chunk)
|
||||||
|
})
|
||||||
|
|
||||||
|
upstreamSocket.on('error', (error) => {
|
||||||
logBridge('dashboard-tunnel-error', {
|
logBridge('dashboard-tunnel-error', {
|
||||||
path: req.url || '/',
|
path: req.url || '/',
|
||||||
upstreamUrl: upstreamWsUrl.toString(),
|
upstreamUrl: upstreamWsUrl.toString(),
|
||||||
instanceId,
|
instanceId,
|
||||||
reason: error instanceof Error ? error.message : 'upstream error',
|
reason: error instanceof Error ? error.message : 'upstream error',
|
||||||
})
|
})
|
||||||
writeBadGateway(socket, 'OpenClaw dashboard websocket upstream unavailable')
|
if (!opened && !socket.destroyed) {
|
||||||
|
socket.end('HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\nContent-Length: 0\r\n\r\n')
|
||||||
|
} else {
|
||||||
|
socket.destroy()
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
socket.on('error', () => upstreamReq.destroy())
|
upstreamSocket.on('close', (hadError) => {
|
||||||
upstreamReq.end()
|
logBridge('dashboard-tunnel-upstream-close', {
|
||||||
|
path: req.url || '/',
|
||||||
|
upstreamUrl: upstreamWsUrl.toString(),
|
||||||
|
instanceId,
|
||||||
|
hadError,
|
||||||
|
upstreamBytes,
|
||||||
|
clientBytes,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.on('error', () => upstreamSocket.destroy())
|
||||||
|
socket.on('close', (hadError) => {
|
||||||
|
logBridge('dashboard-tunnel-client-close', {
|
||||||
|
path: req.url || '/',
|
||||||
|
upstreamUrl: upstreamWsUrl.toString(),
|
||||||
|
instanceId,
|
||||||
|
hadError,
|
||||||
|
upstreamBytes,
|
||||||
|
clientBytes,
|
||||||
|
})
|
||||||
|
upstreamSocket.destroy()
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
clientWss.on('connection', (client, req) => {
|
clientWss.on('connection', (client, req) => {
|
||||||
@@ -418,6 +456,29 @@ server.on('upgrade', (req, socket, head) => {
|
|||||||
socket.destroy()
|
socket.destroy()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
dashboardWsProxyServer.on('upgrade', (req, socket, head) => {
|
||||||
|
if (
|
||||||
|
(req.url || '').startsWith(legacyDashboardProxyPrefix) ||
|
||||||
|
(req.url || '').startsWith(instancesProxyPrefix)
|
||||||
|
) {
|
||||||
|
const { upstreamWsUrl, instanceId } = resolveDashboardUpstream(req)
|
||||||
|
logBridge('dashboard-sidecar-upgrade-accepted', {
|
||||||
|
path: req.url || '/',
|
||||||
|
upstreamUrl: upstreamWsUrl.toString(),
|
||||||
|
instanceId,
|
||||||
|
remoteAddress: req.socket.remoteAddress || 'unknown',
|
||||||
|
})
|
||||||
|
tunnelDashboardUpgrade(req, socket, head, upstreamWsUrl, instanceId)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
logBridge('dashboard-sidecar-upgrade-rejected', {
|
||||||
|
path: req.url || '/',
|
||||||
|
remoteAddress: req.socket.remoteAddress || 'unknown',
|
||||||
|
})
|
||||||
|
socket.destroy()
|
||||||
|
})
|
||||||
|
|
||||||
server.listen(port, hostname, () => {
|
server.listen(port, hostname, () => {
|
||||||
console.log(`dashboard server listening on http://${hostname}:${port}`)
|
console.log(`dashboard server listening on http://${hostname}:${port}`)
|
||||||
logBridge('server-listening', {
|
logBridge('server-listening', {
|
||||||
@@ -427,3 +488,10 @@ server.listen(port, hostname, () => {
|
|||||||
soleOwnerPath: terminalProxyPath,
|
soleOwnerPath: terminalProxyPath,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
dashboardWsProxyServer.listen(dashboardWsProxyPort, hostname, () => {
|
||||||
|
logBridge('dashboard-sidecar-listening', {
|
||||||
|
hostname,
|
||||||
|
port: dashboardWsProxyPort,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
@@ -52,7 +52,8 @@ assert.match(telemetrySource, /authoritySource: "runtimeAuthority"/, 'inventory
|
|||||||
assert.match(telemetrySource, /authorities: authorities\.map\(/, 'inventory route must expose per-sandbox authority metadata')
|
assert.match(telemetrySource, /authorities: authorities\.map\(/, 'inventory route must expose per-sandbox authority metadata')
|
||||||
assert.match(openshellHostSource, /const canMintBootstrapFromCli = instance\.id === defaultInstance\.id/, 'bootstrap minting should only use CLI for the default OpenClaw instance')
|
assert.match(openshellHostSource, /const canMintBootstrapFromCli = instance\.id === defaultInstance\.id/, 'bootstrap minting should only use CLI for the default OpenClaw instance')
|
||||||
assert.match(packageJsonSource, /"dev": "node server\.mjs"/, 'development script must run through the custom server so websocket proxy bridges are active')
|
assert.match(packageJsonSource, /"dev": "node server\.mjs"/, 'development script must run through the custom server so websocket proxy bridges are active')
|
||||||
assert.match(serverSource, /const dashboardWss = new WebSocketServer\(\{ noServer: true \}\)/, 'custom server must provision a dedicated dashboard websocket bridge')
|
assert.match(serverSource, /const dashboardWsProxyServer = http\.createServer/, 'custom server must provision a dedicated dashboard websocket sidecar')
|
||||||
|
assert.match(serverSource, /dashboard-sidecar-listening/, 'custom server must expose the dashboard websocket sidecar listener')
|
||||||
assert.match(serverSource, /dashboard-upgrade-accepted/, 'custom server must accept dashboard websocket upgrades through the proxy path')
|
assert.match(serverSource, /dashboard-upgrade-accepted/, 'custom server must accept dashboard websocket upgrades through the proxy path')
|
||||||
|
|
||||||
console.log('runtime-authority-resolution-check: PASS shared authority resolution assertions')
|
console.log('runtime-authority-resolution-check: PASS shared authority resolution assertions')
|
||||||
|
|||||||
Reference in New Issue
Block a user