Stabilize dashboard runtime proxy

This commit is contained in:
Codex
2026-04-24 13:47:10 +00:00
parent 4d15ce4388
commit 05db76d930
39 changed files with 4349 additions and 1472 deletions
+101 -7
View File
@@ -1,14 +1,108 @@
import { NextResponse } from 'next/server'
import { getOpenClawDashboardUrl } from '../../../../lib/openshellHost'
import { getDefaultOpenClawDashboardInstanceId, getOpenClawDashboardUrl, probeOpenClawDashboard } from '../../../../lib/openshellHost'
import { getOpenClawInstanceIdForSandbox, resolveOpenClawInstance, resolveOpenClawInstanceForSandbox } from '../../../../lib/openclawInstances'
import { resolveRuntimeAuthority } from '../../../../lib/runtimeAuthority'
function parseInventoryCount(requestUrl: URL) {
const raw = requestUrl.searchParams.get('inventoryCount')
if (raw == null) return null
const count = Number.parseInt(raw, 10)
return Number.isFinite(count) && count >= 0 ? count : null
}
function buildLaunchUrl(proxiedUrl: string, bootstrapUrl: string | null) {
if (!bootstrapUrl) return proxiedUrl
const bootstrap = new URL(bootstrapUrl)
const browserHash = bootstrap.hash
bootstrap.hash = ''
const params = new URLSearchParams({
path: '/',
bootstrapUrl: bootstrap.toString(),
})
return `${proxiedUrl}?${params.toString()}${browserHash}`
}
export async function GET(request: Request) {
const requestUrl = new URL(request.url)
const sandboxId = requestUrl.searchParams.get('sandboxId')
const requestedInstanceId = requestUrl.searchParams.get('instanceId')
const inventoryCount = parseInventoryCount(requestUrl)
const mappedSandboxInstanceId = getOpenClawInstanceIdForSandbox(sandboxId)
const instance = requestedInstanceId
? resolveOpenClawInstance(requestedInstanceId)
: resolveOpenClawInstanceForSandbox(sandboxId)
const authority = resolveRuntimeAuthority({
sandboxId,
instanceId: requestedInstanceId,
})
const probe = await probeOpenClawDashboard(authority.openclaw.id)
const instanceQualifiedProxyBase = `/api/openshell/instances/${encodeURIComponent(instance.id)}/dashboard/proxy`
const zeroInventoryMappedDashboard = Boolean(
inventoryCount === 0 &&
sandboxId &&
authority.bridgeActive &&
probe.reachable
)
const truthState = zeroInventoryMappedDashboard
? 'degraded'
: probe.bootstrapAuthority === 'tokenized-cli'
? 'tokenized'
: authority.bridgeActive
? 'bridged'
: 'verified'
const proxiedUrl = authority.explicitInstanceOverride ? instanceQualifiedProxyBase : '/api/openshell/dashboard/proxy'
const launchUrl = buildLaunchUrl(proxiedUrl, probe.bootstrapUrl)
export async function GET() {
const dashboardUrl = getOpenClawDashboardUrl()
return NextResponse.json({
ok: true,
dashboardUrl,
proxiedUrl: '/api/openshell/dashboard/proxy',
sandboxId,
sandboxInstanceId: mappedSandboxInstanceId,
instanceId: instance.id,
inventoryCount,
truthState,
degraded: zeroInventoryMappedDashboard,
authority: {
requestedSandboxId: authority.requestedSandboxId,
resolvedSandboxId: authority.resolvedSandboxId,
sandboxAuthority: authority.sandboxAuthority,
authorityMode: authority.authorityMode,
provenance: authority.provenance,
bridgeActive: authority.bridgeActive,
bridgeReason: authority.bridgeReason,
requestedInstanceId: authority.requestedInstanceId,
instanceId: authority.openclaw.id,
sandboxInstanceId: mappedSandboxInstanceId,
explicitInstanceOverride: authority.explicitInstanceOverride,
usedMappedSandboxInstance: authority.usedMappedSandboxInstance,
},
defaultInstanceId: getDefaultOpenClawDashboardInstanceId(),
dashboardUrl: getOpenClawDashboardUrl(authority.openclaw.id),
bootstrapUrl: probe.bootstrapUrl,
bootstrapTokenPresent: probe.bootstrapTokenPresent,
bootstrapSource: probe.bootstrapSource,
bootstrapAuthority: probe.bootstrapAuthority,
proxiedUrl,
launchUrl,
instanceQualifiedProxiedUrl: instanceQualifiedProxyBase,
openInNewTab: true,
loopbackOnly: true,
note: 'OpenClaw Dashboard is loopback-only on the host, so the web UI uses a local proxy route to expose it.'
loopbackOnly: authority.openclaw.loopbackOnly,
reachable: probe.reachable,
upstreamStatus: probe.status,
upstreamStatusText: probe.statusText,
listenerPresent: probe.listenerPresent,
listenerSummary: probe.listenerSummary,
note: zeroInventoryMappedDashboard
? 'Degraded truth: live OpenShell inventory is zero, but a bridged OpenClaw dashboard upstream is still reachable. Treat this dashboard as a fallback operator surface, not proof that the sandbox currently exists.'
: probe.bootstrapAuthority === 'tokenized-cli'
? 'Tokenized bootstrap available: the bridge resolved a dashboard URL from `openclaw dashboard --no-open`, so the proxy can carry the real OpenClaw session contract instead of treating raw loopback fetch as sufficient truth.'
: authority.bridgeActive
? authority.bridgeReason || 'Bridge-active: this dashboard action is using an explicit upstream OpenClaw bridge instead of assuming same-lane loopback ownership.'
: authority.openclaw.loopbackOnly
? 'OpenClaw Dashboard is loopback-only on the host, so the web UI uses a local proxy route to expose it.'
: 'OpenClaw Dashboard is reachable directly for this instance.'
})
}
@@ -0,0 +1,9 @@
import { proxyErrorResponse, proxyOpenClawDashboard } from '../shared'
export async function GET(request: Request) {
try {
return await proxyOpenClawDashboard(request)
} catch (error) {
return proxyErrorResponse(error)
}
}
+3 -29
View File
@@ -1,35 +1,9 @@
import { NextResponse } from 'next/server'
const OPENCLAW_LOCAL_DASHBOARD = 'http://127.0.0.1:18789/'
import { proxyErrorResponse, proxyOpenClawDashboard } from './shared'
export async function GET(request: Request) {
try {
const url = new URL(request.url)
const targetPath = url.searchParams.get('path') || ''
const target = new URL(targetPath, OPENCLAW_LOCAL_DASHBOARD)
const upstream = await fetch(target.toString(), {
method: 'GET',
headers: {
accept: 'text/html,application/json;q=0.9,*/*;q=0.8'
},
cache: 'no-store'
})
const contentType = upstream.headers.get('content-type') || 'text/html; charset=utf-8'
const body = await upstream.text()
return new NextResponse(body, {
status: upstream.status,
headers: {
'content-type': contentType,
'cache-control': 'no-store'
}
})
return await proxyOpenClawDashboard(request)
} catch (error) {
return NextResponse.json({
ok: false,
error: error instanceof Error ? error.message : 'Failed to proxy OpenClaw dashboard'
}, { status: 500 })
return proxyErrorResponse(error)
}
}
+200
View File
@@ -0,0 +1,200 @@
import { NextResponse } from 'next/server'
import { getDefaultOpenClawDashboardInstanceId } from '@/app/lib/openshellHost'
import { resolveRuntimeAuthority } from '@/app/lib/runtimeAuthority'
const LEGACY_PROXY_PREFIX = '/api/openshell/dashboard/proxy'
const INSTANCES_PREFIX = '/api/openshell/instances/'
const DASHBOARD_PROXY_SUFFIX = '/dashboard/proxy'
const HOP_BY_HOP_HEADERS = new Set([
'accept-encoding',
'connection',
'keep-alive',
'proxy-authenticate',
'proxy-authorization',
'te',
'trailer',
'transfer-encoding',
'upgrade',
'content-length',
])
type ProxyTargetResolution = {
instanceId: string | null
proxyPrefix: string
targetBaseUrl: string
authorityMode: 'direct-host' | 'bridged-sandbox-map' | 'bridged-instance-override'
bridgeActive: boolean
}
function normalizeDashboardProxyInstanceId(instanceId: string | null) {
if (!instanceId) return null
return instanceId === getDefaultOpenClawDashboardInstanceId() ? null : instanceId
}
function resolveProxyTarget(requestUrl: URL): ProxyTargetResolution {
const pathname = requestUrl.pathname
if (pathname.startsWith(INSTANCES_PREFIX)) {
const suffixIndex = pathname.indexOf(DASHBOARD_PROXY_SUFFIX, INSTANCES_PREFIX.length)
if (suffixIndex !== -1) {
const rawInstanceId = pathname.slice(INSTANCES_PREFIX.length, suffixIndex)
const decodedInstanceId = decodeURIComponent(rawInstanceId)
const normalizedInstanceId = normalizeDashboardProxyInstanceId(decodedInstanceId)
const authority = resolveRuntimeAuthority({
sandboxId: requestUrl.searchParams.get('sandboxId'),
instanceId: normalizedInstanceId,
})
return {
instanceId: authority.openclaw.id,
proxyPrefix: `/api/openshell/instances/${encodeURIComponent(decodedInstanceId)}/dashboard/proxy`,
targetBaseUrl: authority.openclaw.dashboardUrl,
authorityMode: authority.authorityMode,
bridgeActive: authority.bridgeActive,
}
}
}
const authority = resolveRuntimeAuthority({
sandboxId: requestUrl.searchParams.get('sandboxId'),
})
return {
instanceId: authority.bridgeActive ? authority.openclaw.id : null,
proxyPrefix: LEGACY_PROXY_PREFIX,
targetBaseUrl: authority.openclaw.dashboardUrl,
authorityMode: authority.authorityMode,
bridgeActive: authority.bridgeActive,
}
}
function buildTargetUrl(requestUrl: URL) {
const { proxyPrefix, targetBaseUrl, authorityMode, bridgeActive } = resolveProxyTarget(requestUrl)
const pathParam = requestUrl.searchParams.get('path')
const bootstrapUrl = requestUrl.searchParams.get('bootstrapUrl')
const pathname = requestUrl.pathname.startsWith(proxyPrefix)
? requestUrl.pathname.slice(proxyPrefix.length)
: '/'
const upstreamPath = pathParam ?? pathname ?? '/'
const normalizedPath = upstreamPath.startsWith('/') ? upstreamPath : `/${upstreamPath}`
const target = bootstrapUrl
? new URL(bootstrapUrl)
: new URL(normalizedPath, targetBaseUrl)
if (!bootstrapUrl) {
requestUrl.searchParams.forEach((value, key) => {
if (key !== 'path') target.searchParams.append(key, value)
})
}
return { target, proxyPrefix, authorityMode, bridgeActive }
}
function copyRequestHeaders(request: Request, target: URL) {
const headers = new Headers()
request.headers.forEach((value, key) => {
if (!HOP_BY_HOP_HEADERS.has(key.toLowerCase()) && key.toLowerCase() !== 'host') {
headers.set(key, value)
}
})
headers.set('host', target.host)
return headers
}
function copyResponseHeaders(upstream: Response) {
const headers = new Headers()
upstream.headers.forEach((value, key) => {
if (!HOP_BY_HOP_HEADERS.has(key.toLowerCase())) {
headers.set(key, value)
}
})
headers.set('cache-control', 'no-store')
return headers
}
function proxiedAssetPath(value: string, proxyPrefix: string) {
if (
!value ||
value.startsWith('#') ||
value.startsWith('//') ||
/^[a-z][a-z\d+.-]*:/i.test(value)
) {
return value
}
const normalized = value.startsWith('./')
? value.slice(2)
: value.startsWith('/')
? value.slice(1)
: value
return `${proxyPrefix}/${normalized}`
}
function rewriteHtml(body: string, proxyPrefix: string) {
return body.replace(
/(<(?:script|img|link)\b[^>]*\s(?:src|href)=)(["'])([^"']+)(["'])/gi,
(_match, prefix: string, quote: string, value: string, suffix: string) =>
`${prefix}${quote}${proxiedAssetPath(value, proxyPrefix)}${suffix}`
)
}
export async function proxyOpenClawDashboard(request: Request) {
const requestUrl = new URL(request.url)
const { target, proxyPrefix, authorityMode, bridgeActive } = buildTargetUrl(requestUrl)
const method = request.method.toUpperCase()
const headers = copyRequestHeaders(request, target)
const shouldSendBody = !['GET', 'HEAD'].includes(method)
const upstreamInit: RequestInit & { duplex?: 'half' } = {
method,
headers,
body: shouldSendBody ? request.body : undefined,
redirect: 'manual',
cache: 'no-store',
}
if (shouldSendBody) {
upstreamInit.duplex = 'half'
}
const upstream = await fetch(target.toString(), {
...upstreamInit,
})
const responseHeaders = copyResponseHeaders(upstream)
responseHeaders.set('x-openclaw-authority-mode', authorityMode)
responseHeaders.set('x-openclaw-bridge-active', bridgeActive ? 'true' : 'false')
responseHeaders.set('x-openclaw-dashboard-bootstrap-contract', 'tokenized-openclaw-dashboard')
const location = upstream.headers.get('location')
if (location) {
responseHeaders.set('location', location.startsWith('/') ? `${proxyPrefix}${location}` : location)
}
const contentType = upstream.headers.get('content-type') || 'application/octet-stream'
if (contentType.includes('text/html')) {
const body = rewriteHtml(await upstream.text(), proxyPrefix)
responseHeaders.set('content-type', contentType)
return new NextResponse(body, {
status: upstream.status,
headers: responseHeaders,
})
}
return new NextResponse(upstream.body, {
status: upstream.status,
headers: responseHeaders,
})
}
export function proxyErrorResponse(error: unknown) {
return NextResponse.json(
{
ok: false,
error: error instanceof Error ? error.message : 'Failed to proxy OpenClaw dashboard',
},
{ status: 500 }
)
}