import { NextResponse } from 'next/server' import { getDefaultOpenClawDashboardInstanceId } from '@/app/lib/openshellHost' import { OPENCLAW_DASHBOARD_TOKEN_COOKIE } from '@/app/lib/openclawDashboardToken' 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 BOOTSTRAP_SCRIPT_NAME = '__nemoclaw_openclaw_bootstrap.js' const CONTROL_AUTH_COOKIE_NAME = 'openshell_control_session' 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 controlUiOrigin: 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, controlUiOrigin: authority.openclaw.controlUiOrigin || new URL(authority.openclaw.dashboardUrl).origin, 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, controlUiOrigin: authority.openclaw.controlUiOrigin || new URL(authority.openclaw.dashboardUrl).origin, authorityMode: authority.authorityMode, bridgeActive: authority.bridgeActive, } } function buildTargetUrl(requestUrl: URL) { const { proxyPrefix, targetBaseUrl, controlUiOrigin, 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, controlUiOrigin, authorityMode, bridgeActive } } function copyRequestHeaders(request: Request, target: URL, controlUiOrigin: string) { const headers = new Headers() const dashboardToken = readCookieValue(request.headers.get('cookie'), OPENCLAW_DASHBOARD_TOKEN_COOKIE) request.headers.forEach((value, key) => { const lowerKey = key.toLowerCase() if ( !HOP_BY_HOP_HEADERS.has(lowerKey) && lowerKey !== 'host' && lowerKey !== 'origin' && lowerKey !== 'referer' ) { const filteredValue = lowerKey === 'cookie' ? filterCookieHeader(value) : value if (filteredValue) headers.set(key, filteredValue) } }) headers.set('host', target.host) headers.set('origin', controlUiOrigin) headers.set('referer', `${controlUiOrigin}/`) if (dashboardToken && !headers.has('authorization')) { headers.set('authorization', `Bearer ${dashboardToken}`) } return headers } function readCookieValue(value: string | null, name: string) { return String(value || '') .split(';') .map((part) => part.trim()) .reduce((found, part) => { if (found || !part.startsWith(`${name}=`)) return found try { return decodeURIComponent(part.slice(name.length + 1)) } catch { return part.slice(name.length + 1) } }, null) } function filterCookieHeader(value: string) { return value .split(';') .map((part) => part.trim()) .filter((part) => part && !part.startsWith(`${CONTROL_AUTH_COOKIE_NAME}=`) && !part.startsWith(`${OPENCLAW_DASHBOARD_TOKEN_COOKIE}=`)) .join('; ') } 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 isBootstrapScriptRequest(requestUrl: URL, proxyPrefix: string) { return requestUrl.pathname === `${proxyPrefix}/${BOOTSTRAP_SCRIPT_NAME}` } function bootstrapScriptResponse(proxyPrefix: string) { const baseWsUrl = process.env.OPENCLAW_DASHBOARD_BASE_WS_URL?.trim() || process.env.BASE_WS_URL?.trim() || '' const wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || '' const script = ` (() => { const proxyPrefix = ${JSON.stringify(proxyPrefix)}; const baseWsUrl = ${JSON.stringify(baseWsUrl)}; const wsProxyPort = ${JSON.stringify(wsProxyPort)}; window.__OPENCLAW_CONTROL_UI_BASE_PATH__ = proxyPrefix; try { const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const pageGatewayUrl = protocol + '//' + window.location.host + proxyPrefix; const portGatewayUrl = wsProxyPort ? protocol + '//' + window.location.hostname + ':' + wsProxyPort + proxyPrefix : ''; const normalizeGatewayUrl = (value) => { const raw = (value || '').trim(); if (!raw) return ''; try { const parsed = new URL(raw, window.location.href); if (parsed.protocol === 'http:') parsed.protocol = 'ws:'; if (parsed.protocol === 'https:') parsed.protocol = 'wss:'; if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') return ''; parsed.hash = ''; if (parsed.pathname === '/' || parsed.pathname === '') { parsed.pathname = proxyPrefix; } else { parsed.pathname = parsed.pathname.replace(/\\/+$/, '') || '/'; } return parsed.toString(); } catch { return ''; } }; const configuredGatewayUrl = normalizeGatewayUrl(baseWsUrl); const defaultGatewayUrl = configuredGatewayUrl || portGatewayUrl || pageGatewayUrl; const settingsKey = 'openclaw.control.settings.v1'; const settingsPrefix = 'openclaw.control.settings.v1:'; const tokenKey = 'openclaw.control.token.v1'; const tokenPrefix = 'openclaw.control.token.v1:'; const hashParams = new URLSearchParams(window.location.hash.startsWith('#') ? window.location.hash.slice(1) : window.location.hash); const gatewayUrl = normalizeGatewayUrl(hashParams.get('gatewayUrl')) || defaultGatewayUrl; const token = (hashParams.get('token') || '').trim(); const storageScope = (value) => { try { const parsed = new URL(value, window.location.href); const path = parsed.pathname === '/' ? '' : parsed.pathname.replace(/\\/+$/, '') || parsed.pathname; return parsed.protocol + '//' + parsed.host + path; } catch { return value; } }; const uniqueScopes = (values) => Array.from(new Set(values.map(storageScope).filter(Boolean))); const gatewayScopes = uniqueScopes([gatewayUrl, configuredGatewayUrl, portGatewayUrl, pageGatewayUrl]); const settingsKeys = gatewayScopes.map((scope) => settingsPrefix + scope); const readSettings = () => { for (const key of [...settingsKeys, settingsPrefix + 'default', settingsKey]) { try { const raw = window.localStorage.getItem(key); if (!raw) continue; const parsed = JSON.parse(raw); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed; } catch {} } return {}; }; const settings = readSettings(); settings.gatewayUrl = gatewayUrl; const serializedSettings = JSON.stringify(settings); window.localStorage.setItem(settingsKey, serializedSettings); for (const key of settingsKeys) window.localStorage.setItem(key, serializedSettings); window.sessionStorage.removeItem(tokenKey); if (token) { for (const scope of gatewayScopes) window.sessionStorage.setItem(tokenPrefix + scope, token); } } catch { // Best-effort compatibility bridge for OpenClaw's persisted UI settings. } })(); ` return new NextResponse( script, { status: 200, headers: { 'cache-control': 'no-store', 'content-type': 'application/javascript; charset=utf-8', }, } ) } function injectOpenClawBootstrap(body: string, proxyPrefix: string) { const bootstrap = `` return body.replace(/]*)?>/i, (match) => `${match}${bootstrap}`) } function rewriteHtml(body: string, proxyPrefix: string) { const rewritten = 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}` ) return injectOpenClawBootstrap(rewritten, proxyPrefix) } export async function proxyOpenClawDashboard(request: Request) { const requestUrl = new URL(request.url) const resolution = resolveProxyTarget(requestUrl) if (isBootstrapScriptRequest(requestUrl, resolution.proxyPrefix)) { return bootstrapScriptResponse(resolution.proxyPrefix) } const { target, proxyPrefix, controlUiOrigin, authorityMode, bridgeActive } = buildTargetUrl(requestUrl) const method = request.method.toUpperCase() const headers = copyRequestHeaders(request, target, controlUiOrigin) 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 } ) }