diff --git a/app/api/openshell/dashboard/open/route.ts b/app/api/openshell/dashboard/open/route.ts index 23c494c..7d60e1b 100644 --- a/app/api/openshell/dashboard/open/route.ts +++ b/app/api/openshell/dashboard/open/route.ts @@ -19,8 +19,12 @@ function buildBrowserGatewayUrl(request: Request, requestUrl: URL, proxiedUrl: s const forwardedHost = firstHeaderValue(request.headers.get('x-forwarded-host')) const host = forwardedHost || request.headers.get('host') || requestUrl.host 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) { diff --git a/app/api/openshell/dashboard/proxy/shared.ts b/app/api/openshell/dashboard/proxy/shared.ts index 3a767d4..c2a5ded 100644 --- a/app/api/openshell/dashboard/proxy/shared.ts +++ b/app/api/openshell/dashboard/proxy/shared.ts @@ -140,8 +140,37 @@ function isBootstrapScriptRequest(requestUrl: URL, 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( - `window.__OPENCLAW_CONTROL_UI_BASE_PATH__=${JSON.stringify(proxyPrefix)};\n`, + script, { status: 200, headers: { diff --git a/server.mjs b/server.mjs index 31afee4..b390991 100644 --- a/server.mjs +++ b/server.mjs @@ -1,11 +1,14 @@ import http from 'node:http' import crypto from 'node:crypto' +import net from 'node:net' +import tls from 'node:tls' import next from 'next' import { WebSocketServer, WebSocket } from 'ws' const dev = process.env.NODE_ENV !== 'production' const hostname = process.env.HOSTNAME || process.env.HOST || '0.0.0.0' 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 terminalWsProtocol = terminalServerUrl.protocol === 'https:' ? 'wss:' : 'ws:' const terminalProxyPath = '/api/openshell/terminal/live/ws' @@ -196,58 +199,63 @@ const handleUpgrade = typeof app.getUpgradeHandler === 'function' await app.prepare() 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 }) function buildRawDashboardUpgradeHeaders(req, upstreamWsUrl) { - const headers = { ...req.headers } const upstreamOrigin = new URL(upstreamWsUrl.toString()) upstreamOrigin.protocol = upstreamOrigin.protocol === 'wss:' ? 'https:' : 'http:' upstreamOrigin.pathname = '/' upstreamOrigin.search = '' upstreamOrigin.hash = '' - headers.host = upstreamWsUrl.host - headers.origin = upstreamOrigin.origin + const headers = [] + 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 } -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) { - const upstreamReq = http.request({ - hostname: upstreamWsUrl.hostname, - port: upstreamWsUrl.port || '80', - path: `${upstreamWsUrl.pathname}${upstreamWsUrl.search}`, - method: 'GET', - headers: buildRawDashboardUpgradeHeaders(req, upstreamWsUrl), - }) + const isSecure = upstreamWsUrl.protocol === 'wss:' + const port = Number(upstreamWsUrl.port || (isSecure ? 443 : 80)) + const upstreamSocket = isSecure + ? tls.connect({ host: upstreamWsUrl.hostname, port, servername: upstreamWsUrl.hostname }) + : net.connect({ host: upstreamWsUrl.hostname, port }) + const upstreamPath = `${upstreamWsUrl.pathname || '/'}${upstreamWsUrl.search || ''}` + const requestHead = [ + `GET ${upstreamPath} HTTP/1.1`, + ...buildRawDashboardUpgradeHeaders(req, upstreamWsUrl), + '', + '', + ].join('\r\n') + let opened = false + let upstreamBytes = 0 + let clientBytes = 0 - upstreamReq.on('upgrade', (upstreamRes, upstreamSocket, upstreamHead) => { - 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') - - socket.write(responseHead) - if (upstreamHead?.length) socket.write(upstreamHead) + upstreamSocket.once(isSecure ? 'secureConnect' : 'connect', () => { + opened = true + upstreamSocket.write(requestHead) if (head?.length) upstreamSocket.write(head) - upstreamSocket.pipe(socket) - socket.pipe(upstreamSocket) + upstreamSocket.resume() + socket.resume() logBridge('dashboard-tunnel-open', { path: req.url || '/', upstreamUrl: upstreamWsUrl.toString(), @@ -256,23 +264,53 @@ function tunnelDashboardUpgrade(req, socket, head, upstreamWsUrl, instanceId) { }) }) - upstreamReq.on('response', (upstreamRes) => { - writeBadGateway(socket, `OpenClaw dashboard websocket upgrade rejected: ${upstreamRes.statusCode || 502}`) - upstreamRes.resume() + upstreamSocket.on('data', (chunk) => { + upstreamBytes += chunk.length + 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', { path: req.url || '/', upstreamUrl: upstreamWsUrl.toString(), instanceId, 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()) - upstreamReq.end() + upstreamSocket.on('close', (hadError) => { + 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) => { @@ -418,6 +456,29 @@ server.on('upgrade', (req, socket, head) => { 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, () => { console.log(`dashboard server listening on http://${hostname}:${port}`) logBridge('server-listening', { @@ -427,3 +488,10 @@ server.listen(port, hostname, () => { soleOwnerPath: terminalProxyPath, }) }) + +dashboardWsProxyServer.listen(dashboardWsProxyPort, hostname, () => { + logBridge('dashboard-sidecar-listening', { + hostname, + port: dashboardWsProxyPort, + }) +}) diff --git a/tests/runtime-authority-resolution-check.mjs b/tests/runtime-authority-resolution-check.mjs index 0346953..a32448c 100644 --- a/tests/runtime-authority-resolution-check.mjs +++ b/tests/runtime-authority-resolution-check.mjs @@ -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(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(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') console.log('runtime-authority-resolution-check: PASS shared authority resolution assertions')