Merge pull request #16 from mmckeen-nv/codex/gateway-overrides-quick-deploy

Integrate NemoClaw recovery and dashboard routing
This commit is contained in:
mmckeen-nv
2026-05-08 10:36:42 -06:00
committed by GitHub
25 changed files with 1001 additions and 152 deletions
+7 -1
View File
@@ -15,8 +15,14 @@ OPENSHELL_GATEWAY=nemoclaw
# OPENSHELL_GATEWAY_PORT=8080 # OPENSHELL_GATEWAY_PORT=8080
# OPENSHELL_GATEWAY_URL=http://host.docker.internal:8080 # OPENSHELL_GATEWAY_URL=http://host.docker.internal:8080
# Dashboard port # Dashboard port. PORT controls the server listener; NEXT_PUBLIC_DASHBOARD_PORT is exposed to the UI.
PORT=3000
NEXT_PUBLIC_DASHBOARD_PORT=3000 NEXT_PUBLIC_DASHBOARD_PORT=3000
# Browser-visible OpenClaw dashboard websocket base.
# Leave unset for same-origin reverse-proxy deployments.
# OPENCLAW_DASHBOARD_BASE_WS_URL=wss://control.example.com
# BASE_WS_URL=wss://control.example.com
# OPENCLAW_DASHBOARD_WS_PROXY_PORT=3001
# Simple operator login for the dashboard # Simple operator login for the dashboard
# Generate both values before exposing the UI beyond localhost. # Generate both values before exposing the UI beyond localhost.
+20 -4
View File
@@ -130,10 +130,19 @@ grep OPENSHELL_CONTROL_PASSWORD .env.local
## Run ## Run
For local development with hot reload:
```bash ```bash
npm run dev npm run dev
``` ```
For a long-running dashboard or controller node, build once and run the custom server in production mode:
```bash
npm run build
npm run start
```
Open: Open:
```text ```text
@@ -143,9 +152,10 @@ http://localhost:3000
Default ports: Default ports:
- `3000`: dashboard HTTP server - `3000`: dashboard HTTP server
- `3001`: OpenClaw dashboard websocket sidecar
- `3011`: operator terminal upstream - `3011`: operator terminal upstream
The dashboard WebSocket proxy is served on the same listener by default, using `/api/openshell/dashboard/proxy` or `/api/openshell/instances/[instanceId]/dashboard/proxy`. Set `OPENCLAW_DASHBOARD_WS_PROXY_PORT=3001` only if you intentionally want the legacy dedicated sidecar listener.
## Authentication ## Authentication
This project currently uses a simple local password and signed HTTP-only cookie. This project currently uses a simple local password and signed HTTP-only cookie.
@@ -169,8 +179,8 @@ There is no email sender. Forgot-password uses `OPENSHELL_CONTROL_RECOVERY_TOKEN
After changing `.env.local`, restart the server: After changing `.env.local`, restart the server:
```bash ```bash
pkill -f 'node server.mjs|npm run dev' || true pkill -f 'node server.mjs|npm run dev|npm run start' || true
npm run dev npm run start
``` ```
## OpenShell And OpenClaw Notes ## OpenShell And OpenClaw Notes
@@ -195,6 +205,7 @@ The custom server in `server.mjs` also handles websocket upgrades for:
- OpenClaw dashboard websocket traffic. - OpenClaw dashboard websocket traffic.
Those upgrade paths are protected by the same auth cookie as the HTTP routes. Those upgrade paths are protected by the same auth cookie as the HTTP routes.
Behind a reverse proxy, route WebSocket upgrades for the dashboard proxy paths to the same `server.mjs` listener as the HTTP app. Use `OPENCLAW_DASHBOARD_BASE_WS_URL` or `BASE_WS_URL` only when the browser-visible WebSocket base must be a fully qualified override such as `wss://control.example.com/api/ws-proxy`.
## Remote Controller Nodes ## Remote Controller Nodes
@@ -281,6 +292,7 @@ npm run dev
npm run lint npm run lint
npx tsc --noEmit npx tsc --noEmit
npm run build npm run build
npm run start
``` ```
After running `npm run build` during development, restart cleanly: After running `npm run build` during development, restart cleanly:
@@ -302,9 +314,13 @@ cp .env.example .env.local
Common keys: Common keys:
```bash ```bash
PORT=3000
NEXT_PUBLIC_DASHBOARD_PORT=3000 NEXT_PUBLIC_DASHBOARD_PORT=3000
NEXT_PUBLIC_API_BASE=/api NEXT_PUBLIC_API_BASE=/api
NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS=true NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS=true
# OPENCLAW_DASHBOARD_BASE_WS_URL=wss://control.example.com
# BASE_WS_URL=wss://control.example.com
# OPENCLAW_DASHBOARD_WS_PROXY_PORT=3001
OPEN_SHELL_CONTAINER=openshell-cluster-nemoclaw OPEN_SHELL_CONTAINER=openshell-cluster-nemoclaw
OPENSHELL_GATEWAY=nemoclaw OPENSHELL_GATEWAY=nemoclaw
# For containerized CLI runs, when supported by the installed OpenShell/NemoClaw versions: # For containerized CLI runs, when supported by the installed OpenShell/NemoClaw versions:
@@ -372,7 +388,7 @@ npm run build
If the UI behaves oddly after a production build: If the UI behaves oddly after a production build:
```bash ```bash
pkill -f 'node server.mjs|npm run dev' || true pkill -f 'node server.mjs|npm run dev|npm run start' || true
rm -rf .next rm -rf .next
npm run dev npm run dev
``` ```
+2 -2
View File
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from "next/server" import { NextRequest, NextResponse } from "next/server"
import { createSessionCookieValue, getAuthSettings, sessionCookieOptions, verifyPassword } from "@/app/lib/controlAuth" import { createSessionCookieValue, getAuthSettings, sessionCookieOptionsForRequest, verifyPassword } from "@/app/lib/controlAuth"
import { checkRateLimit, clearRateLimit, rateLimitKey, recordRateLimitFailure } from "@/app/lib/rateLimit" import { checkRateLimit, clearRateLimit, rateLimitKey, recordRateLimitFailure } from "@/app/lib/rateLimit"
const AUTH_WINDOW_MS = 5 * 60 * 1000 const AUTH_WINDOW_MS = 5 * 60 * 1000
@@ -34,6 +34,6 @@ export async function POST(request: NextRequest) {
clearRateLimit(limitKey) clearRateLimit(limitKey)
const response = NextResponse.json({ ok: true, next: nextPath }) const response = NextResponse.json({ ok: true, next: nextPath })
response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions) response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptionsForRequest(request))
return response return response
} }
+4 -7
View File
@@ -1,14 +1,11 @@
import { NextResponse } from "next/server" import { NextRequest, NextResponse } from "next/server"
import { getAuthSettings } from "@/app/lib/controlAuth" import { getAuthSettings, sessionCookieOptionsForRequest } from "@/app/lib/controlAuth"
export async function POST() { export async function POST(request: NextRequest) {
const settings = getAuthSettings() const settings = getAuthSettings()
const response = NextResponse.json({ ok: true }) const response = NextResponse.json({ ok: true })
response.cookies.set(settings.cookieName, "", { response.cookies.set(settings.cookieName, "", {
httpOnly: true, ...sessionCookieOptionsForRequest(request),
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
path: "/",
maxAge: 0, maxAge: 0,
}) })
return response return response
+2 -2
View File
@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from "next/server" import { NextRequest, NextResponse } from "next/server"
import { createSessionCookieValue, getAuthSettings, sessionCookieOptions, verifyRecoveryToken } from "@/app/lib/controlAuth" import { createSessionCookieValue, getAuthSettings, sessionCookieOptionsForRequest, verifyRecoveryToken } from "@/app/lib/controlAuth"
import { updateLocalAuthCredentials } from "@/app/lib/controlAuthConfig" import { updateLocalAuthCredentials } from "@/app/lib/controlAuthConfig"
import { checkRateLimit, clearRateLimit, rateLimitKey, recordRateLimitFailure } from "@/app/lib/rateLimit" import { checkRateLimit, clearRateLimit, rateLimitKey, recordRateLimitFailure } from "@/app/lib/rateLimit"
@@ -37,6 +37,6 @@ export async function POST(request: NextRequest) {
recoveryToken: result.recoveryToken, recoveryToken: result.recoveryToken,
note: "Password reset. Save the new recovery token from .env.local.", note: "Password reset. Save the new recovery token from .env.local.",
}) })
response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions) response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptionsForRequest(request))
return response return response
} }
+2 -2
View File
@@ -2,7 +2,7 @@ import { NextRequest, NextResponse } from "next/server"
import { import {
createSessionCookieValue, createSessionCookieValue,
getAuthSettings, getAuthSettings,
sessionCookieOptions, sessionCookieOptionsForRequest,
verifyPassword, verifyPassword,
verifyRecoveryToken, verifyRecoveryToken,
verifySessionCookieValue, verifySessionCookieValue,
@@ -54,6 +54,6 @@ export async function POST(request: NextRequest) {
recoveryToken: result.recoveryToken, recoveryToken: result.recoveryToken,
note: "Password updated. Save the new recovery token from .env.local.", note: "Password updated. Save the new recovery token from .env.local.",
}) })
response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions) response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptionsForRequest(request))
return response return response
} }
+6 -2
View File
@@ -106,8 +106,12 @@ function isVllmEndpoint(name: string, baseUrl: string) {
return [name, baseUrl].some((value) => /vllm/i.test(value)) return [name, baseUrl].some((value) => /vllm/i.test(value))
} }
function isOllamaEndpoint(name: string, baseUrl: string) {
return [name, baseUrl].some((value) => /ollama|11434/i.test(value))
}
function normalizeProviderType(type: string, name: string, baseUrl: string) { function normalizeProviderType(type: string, name: string, baseUrl: string) {
return isVllmEndpoint(name, baseUrl) ? "openai" : type return isVllmEndpoint(name, baseUrl) || isOllamaEndpoint(name, baseUrl) ? "openai" : type
} }
function redactSecretOutput(value: string, secrets: string[] = []) { function redactSecretOutput(value: string, secrets: string[] = []) {
@@ -153,7 +157,7 @@ export async function POST(request: Request) {
const credentialKey = optionalString(body?.credentialKey) || "OPENAI_API_KEY" const credentialKey = optionalString(body?.credentialKey) || "OPENAI_API_KEY"
const makeActive = body?.makeActive !== false const makeActive = body?.makeActive !== false
const system = body?.route === "system" || body?.system === true const system = body?.route === "system" || body?.system === true
const noVerify = body?.noVerify !== false || isVllmEndpoint(name, baseUrl) const noVerify = body?.noVerify !== false || isVllmEndpoint(name, baseUrl) || isOllamaEndpoint(name, baseUrl)
const timeout = Number(body?.timeout ?? 0) const timeout = Number(body?.timeout ?? 0)
if (makeActive && !model) throw new Error("model is required when making the endpoint active") if (makeActive && !model) throw new Error("model is required when making the endpoint active")
+30 -2
View File
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
import { getDefaultOpenClawDashboardInstanceId, getOpenClawDashboardUrl, probeOpenClawDashboard } from '../../../../lib/openshellHost' import { getDefaultOpenClawDashboardInstanceId, getOpenClawDashboardUrl, probeOpenClawDashboard } from '../../../../lib/openshellHost'
import { getOpenClawInstanceIdForSandbox, resolveOpenClawInstance, resolveOpenClawInstanceForSandbox } from '../../../../lib/openclawInstances' import { getOpenClawInstanceIdForSandbox, resolveOpenClawInstance, resolveOpenClawInstanceForSandbox } from '../../../../lib/openclawInstances'
import { resolveRuntimeAuthority } from '../../../../lib/runtimeAuthority' import { resolveRuntimeAuthority } from '../../../../lib/runtimeAuthority'
import { extractOpenClawDashboardToken, setOpenClawDashboardTokenCookie } from '../../../../lib/openclawDashboardToken'
function parseInventoryCount(requestUrl: URL) { function parseInventoryCount(requestUrl: URL) {
const raw = requestUrl.searchParams.get('inventoryCount') const raw = requestUrl.searchParams.get('inventoryCount')
@@ -14,12 +15,37 @@ function firstHeaderValue(value: string | null) {
return value?.split(',')[0]?.trim() || null return value?.split(',')[0]?.trim() || null
} }
function getConfiguredBaseWsUrl() {
return process.env.OPENCLAW_DASHBOARD_BASE_WS_URL?.trim() || process.env.BASE_WS_URL?.trim() || null
}
function normalizeBrowserWebSocketBase(value: string | null, proxiedUrl: string) {
if (!value) return null
const parsed = new URL(value)
if (parsed.protocol === 'http:') parsed.protocol = 'ws:'
if (parsed.protocol === 'https:') parsed.protocol = 'wss:'
if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:') {
throw new Error('OPENCLAW_DASHBOARD_BASE_WS_URL/BASE_WS_URL must use ws://, wss://, http://, or https://')
}
parsed.hash = ''
if (parsed.pathname === '/' || parsed.pathname === '') {
parsed.pathname = proxiedUrl
} else {
parsed.pathname = parsed.pathname.replace(/\/+$/, '') || '/'
}
return parsed.toString()
}
function buildBrowserGatewayUrl(request: Request, requestUrl: URL, proxiedUrl: string) { function buildBrowserGatewayUrl(request: Request, requestUrl: URL, proxiedUrl: string) {
const configuredBaseWsUrl = normalizeBrowserWebSocketBase(getConfiguredBaseWsUrl(), proxiedUrl)
if (configuredBaseWsUrl) return configuredBaseWsUrl
const forwardedProtocol = firstHeaderValue(request.headers.get('x-forwarded-proto')) const forwardedProtocol = firstHeaderValue(request.headers.get('x-forwarded-proto'))
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 wsProxyPort = process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT?.trim() || ''
const gatewayHost = wsProxyPort const gatewayHost = wsProxyPort
? new URL(`${requestUrl.protocol}//${host}`).hostname + `:${wsProxyPort}` ? new URL(`${requestUrl.protocol}//${host}`).hostname + `:${wsProxyPort}`
: host : host
@@ -82,7 +108,7 @@ export async function GET(request: Request) {
const proxiedUrl = authority.bridgeActive ? instanceQualifiedProxyBase : '/api/openshell/dashboard/proxy' const proxiedUrl = authority.bridgeActive ? instanceQualifiedProxyBase : '/api/openshell/dashboard/proxy'
const launchUrl = buildLaunchUrl(request, requestUrl, proxiedUrl, probe.bootstrapUrl) const launchUrl = buildLaunchUrl(request, requestUrl, proxiedUrl, probe.bootstrapUrl)
return NextResponse.json({ const response = NextResponse.json({
ok: true, ok: true,
sandboxId, sandboxId,
sandboxInstanceId: mappedSandboxInstanceId, sandboxInstanceId: mappedSandboxInstanceId,
@@ -130,4 +156,6 @@ export async function GET(request: Request) {
? 'OpenClaw Dashboard is loopback-only on the host, so the web UI uses a local proxy route to expose it.' ? '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.' : 'OpenClaw Dashboard is reachable directly for this instance.'
}) })
setOpenClawDashboardTokenCookie(response, request, proxiedUrl, extractOpenClawDashboardToken(probe.bootstrapUrl))
return response
} }
+57 -6
View File
@@ -1,11 +1,13 @@
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import { getDefaultOpenClawDashboardInstanceId } from '@/app/lib/openshellHost' import { getDefaultOpenClawDashboardInstanceId } from '@/app/lib/openshellHost'
import { OPENCLAW_DASHBOARD_TOKEN_COOKIE } from '@/app/lib/openclawDashboardToken'
import { resolveRuntimeAuthority } from '@/app/lib/runtimeAuthority' import { resolveRuntimeAuthority } from '@/app/lib/runtimeAuthority'
const LEGACY_PROXY_PREFIX = '/api/openshell/dashboard/proxy' const LEGACY_PROXY_PREFIX = '/api/openshell/dashboard/proxy'
const INSTANCES_PREFIX = '/api/openshell/instances/' const INSTANCES_PREFIX = '/api/openshell/instances/'
const DASHBOARD_PROXY_SUFFIX = '/dashboard/proxy' const DASHBOARD_PROXY_SUFFIX = '/dashboard/proxy'
const BOOTSTRAP_SCRIPT_NAME = '__nemoclaw_openclaw_bootstrap.js' const BOOTSTRAP_SCRIPT_NAME = '__nemoclaw_openclaw_bootstrap.js'
const CONTROL_AUTH_COOKIE_NAME = 'openshell_control_session'
const HOP_BY_HOP_HEADERS = new Set([ const HOP_BY_HOP_HEADERS = new Set([
'accept-encoding', 'accept-encoding',
'connection', 'connection',
@@ -95,6 +97,7 @@ function buildTargetUrl(requestUrl: URL) {
function copyRequestHeaders(request: Request, target: URL, controlUiOrigin: string) { function copyRequestHeaders(request: Request, target: URL, controlUiOrigin: string) {
const headers = new Headers() const headers = new Headers()
const dashboardToken = readCookieValue(request.headers.get('cookie'), OPENCLAW_DASHBOARD_TOKEN_COOKIE)
request.headers.forEach((value, key) => { request.headers.forEach((value, key) => {
const lowerKey = key.toLowerCase() const lowerKey = key.toLowerCase()
@@ -104,16 +107,42 @@ function copyRequestHeaders(request: Request, target: URL, controlUiOrigin: stri
lowerKey !== 'origin' && lowerKey !== 'origin' &&
lowerKey !== 'referer' lowerKey !== 'referer'
) { ) {
headers.set(key, value) const filteredValue = lowerKey === 'cookie' ? filterCookieHeader(value) : value
if (filteredValue) headers.set(key, filteredValue)
} }
}) })
headers.set('host', target.host) headers.set('host', target.host)
headers.set('origin', controlUiOrigin) headers.set('origin', controlUiOrigin)
headers.set('referer', `${controlUiOrigin}/`) headers.set('referer', `${controlUiOrigin}/`)
if (dashboardToken && !headers.has('authorization')) {
headers.set('authorization', `Bearer ${dashboardToken}`)
}
return headers return headers
} }
function readCookieValue(value: string | null, name: string) {
return String(value || '')
.split(';')
.map((part) => part.trim())
.reduce<string | null>((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) { function copyResponseHeaders(upstream: Response) {
const headers = new Headers() const headers = new Headers()
@@ -151,24 +180,46 @@ 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 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 script = `
(() => { (() => {
const proxyPrefix = ${JSON.stringify(proxyPrefix)}; const proxyPrefix = ${JSON.stringify(proxyPrefix)};
const baseWsUrl = ${JSON.stringify(baseWsUrl)};
const wsProxyPort = ${JSON.stringify(wsProxyPort)}; const wsProxyPort = ${JSON.stringify(wsProxyPort)};
window.__OPENCLAW_CONTROL_UI_BASE_PATH__ = proxyPrefix; window.__OPENCLAW_CONTROL_UI_BASE_PATH__ = proxyPrefix;
try { try {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const pageGatewayUrl = protocol + '//' + window.location.host + proxyPrefix; const pageGatewayUrl = protocol + '//' + window.location.host + proxyPrefix;
const sidecarHost = wsProxyPort ? window.location.hostname + ':' + wsProxyPort : window.location.host; const portGatewayUrl = wsProxyPort ? protocol + '//' + window.location.hostname + ':' + wsProxyPort + proxyPrefix : '';
const sidecarGatewayUrl = protocol + '//' + sidecarHost + 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 settingsKey = 'openclaw.control.settings.v1';
const settingsPrefix = 'openclaw.control.settings.v1:'; const settingsPrefix = 'openclaw.control.settings.v1:';
const tokenKey = 'openclaw.control.token.v1'; const tokenKey = 'openclaw.control.token.v1';
const tokenPrefix = '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 hashParams = new URLSearchParams(window.location.hash.startsWith('#') ? window.location.hash.slice(1) : window.location.hash);
const gatewayUrl = (hashParams.get('gatewayUrl') || '').trim() || sidecarGatewayUrl; const gatewayUrl = normalizeGatewayUrl(hashParams.get('gatewayUrl')) || defaultGatewayUrl;
const token = (hashParams.get('token') || '').trim(); const token = (hashParams.get('token') || '').trim();
const storageScope = (value) => { const storageScope = (value) => {
try { try {
@@ -180,7 +231,7 @@ function bootstrapScriptResponse(proxyPrefix: string) {
} }
}; };
const uniqueScopes = (values) => Array.from(new Set(values.map(storageScope).filter(Boolean))); const uniqueScopes = (values) => Array.from(new Set(values.map(storageScope).filter(Boolean)));
const gatewayScopes = uniqueScopes([gatewayUrl, sidecarGatewayUrl, pageGatewayUrl]); const gatewayScopes = uniqueScopes([gatewayUrl, configuredGatewayUrl, portGatewayUrl, pageGatewayUrl]);
const settingsKeys = gatewayScopes.map((scope) => settingsPrefix + scope); const settingsKeys = gatewayScopes.map((scope) => settingsPrefix + scope);
const readSettings = () => { const readSettings = () => {
for (const key of [...settingsKeys, settingsPrefix + 'default', settingsKey]) { for (const key of [...settingsKeys, settingsPrefix + 'default', settingsKey]) {
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server" import { NextResponse } from "next/server"
import { execOpenShell, normalizeSandboxPhase, resolveSandboxRef } from "@/app/lib/openshellHost" import { execOpenShell, normalizeSandboxPhase, resolveSandboxRef } from "@/app/lib/openshellHost"
import { listBackupCatalog } from "@/app/lib/backupCatalog" import { listBackupCatalog } from "@/app/lib/backupCatalog"
import { getNemoClawDoctorReport } from "@/app/lib/nemoclawCli"
function parseField(output: string, label: string) { function parseField(output: string, label: string) {
const normalizedLabel = label.toLowerCase() const normalizedLabel = label.toLowerCase()
@@ -23,6 +24,15 @@ export async function GET(
const phase = normalizeSandboxPhase(parseField(resolved.details, "Phase")) const phase = normalizeSandboxPhase(parseField(resolved.details, "Phase"))
const catalog = await listBackupCatalog() const catalog = await listBackupCatalog()
const relatedBackups = catalog.filter((backup) => backup.sandboxId === sandboxId || backup.sandboxName === resolved.name) const relatedBackups = catalog.filter((backup) => backup.sandboxId === sandboxId || backup.sandboxName === resolved.name)
const nemoclawDoctor = await getNemoClawDoctorReport(resolved.name).catch((error) => ({
available: false,
supported: false,
attempted: false,
version: null,
minimumVersion: "0.0.37",
report: null,
error: error instanceof Error ? error.message : "NemoClaw doctor check failed",
}))
let sshConfig = "" let sshConfig = ""
let sshConfigError = "" let sshConfigError = ""
@@ -60,6 +70,16 @@ export async function GET(
? `${relatedBackups.length} saved backup${relatedBackups.length === 1 ? "" : "s"} in catalog.` ? `${relatedBackups.length} saved backup${relatedBackups.length === 1 ? "" : "s"} in catalog.`
: "No saved catalog backups yet.", : "No saved catalog backups yet.",
}, },
{
key: "nemoclaw-doctor",
label: "NemoClaw doctor",
ok: !nemoclawDoctor.supported || Boolean(nemoclawDoctor.report && nemoclawDoctor.report.status !== "fail"),
detail: nemoclawDoctor.supported
? nemoclawDoctor.report
? `NemoClaw ${nemoclawDoctor.version || "unknown"} doctor reported ${nemoclawDoctor.report.status} (${nemoclawDoctor.report.failed} failed, ${nemoclawDoctor.report.warnings} warnings).`
: nemoclawDoctor.error || "NemoClaw doctor did not return a report."
: `Using OpenShell compatibility checks; NemoClaw doctor requires ${nemoclawDoctor.minimumVersion}+${nemoclawDoctor.version ? `, found ${nemoclawDoctor.version}` : ""}.`,
},
] ]
return NextResponse.json({ return NextResponse.json({
@@ -71,6 +91,19 @@ export async function GET(
phase, phase,
}, },
checks, checks,
nemoclaw: {
doctor: {
available: nemoclawDoctor.available,
supported: nemoclawDoctor.supported,
attempted: nemoclawDoctor.attempted,
version: nemoclawDoctor.version,
minimumVersion: nemoclawDoctor.minimumVersion,
status: nemoclawDoctor.report?.status ?? null,
failed: nemoclawDoctor.report?.failed ?? null,
warnings: nemoclawDoctor.report?.warnings ?? null,
error: nemoclawDoctor.error ?? null,
},
},
backupCount: relatedBackups.length, backupCount: relatedBackups.length,
durationMs: Date.now() - startedAt, durationMs: Date.now() - startedAt,
checkedAt: new Date().toISOString(), checkedAt: new Date().toISOString(),
+20 -1
View File
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server"
import { execFile } from "node:child_process" import { execFile } from "node:child_process"
import { promisify } from "node:util" import { promisify } from "node:util"
import { OPENSHELL_BIN, hostCommandEnv } from "@/app/lib/hostCommands" import { OPENSHELL_BIN, hostCommandEnv } from "@/app/lib/hostCommands"
import { recoverSandboxWithNemoClaw } from "@/app/lib/nemoclawCli"
import { inspectSandbox, resolveSandboxRef } from "@/app/lib/openshellHost" import { inspectSandbox, resolveSandboxRef } from "@/app/lib/openshellHost"
const execFileAsync = promisify(execFile) const execFileAsync = promisify(execFile)
@@ -100,6 +101,21 @@ export async function POST(
}, { status: 409 }) }, { status: 409 })
} }
const nemoclawRecover = await recoverSandboxWithNemoClaw(sandboxName)
if (nemoclawRecover.attempted && nemoclawRecover.ok) {
return NextResponse.json({
ok: true,
restarted: true,
restartMode: "nemoclaw-recover",
sandboxId: resolved.id,
sandboxName,
readiness,
nemoclawRecover,
elapsedMs: Date.now() - startedAt,
note: "NemoClaw recover completed. The sandbox runtime and dashboard forward were checked without deleting the sandbox.",
})
}
const runtime = await runSandboxShell(sandboxName, restartOpenClawGatewayScript(), 45000) const runtime = await runSandboxShell(sandboxName, restartOpenClawGatewayScript(), 45000)
return NextResponse.json({ return NextResponse.json({
@@ -109,9 +125,12 @@ export async function POST(
sandboxId: resolved.id, sandboxId: resolved.id,
sandboxName, sandboxName,
readiness, readiness,
nemoclawRecover,
runtime, runtime,
elapsedMs: Date.now() - startedAt, elapsedMs: Date.now() - startedAt,
note: "OpenClaw runtime restarted inside the sandbox. The sandbox pod was not deleted.", note: nemoclawRecover.attempted
? "NemoClaw recover did not complete, so the dashboard fell back to restarting the in-sandbox OpenClaw runtime. The sandbox pod was not deleted."
: "OpenClaw runtime restarted inside the sandbox. The sandbox pod was not deleted.",
}) })
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : "Failed to restart sandbox runtime" const message = error instanceof Error ? error.message : "Failed to restart sandbox runtime"
+44 -30
View File
@@ -40,6 +40,9 @@ const providerTypeOptions = [
{ value: "generic", label: "Generic" }, { value: "generic", label: "Generic" },
] ]
const OLLAMA_PROVIDER_NAME = "ollama-local"
const OLLAMA_BASE_URL = "http://host.docker.internal:11434/v1"
function emptyRoute(): InferenceRoute { function emptyRoute(): InferenceRoute {
return { configured: false, provider: null, model: null, version: null, timeout: null } return { configured: false, provider: null, model: null, version: null, timeout: null }
} }
@@ -111,7 +114,7 @@ export default function InferenceEndpointPanel() {
} }
const models = Array.isArray(data.models) ? data.models : [] const models = Array.isArray(data.models) ? data.models : []
setOllamaModels(models) setOllamaModels(models)
setOllamaMessage(models.length > 0 ? `${models.length} Ollama model${models.length === 1 ? "" : "s"} available.` : "Ollama is reachable but has no models installed.") setOllamaMessage(models.length > 0 ? `${models.length} Ollama model${models.length === 1 ? "" : "s"} available. Click one to load the Ollama endpoint preset.` : "Ollama is reachable but has no models installed.")
if (models[0]?.name) setModel((current) => current || models[0].name) if (models[0]?.name) setModel((current) => current || models[0].name)
} catch (error) { } catch (error) {
setOllamaModels([]) setOllamaModels([])
@@ -122,11 +125,22 @@ export default function InferenceEndpointPanel() {
}, []) }, [])
useEffect(() => { useEffect(() => {
if (!isOllamaEndpoint) return
loadOllamaModels({ silent: true }) loadOllamaModels({ silent: true })
const interval = window.setInterval(() => loadOllamaModels({ silent: true }), 10000) const interval = window.setInterval(() => loadOllamaModels({ silent: true }), 10000)
return () => window.clearInterval(interval) return () => window.clearInterval(interval)
}, [isOllamaEndpoint, loadOllamaModels]) }, [loadOllamaModels])
function applyOllamaModelPreset(modelName: string) {
setName(OLLAMA_PROVIDER_NAME)
setType("openai")
setModel(modelName)
setBaseUrl(OLLAMA_BASE_URL)
setCredentialKey("OPENAI_API_KEY")
setApiKey("")
setRoute("gateway")
setNoVerify(true)
setMessage(`Ollama preset loaded for ${modelName}. Save to route sandbox inference through local Ollama.`)
}
function selectProvider(provider: ProviderSummary) { function selectProvider(provider: ProviderSummary) {
if (!provider.name) return if (!provider.name) return
@@ -134,7 +148,7 @@ export default function InferenceEndpointPanel() {
setType(provider.type || "openai") setType(provider.type || "openai")
setCredentialKey(provider.credentialKeys[0] || "OPENAI_API_KEY") setCredentialKey(provider.credentialKeys[0] || "OPENAI_API_KEY")
if (provider.name.toLowerCase().includes("ollama")) { if (provider.name.toLowerCase().includes("ollama")) {
setBaseUrl("http://host.docker.internal:11434/v1") setBaseUrl(OLLAMA_BASE_URL)
setApiKey("") setApiKey("")
} }
setMessage(`Loaded ${provider.name}. Enter a model and save to make it active.`) setMessage(`Loaded ${provider.name}. Enter a model and save to make it active.`)
@@ -252,6 +266,32 @@ export default function InferenceEndpointPanel() {
<div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_360px] gap-6"> <div className="grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_360px] gap-6">
<section className="space-y-4"> <section className="space-y-4">
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<div className="flex items-center justify-between gap-4">
<div>
<h3 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Ollama Models</h3>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">{ollamaMessage || "Polling local Ollama every 10 seconds."}</p>
</div>
<button type="button" onClick={() => loadOllamaModels()} disabled={ollamaLoading} className="px-3 py-2 rounded-sm bg-[var(--background)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)] disabled:opacity-50">
{ollamaLoading ? "Polling..." : "Poll"}
</button>
</div>
{ollamaModels.length > 0 ? (
<div className="mt-3 grid grid-cols-1 md:grid-cols-2 gap-2">
{ollamaModels.map((item) => (
<button key={item.name} type="button" onClick={() => applyOllamaModelPreset(item.name)} className={`rounded-sm border p-3 text-left ${isOllamaEndpoint && model === item.name ? "border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]" : "border-[var(--border-subtle)] bg-[var(--background)] hover:border-[var(--nvidia-green)]"}`}>
<div className="text-xs font-mono text-[var(--foreground)]">{item.name}</div>
<div className="mt-1 text-[11px] text-[var(--foreground-dim)]">
{[item.parameterSize, item.quantization, item.sizeLabel].filter(Boolean).join(" · ") || item.family || "local model"}
</div>
</button>
))}
</div>
) : (
<p className="mt-3 text-xs text-[var(--foreground-dim)]">No local Ollama models reported.</p>
)}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2"> <div className="space-y-2">
<FieldLabel>Provider Name</FieldLabel> <FieldLabel>Provider Name</FieldLabel>
@@ -303,32 +343,6 @@ export default function InferenceEndpointPanel() {
Skip provider verification while saving Skip provider verification while saving
</label> </label>
{isOllamaEndpoint && (
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
<div className="flex items-center justify-between gap-4">
<div>
<h3 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Ollama Models</h3>
<p className="mt-1 text-xs text-[var(--foreground-dim)]">{ollamaMessage || "Polling local Ollama every 10 seconds."}</p>
</div>
<button type="button" onClick={() => loadOllamaModels()} disabled={ollamaLoading} className="px-3 py-2 rounded-sm bg-[var(--background)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)] disabled:opacity-50">
{ollamaLoading ? "Polling..." : "Poll"}
</button>
</div>
{ollamaModels.length > 0 && (
<div className="mt-3 grid grid-cols-1 md:grid-cols-2 gap-2">
{ollamaModels.map((item) => (
<button key={item.name} type="button" onClick={() => setModel(item.name)} className={`rounded-sm border p-3 text-left ${model === item.name ? "border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]" : "border-[var(--border-subtle)] bg-[var(--background)]"}`}>
<div className="text-xs font-mono text-[var(--foreground)]">{item.name}</div>
<div className="mt-1 text-[11px] text-[var(--foreground-dim)]">
{[item.parameterSize, item.quantization, item.sizeLabel].filter(Boolean).join(" · ") || item.family || "local model"}
</div>
</button>
))}
</div>
)}
</div>
)}
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<button onClick={saveEndpoint} disabled={saving} className="px-4 py-2 rounded-sm bg-[var(--nvidia-green)] text-white text-xs font-mono uppercase tracking-wider disabled:opacity-50"> <button onClick={saveEndpoint} disabled={saving} className="px-4 py-2 rounded-sm bg-[var(--nvidia-green)] text-white text-xs font-mono uppercase tracking-wider disabled:opacity-50">
{saving ? "Saving..." : "Save Endpoint"} {saving ? "Saving..." : "Save Endpoint"}
+46 -1
View File
@@ -1,6 +1,13 @@
const COOKIE_NAME = "openshell_control_session" const COOKIE_NAME = "openshell_control_session"
const SESSION_TTL_SECONDS = 12 * 60 * 60 const SESSION_TTL_SECONDS = 12 * 60 * 60
type CookieSecurityRequest = {
headers: Pick<Headers, "get">
nextUrl?: {
protocol: string
}
}
type SessionPayload = { type SessionPayload = {
sub: string sub: string
iat: number iat: number
@@ -24,6 +31,37 @@ function isDisabled() {
return /^(1|true|yes|on)$/i.test(process.env.OPENSHELL_CONTROL_AUTH_DISABLED || "") return /^(1|true|yes|on)$/i.test(process.env.OPENSHELL_CONTROL_AUTH_DISABLED || "")
} }
function envFlag(value: string | undefined) {
if (!value) return null
if (/^(1|true|yes|on)$/i.test(value)) return true
if (/^(0|false|no|off)$/i.test(value)) return false
return null
}
function firstForwardedValue(value: string | null) {
return value?.split(",")[0]?.trim().toLowerCase() || ""
}
function publicBaseUsesHttps() {
if (!process.env.PUBLIC_BASE_URL) return false
try {
return new URL(process.env.PUBLIC_BASE_URL).protocol === "https:"
} catch {
return false
}
}
export function shouldUseSecureSessionCookie(request?: CookieSecurityRequest) {
const forced = envFlag(process.env.OPENSHELL_CONTROL_COOKIE_SECURE)
if (forced !== null) return forced
const forwardedProto = request ? firstForwardedValue(request.headers.get("x-forwarded-proto")) : ""
if (forwardedProto) return forwardedProto === "https"
if (request?.nextUrl?.protocol === "https:") return true
return publicBaseUsesHttps()
}
async function hmac(payload: string) { async function hmac(payload: string) {
const key = await crypto.subtle.importKey( const key = await crypto.subtle.importKey(
"raw", "raw",
@@ -99,7 +137,14 @@ export async function verifyRecoveryToken(token: string) {
export const sessionCookieOptions = { export const sessionCookieOptions = {
httpOnly: true, httpOnly: true,
sameSite: "lax" as const, sameSite: "lax" as const,
secure: process.env.NODE_ENV === "production", secure: shouldUseSecureSessionCookie(),
path: "/", path: "/",
maxAge: SESSION_TTL_SECONDS, maxAge: SESSION_TTL_SECONDS,
} }
export function sessionCookieOptionsForRequest(request: CookieSecurityRequest) {
return {
...sessionCookieOptions,
secure: shouldUseSecureSessionCookie(request),
}
}
+2 -1
View File
@@ -124,6 +124,7 @@ function buildEnvBlock(input: {
`CONTROLLER_NODE_ID=${input.controllerName}`, `CONTROLLER_NODE_ID=${input.controllerName}`,
`CONTROLLER_NODE_PARENT_URL=${input.parentControllerUrl}`, `CONTROLLER_NODE_PARENT_URL=${input.parentControllerUrl}`,
`CONTROLLER_NODE_SHARED_SECRET=${input.token}`, `CONTROLLER_NODE_SHARED_SECRET=${input.token}`,
`PORT=${input.dashboardPort}`,
`NEXT_PUBLIC_DASHBOARD_PORT=${input.dashboardPort}`, `NEXT_PUBLIC_DASHBOARD_PORT=${input.dashboardPort}`,
"NEXT_PUBLIC_API_BASE=", "NEXT_PUBLIC_API_BASE=",
"NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS=true", "NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS=true",
@@ -217,7 +218,7 @@ ENV_CONTROLLER_NODE
touch .env.local touch .env.local
TMP_ENV="$(mktemp)" TMP_ENV="$(mktemp)"
grep -Ev '^(CONTROLLER_NODE_ID|CONTROLLER_NODE_PARENT_URL|CONTROLLER_NODE_SHARED_SECRET|NEXT_PUBLIC_DASHBOARD_PORT|NEXT_PUBLIC_API_BASE|NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS|OPENSHELL_GATEWAY|OPEN_SHELL_CONTAINER|TERMINAL_SERVER_AUTOSTART|TERMINAL_SERVER_PORT|OPENCLAW_DASHBOARD_URL|OPENCLAW_INSTANCE_REGISTRY_JSON)=' .env.local > "$TMP_ENV" || true grep -Ev '^(CONTROLLER_NODE_ID|CONTROLLER_NODE_PARENT_URL|CONTROLLER_NODE_SHARED_SECRET|PORT|NEXT_PUBLIC_DASHBOARD_PORT|NEXT_PUBLIC_API_BASE|NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS|OPENSHELL_GATEWAY|OPEN_SHELL_CONTAINER|TERMINAL_SERVER_AUTOSTART|TERMINAL_SERVER_PORT|OPENCLAW_DASHBOARD_URL|OPENCLAW_INSTANCE_REGISTRY_JSON)=' .env.local > "$TMP_ENV" || true
cat "$TMP_ENV" .env.controller-node > .env.local cat "$TMP_ENV" .env.controller-node > .env.local
rm -f "$TMP_ENV" rm -f "$TMP_ENV"
chmod 600 .env.local .env.controller-node chmod 600 .env.local .env.controller-node
+217
View File
@@ -0,0 +1,217 @@
import { execFile } from "node:child_process"
import { promisify } from "node:util"
import { NEMOCLAW_BIN, NODE_BIN, commandExists, hostCommandEnv } from "./hostCommands"
const execFileAsync = promisify(execFile)
const NEMOCLAW_RECOVERY_MIN_VERSION = "0.0.37"
type NemoClawInvocation = {
file: string
args: string[]
display: string[]
}
type NemoClawRunResult = {
ok: boolean
stdout: string
stderr: string
exitCode: number | null
error: string | null
}
export type NemoClawDoctorCheck = {
group: string
label: string
status: "ok" | "warn" | "fail" | "info"
detail: string
hint?: string
}
export type NemoClawDoctorReport = {
schemaVersion: number
sandbox: string
status: "ok" | "warn" | "fail" | "info"
failed: number
warnings: number
checks: NemoClawDoctorCheck[]
}
function buildNemoClawInvocation(args: string[]): NemoClawInvocation | null {
if (!commandExists(NEMOCLAW_BIN)) return null
if (/\.(?:c?m?js|ts)$/i.test(NEMOCLAW_BIN)) {
return {
file: NODE_BIN,
args: [NEMOCLAW_BIN, ...args],
display: [NODE_BIN, NEMOCLAW_BIN, ...args],
}
}
return {
file: NEMOCLAW_BIN,
args,
display: [NEMOCLAW_BIN, ...args],
}
}
function parseVersion(value: string) {
return value.match(/v?(\d+\.\d+\.\d+)/)?.[1] ?? null
}
function versionGte(left: string, right: string) {
const leftParts = left.split(".").map((part) => Number.parseInt(part, 10) || 0)
const rightParts = right.split(".").map((part) => Number.parseInt(part, 10) || 0)
const length = Math.max(leftParts.length, rightParts.length)
for (let index = 0; index < length; index += 1) {
const a = leftParts[index] || 0
const b = rightParts[index] || 0
if (a > b) return true
if (a < b) return false
}
return true
}
function parseJsonObject(value: string) {
const trimmed = value.trim()
if (!trimmed) return null
try {
return JSON.parse(trimmed)
} catch {
const start = trimmed.indexOf("{")
const end = trimmed.lastIndexOf("}")
if (start === -1 || end === -1 || end <= start) return null
return JSON.parse(trimmed.slice(start, end + 1))
}
}
async function runNemoClaw(args: string[], timeout = 30000): Promise<NemoClawRunResult & { command: string[] }> {
const invocation = buildNemoClawInvocation(args)
if (!invocation) {
return {
ok: false,
stdout: "",
stderr: "",
exitCode: null,
error: "NemoClaw CLI is not available",
command: [NEMOCLAW_BIN, ...args],
}
}
try {
const { stdout, stderr } = await execFileAsync(invocation.file, invocation.args, {
env: hostCommandEnv({
OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
NO_COLOR: "1",
CLICOLOR: "0",
CLICOLOR_FORCE: "0",
}),
timeout,
maxBuffer: 8 * 1024 * 1024,
})
return {
ok: true,
stdout: String(stdout).trim(),
stderr: String(stderr).trim(),
exitCode: 0,
error: null,
command: invocation.display,
}
} catch (error: any) {
return {
ok: false,
stdout: String(error?.stdout || "").trim(),
stderr: String(error?.stderr || "").trim(),
exitCode: typeof error?.code === "number" ? error.code : null,
error: error instanceof Error ? error.message : String(error ?? "NemoClaw command failed"),
command: invocation.display,
}
}
}
export async function getNemoClawVersion() {
const result = await runNemoClaw(["--version"], 10000)
const version = parseVersion(`${result.stdout}\n${result.stderr}`)
return {
available: result.ok || Boolean(version),
version,
stdout: result.stdout,
stderr: result.stderr,
error: result.ok ? null : result.error,
command: result.command,
}
}
async function hasModernNemoClawSurface() {
const version = await getNemoClawVersion()
return {
...version,
supported: version.version ? versionGte(version.version, NEMOCLAW_RECOVERY_MIN_VERSION) : false,
minimumVersion: NEMOCLAW_RECOVERY_MIN_VERSION,
}
}
export async function getNemoClawDoctorReport(sandboxName: string) {
const capability = await hasModernNemoClawSurface()
if (!capability.supported) {
return {
available: capability.available,
supported: false,
attempted: false,
version: capability.version,
minimumVersion: capability.minimumVersion,
report: null as NemoClawDoctorReport | null,
error: capability.available
? `NemoClaw ${capability.version || "unknown"} does not expose doctor --json`
: capability.error || "NemoClaw CLI is not available",
}
}
const result = await runNemoClaw([sandboxName, "doctor", "--json"], 30000)
const parsed = result.ok ? parseJsonObject(result.stdout) : null
const report = parsed && typeof parsed === "object" ? parsed as NemoClawDoctorReport : null
return {
available: true,
supported: true,
attempted: true,
version: capability.version,
minimumVersion: capability.minimumVersion,
report,
error: report ? null : result.error || result.stderr || "NemoClaw doctor did not return JSON",
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
}
}
export async function recoverSandboxWithNemoClaw(sandboxName: string) {
const capability = await hasModernNemoClawSurface()
if (!capability.supported) {
return {
available: capability.available,
supported: false,
attempted: false,
version: capability.version,
minimumVersion: capability.minimumVersion,
ok: false,
stdout: "",
stderr: "",
exitCode: null as number | null,
error: capability.available
? `NemoClaw ${capability.version || "unknown"} does not expose sandbox recover`
: capability.error || "NemoClaw CLI is not available",
}
}
const result = await runNemoClaw([sandboxName, "recover"], 90000)
return {
available: true,
supported: true,
attempted: true,
version: capability.version,
minimumVersion: capability.minimumVersion,
ok: result.ok,
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
error: result.error,
}
}
+34
View File
@@ -0,0 +1,34 @@
import type { NextResponse } from "next/server"
import { shouldUseSecureSessionCookie } from "./controlAuth"
export const OPENCLAW_DASHBOARD_TOKEN_COOKIE = "openclaw_dashboard_token"
const DASHBOARD_TOKEN_TTL_SECONDS = 12 * 60 * 60
export function dashboardTokenCookieOptions(request: Request, path: string) {
return {
httpOnly: true,
sameSite: "lax" as const,
secure: shouldUseSecureSessionCookie({
headers: request.headers,
nextUrl: new URL(request.url),
}),
path,
maxAge: DASHBOARD_TOKEN_TTL_SECONDS,
}
}
export function extractOpenClawDashboardToken(url: string | null | undefined) {
if (!url) return null
try {
const parsed = new URL(url)
const hash = parsed.hash.startsWith("#") ? parsed.hash.slice(1) : parsed.hash
return new URLSearchParams(hash).get("token")?.trim() || null
} catch {
return null
}
}
export function setOpenClawDashboardTokenCookie(response: NextResponse, request: Request, path: string, token: string | null) {
if (!token) return
response.cookies.set(OPENCLAW_DASHBOARD_TOKEN_COOKIE, token, dashboardTokenCookieOptions(request, path))
}
+7 -2
View File
@@ -368,7 +368,6 @@ else
fi fi
check_port 3000 "dashboard HTTP" check_port 3000 "dashboard HTTP"
check_port 3001 "OpenClaw dashboard websocket sidecar"
check_port 3011 "operator terminal upstream" check_port 3011 "operator terminal upstream"
if docker ps --format '{{.Names}}' | grep -Eq '^openshell-cluster-'; then if docker ps --format '{{.Names}}' | grep -Eq '^openshell-cluster-'; then
@@ -398,6 +397,7 @@ if [[ ! -f "$ENV_FILE" ]]; then
log "Creating $ENV_FILE" log "Creating $ENV_FILE"
cat > "$ENV_FILE" <<EOF cat > "$ENV_FILE" <<EOF
# OpenShell Control local configuration # OpenShell Control local configuration
PORT=3000
NEXT_PUBLIC_DASHBOARD_PORT=3000 NEXT_PUBLIC_DASHBOARD_PORT=3000
NEXT_PUBLIC_API_BASE=/api NEXT_PUBLIC_API_BASE=/api
NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS=true NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS=true
@@ -407,11 +407,16 @@ OPENSHELL_GATEWAY=nemoclaw
# OPENSHELL_GATEWAY_HOST=host.docker.internal # OPENSHELL_GATEWAY_HOST=host.docker.internal
# OPENSHELL_GATEWAY_PORT=8080 # OPENSHELL_GATEWAY_PORT=8080
# OPENSHELL_GATEWAY_URL=http://host.docker.internal:8080 # OPENSHELL_GATEWAY_URL=http://host.docker.internal:8080
# For reverse proxies, OpenClaw dashboard websockets use the same-origin proxy path by default.
# OPENCLAW_DASHBOARD_BASE_WS_URL=wss://control.example.com
# BASE_WS_URL=wss://control.example.com
# OPENCLAW_DASHBOARD_WS_PROXY_PORT=3001
EOF EOF
else else
log "Keeping existing $ENV_FILE" log "Keeping existing $ENV_FILE"
fi fi
upsert_env "PORT" "3000"
upsert_env "NEXT_PUBLIC_DASHBOARD_PORT" "3000" upsert_env "NEXT_PUBLIC_DASHBOARD_PORT" "3000"
upsert_env "NEXT_PUBLIC_API_BASE" "/api" upsert_env "NEXT_PUBLIC_API_BASE" "/api"
upsert_env "NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS" "true" upsert_env "NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS" "true"
@@ -461,8 +466,8 @@ echo " http://localhost:3000"
echo "" echo ""
echo "Ports used by default:" echo "Ports used by default:"
echo " 3000 dashboard HTTP" echo " 3000 dashboard HTTP"
echo " 3001 OpenClaw dashboard websocket sidecar"
echo " 3011 operator terminal upstream" echo " 3011 operator terminal upstream"
echo "Optional legacy OpenClaw dashboard websocket sidecar: set OPENCLAW_DASHBOARD_WS_PROXY_PORT."
echo "" echo ""
if [[ "$DO_START" -eq 1 ]]; then if [[ "$DO_START" -eq 1 ]]; then
+4 -3
View File
@@ -3,10 +3,11 @@
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "node server.mjs", "dev": "NODE_ENV=development node server.mjs",
"dev:proxy": "node server.mjs", "dev:proxy": "NODE_ENV=development node server.mjs",
"build": "next build", "build": "next build",
"start": "node server.mjs", "start": "NODE_ENV=production node server.mjs",
"start:prod": "npm run build && npm run start",
"lint": "next lint", "lint": "next lint",
"terminal-server": "node terminal-server.mjs" "terminal-server": "node terminal-server.mjs"
}, },
+297 -76
View File
@@ -21,10 +21,20 @@ function loadLocalEnvFile(pathname) {
loadLocalEnvFile('.env.local') loadLocalEnvFile('.env.local')
function parseOptionalPort(value, name) {
const raw = typeof value === 'string' ? value.trim() : ''
if (!raw) return null
const parsed = Number(raw)
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
throw new Error(`${name} must be a TCP port between 1 and 65535`)
}
return parsed
}
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 || process.env.NEXT_PUBLIC_DASHBOARD_PORT || 3000)
const dashboardWsProxyPort = Number(process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT || 3001) const dashboardWsProxyPort = parseOptionalPort(process.env.OPENCLAW_DASHBOARD_WS_PROXY_PORT, 'OPENCLAW_DASHBOARD_WS_PROXY_PORT')
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'
@@ -36,6 +46,7 @@ const defaultInstanceId = 'default'
const sandboxDashboardPortBase = Number.parseInt(process.env.OPENCLAW_SANDBOX_DASHBOARD_PORT_BASE || '19000', 10) const sandboxDashboardPortBase = Number.parseInt(process.env.OPENCLAW_SANDBOX_DASHBOARD_PORT_BASE || '19000', 10)
const sandboxDashboardPortRange = 2000 const sandboxDashboardPortRange = 2000
const authCookieName = 'openshell_control_session' const authCookieName = 'openshell_control_session'
const openClawDashboardTokenCookieName = 'openclaw_dashboard_token'
function now() { function now() {
return new Date().toISOString() return new Date().toISOString()
@@ -72,6 +83,27 @@ function safeEqual(left, right) {
return leftBuffer.length === rightBuffer.length && crypto.timingSafeEqual(leftBuffer, rightBuffer) return leftBuffer.length === rightBuffer.length && crypto.timingSafeEqual(leftBuffer, rightBuffer)
} }
function filterCookieHeader(value) {
return String(value || '')
.split(';')
.map((part) => part.trim())
.filter((part) => part && !part.startsWith(`${authCookieName}=`) && !part.startsWith(`${openClawDashboardTokenCookieName}=`))
.join('; ')
}
function readCookieValue(value, name) {
for (const part of String(value || '').split(';')) {
const trimmed = part.trim()
if (!trimmed.startsWith(`${name}=`)) continue
try {
return decodeURIComponent(trimmed.slice(name.length + 1))
} catch {
return trimmed.slice(name.length + 1)
}
}
return null
}
function parseCookies(req) { function parseCookies(req) {
return String(req.headers.cookie || '') return String(req.headers.cookie || '')
.split(';') .split(';')
@@ -304,6 +336,26 @@ function normalizeCloseCode(code) {
: 1000 : 1000
} }
function redactSensitiveUrl(value) {
try {
const url = new URL(value.toString())
for (const key of ['token', 'authToken', 'access_token']) {
if (url.searchParams.has(key)) url.searchParams.set(key, '<redacted>')
}
return url.toString()
} catch {
return String(value || '')
}
}
function withDashboardTokenQuery(upstreamWsUrl, token) {
const url = new URL(upstreamWsUrl.toString())
if (token && !url.searchParams.has('token') && !url.searchParams.has('authToken')) {
url.searchParams.set('token', token)
}
return url
}
function shouldAutoStartTerminalServer() { function shouldAutoStartTerminalServer() {
if (/^(0|false|no|off)$/i.test(process.env.TERMINAL_SERVER_AUTOSTART || '')) return false if (/^(0|false|no|off)$/i.test(process.env.TERMINAL_SERVER_AUTOSTART || '')) return false
if (terminalServerUrl.protocol !== 'http:') return false if (terminalServerUrl.protocol !== 'http:') return false
@@ -393,45 +445,221 @@ const handleUpgrade = typeof app.getUpgradeHandler === 'function'
: null : null
const server = http.createServer((req, res) => handle(req, res)) const server = http.createServer((req, res) => handle(req, res))
const dashboardWsProxyServer = http.createServer((_, res) => { const dashboardWsProxyServer = dashboardWsProxyPort
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }) ? http.createServer((_, res) => {
res.end('OpenClaw dashboard websocket proxy only') res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
}) res.end('OpenClaw dashboard websocket proxy only')
})
: null
const clientWss = new WebSocketServer({ noServer: true }) const clientWss = new WebSocketServer({ noServer: true })
const dashboardWss = new WebSocketServer({ noServer: true })
function copyDashboardWebSocketHeaders(req, controlUiOrigin) {
const headers = copyHeaders(req)
const cookie = filterCookieHeader(req.headers.cookie)
const dashboardToken = readCookieValue(req.headers.cookie, openClawDashboardTokenCookieName)
if (cookie) headers.cookie = cookie
else delete headers.cookie
headers.origin = controlUiOrigin
headers.referer = `${controlUiOrigin}/`
if (dashboardToken && !headers.authorization) headers.authorization = `Bearer ${dashboardToken}`
return headers
}
function handleDashboardProxyUpgrade(req, socket, head, logEvent) {
const { upstreamWsUrl, instanceId, controlUiOrigin } = resolveDashboardUpstream(req)
logBridge(logEvent, {
path: req.url || '/',
upstreamUrl: upstreamWsUrl.toString(),
instanceId,
remoteAddress: req.socket.remoteAddress || 'unknown',
})
dashboardWss.handleUpgrade(req, socket, head, (ws) => {
dashboardWss.emit('connection', ws, req, { upstreamWsUrl, instanceId, controlUiOrigin })
})
}
dashboardWss.on('connection', (client, req, context) => {
const bridgeId = crypto.randomUUID()
const dashboardToken = readCookieValue(req.headers.cookie, openClawDashboardTokenCookieName)
const upstreamUrl = withDashboardTokenQuery(context.upstreamWsUrl, dashboardToken)
const redactedUpstreamUrl = redactSensitiveUrl(upstreamUrl)
const upstreamHeaders = copyDashboardWebSocketHeaders(req, context.controlUiOrigin)
const upstream = new WebSocket(upstreamUrl.toString(), {
headers: upstreamHeaders,
})
const pendingClientFrames = []
let closing = false
let clientFramesIn = 0
let upstreamFramesOut = 0
let upstreamFramesIn = 0
let clientFramesOut = 0
logBridge('dashboard-ws-client-connected', {
bridgeId,
path: req.url || '/',
upstreamUrl: redactedUpstreamUrl,
instanceId: context.instanceId,
remoteAddress: req.socket.remoteAddress || 'unknown',
upstreamHeaderKeys: Object.keys(upstreamHeaders).sort().join(','),
dashboardTokenPresent: Boolean(dashboardToken),
})
const flushPendingFrames = () => {
while (pendingClientFrames.length && upstream.readyState === WebSocket.OPEN) {
const frame = pendingClientFrames.shift()
upstreamFramesOut += 1
upstream.send(frame.data, { binary: frame.isBinary })
}
logBridge('dashboard-ws-upstream-open', {
bridgeId,
bufferedFramesFlushed: upstreamFramesOut,
pendingFrames: pendingClientFrames.length,
})
}
const closeClient = (code = 1000, reason) => {
const safeCode = normalizeCloseCode(code)
if (client.readyState === WebSocket.OPEN) client.close(safeCode, reason)
else if (client.readyState === WebSocket.CONNECTING) client.terminate()
}
const closeUpstream = (code = 1000, reason) => {
const safeCode = normalizeCloseCode(code)
if (upstream.readyState === WebSocket.OPEN) upstream.close(safeCode, reason)
else if (upstream.readyState === WebSocket.CONNECTING) upstream.terminate()
}
const closeBoth = (code = 1000, reason, source = 'unknown') => {
if (closing) return
closing = true
logBridge('dashboard-ws-closing', {
bridgeId,
source,
code,
reason,
clientFramesIn,
upstreamFramesOut,
upstreamFramesIn,
clientFramesOut,
pendingFrames: pendingClientFrames.length,
})
closeClient(code, reason)
closeUpstream(code, reason)
}
client.on('message', (data, isBinary) => {
clientFramesIn += 1
if (upstream.readyState === WebSocket.OPEN) {
upstreamFramesOut += 1
upstream.send(data, { binary: isBinary })
return
}
if (upstream.readyState === WebSocket.CONNECTING) {
pendingClientFrames.push({ data, isBinary })
return
}
closeBoth(1011, 'upstream unavailable', 'dashboard-client-message-no-upstream')
})
client.on('close', (code, reasonBuffer) => {
const reason = Buffer.isBuffer(reasonBuffer) ? reasonBuffer.toString() : String(reasonBuffer || '')
closeBoth(code || 1000, reason || undefined, 'dashboard-client-close')
})
client.on('error', (error) => closeBoth(1011, error instanceof Error ? error.message : 'dashboard client error', 'dashboard-client-error'))
upstream.on('open', () => {
logBridge('dashboard-ws-upstream-connected', {
bridgeId,
upstreamUrl: redactedUpstreamUrl,
instanceId: context.instanceId,
})
flushPendingFrames()
})
upstream.on('message', (data, isBinary) => {
upstreamFramesIn += 1
if (client.readyState === WebSocket.OPEN) {
clientFramesOut += 1
client.send(data, { binary: isBinary })
}
})
upstream.on('close', (code, reasonBuffer) => {
const reason = Buffer.isBuffer(reasonBuffer) ? reasonBuffer.toString() : String(reasonBuffer || '')
closeBoth(code || 1000, reason || undefined, 'dashboard-upstream-close')
})
upstream.on('error', (error) => {
logBridge('dashboard-ws-upstream-error', {
bridgeId,
upstreamUrl: redactedUpstreamUrl,
instanceId: context.instanceId,
reason: error instanceof Error ? error.message : 'dashboard upstream error',
})
closeBoth(1011, error instanceof Error ? error.message : 'dashboard upstream error', 'dashboard-upstream-error')
})
})
function buildRawDashboardUpgradeHeaders(req, upstreamWsUrl, controlUiOrigin) { function buildRawDashboardUpgradeHeaders(req, upstreamWsUrl, controlUiOrigin) {
const headers = [] const headers = []
const seen = new Set() const dashboardToken = readCookieValue(req.headers.cookie, openClawDashboardTokenCookieName)
const rawHeaders = new Map()
for (let i = 0; i < req.rawHeaders.length; i += 2) { for (let i = 0; i < req.rawHeaders.length; i += 2) {
const name = req.rawHeaders[i] const name = req.rawHeaders[i]
const value = req.rawHeaders[i + 1] const value = req.rawHeaders[i + 1]
const lowerName = name.toLowerCase() const lowerName = name.toLowerCase()
seen.add(lowerName) if (!rawHeaders.has(lowerName)) rawHeaders.set(lowerName, [])
if (lowerName === 'host') { rawHeaders.get(lowerName).push({ name, value })
headers.push(`Host: ${upstreamWsUrl.host}`) }
} else if (lowerName === 'origin') {
headers.push(`Origin: ${controlUiOrigin}`) const firstValue = (name) => rawHeaders.get(name)?.[0]?.value
} else { const pushRaw = (name) => {
headers.push(`${name}: ${value}`) for (const header of rawHeaders.get(name) || []) {
headers.push(`${header.name}: ${header.value}`)
} }
} }
if (!seen.has('host')) headers.push(`Host: ${upstreamWsUrl.host}`) headers.push(`Host: ${upstreamWsUrl.host}`)
if (!seen.has('origin')) headers.push(`Origin: ${controlUiOrigin}`) headers.push(`Upgrade: ${firstValue('upgrade') || 'websocket'}`)
headers.push(`Connection: ${firstValue('connection') || 'Upgrade'}`)
if (firstValue('sec-websocket-key')) pushRaw('sec-websocket-key')
if (firstValue('sec-websocket-version')) pushRaw('sec-websocket-version')
pushRaw('sec-websocket-protocol')
pushRaw('sec-websocket-extensions')
headers.push(`Origin: ${controlUiOrigin}`)
for (const header of rawHeaders.get('cookie') || []) {
const filteredCookie = filterCookieHeader(header.value)
if (filteredCookie) headers.push(`Cookie: ${filteredCookie}`)
}
if (rawHeaders.has('authorization')) {
pushRaw('authorization')
} else if (dashboardToken) {
headers.push(`Authorization: Bearer ${dashboardToken}`)
}
return headers return headers
} }
function tunnelDashboardUpgrade(req, socket, head, upstreamWsUrl, instanceId, controlUiOrigin) { function tunnelDashboardUpgrade(req, socket, head, upstreamWsUrl, instanceId, controlUiOrigin) {
const isSecure = upstreamWsUrl.protocol === 'wss:' socket.pause()
const port = Number(upstreamWsUrl.port || (isSecure ? 443 : 80)) const dashboardToken = readCookieValue(req.headers.cookie, openClawDashboardTokenCookieName)
const upstreamUrlWithToken = withDashboardTokenQuery(upstreamWsUrl, dashboardToken)
const redactedUpstreamUrl = redactSensitiveUrl(upstreamUrlWithToken)
const isSecure = upstreamUrlWithToken.protocol === 'wss:'
const port = Number(upstreamUrlWithToken.port || (isSecure ? 443 : 80))
const upstreamSocket = isSecure const upstreamSocket = isSecure
? tls.connect({ host: upstreamWsUrl.hostname, port, servername: upstreamWsUrl.hostname }) ? tls.connect({ host: upstreamUrlWithToken.hostname, port, servername: upstreamUrlWithToken.hostname })
: net.connect({ host: upstreamWsUrl.hostname, port }) : net.connect({ host: upstreamUrlWithToken.hostname, port })
const upstreamPath = `${upstreamWsUrl.pathname || '/'}${upstreamWsUrl.search || ''}` const upstreamPath = `${upstreamUrlWithToken.pathname || '/'}${upstreamUrlWithToken.search || ''}`
const requestHead = [ const requestHead = [
`GET ${upstreamPath} HTTP/1.1`, `GET ${upstreamPath} HTTP/1.1`,
...buildRawDashboardUpgradeHeaders(req, upstreamWsUrl, controlUiOrigin), ...buildRawDashboardUpgradeHeaders(req, upstreamUrlWithToken, controlUiOrigin),
'', '',
'', '',
].join('\r\n') ].join('\r\n')
@@ -443,30 +671,31 @@ function tunnelDashboardUpgrade(req, socket, head, upstreamWsUrl, instanceId, co
opened = true opened = true
upstreamSocket.write(requestHead) upstreamSocket.write(requestHead)
if (head?.length) upstreamSocket.write(head) if (head?.length) upstreamSocket.write(head)
socket.pipe(upstreamSocket, { end: false })
upstreamSocket.pipe(socket, { end: false })
upstreamSocket.resume() upstreamSocket.resume()
socket.resume() socket.resume()
logBridge('dashboard-tunnel-open', { logBridge('dashboard-tunnel-open', {
path: req.url || '/', path: req.url || '/',
upstreamUrl: upstreamWsUrl.toString(), upstreamUrl: redactedUpstreamUrl,
instanceId, instanceId,
remoteAddress: req.socket.remoteAddress || 'unknown', remoteAddress: req.socket.remoteAddress || 'unknown',
dashboardTokenPresent: Boolean(dashboardToken),
}) })
}) })
upstreamSocket.on('data', (chunk) => { upstreamSocket.on('data', (chunk) => {
upstreamBytes += chunk.length upstreamBytes += chunk.length
if (!socket.destroyed) socket.write(chunk)
}) })
socket.on('data', (chunk) => { socket.on('data', (chunk) => {
clientBytes += chunk.length clientBytes += chunk.length
if (!upstreamSocket.destroyed) upstreamSocket.write(chunk)
}) })
upstreamSocket.on('error', (error) => { upstreamSocket.on('error', (error) => {
logBridge('dashboard-tunnel-error', { logBridge('dashboard-tunnel-error', {
path: req.url || '/', path: req.url || '/',
upstreamUrl: upstreamWsUrl.toString(), upstreamUrl: redactedUpstreamUrl,
instanceId, instanceId,
reason: error instanceof Error ? error.message : 'upstream error', reason: error instanceof Error ? error.message : 'upstream error',
}) })
@@ -480,7 +709,7 @@ function tunnelDashboardUpgrade(req, socket, head, upstreamWsUrl, instanceId, co
upstreamSocket.on('close', (hadError) => { upstreamSocket.on('close', (hadError) => {
logBridge('dashboard-tunnel-upstream-close', { logBridge('dashboard-tunnel-upstream-close', {
path: req.url || '/', path: req.url || '/',
upstreamUrl: upstreamWsUrl.toString(), upstreamUrl: redactedUpstreamUrl,
instanceId, instanceId,
hadError, hadError,
upstreamBytes, upstreamBytes,
@@ -492,7 +721,7 @@ function tunnelDashboardUpgrade(req, socket, head, upstreamWsUrl, instanceId, co
socket.on('close', (hadError) => { socket.on('close', (hadError) => {
logBridge('dashboard-tunnel-client-close', { logBridge('dashboard-tunnel-client-close', {
path: req.url || '/', path: req.url || '/',
upstreamUrl: upstreamWsUrl.toString(), upstreamUrl: redactedUpstreamUrl,
instanceId, instanceId,
hadError, hadError,
upstreamBytes, upstreamBytes,
@@ -631,14 +860,7 @@ server.on('upgrade', (req, socket, head) => {
rejectUnauthorizedUpgrade(req, socket, req.url || '/') rejectUnauthorizedUpgrade(req, socket, req.url || '/')
return return
} }
const { upstreamWsUrl, instanceId, controlUiOrigin } = resolveDashboardUpstream(req) handleDashboardProxyUpgrade(req, socket, head, 'dashboard-upgrade-accepted')
logBridge('dashboard-upgrade-accepted', {
path: req.url || '/',
upstreamUrl: upstreamWsUrl.toString(),
instanceId,
remoteAddress: req.socket.remoteAddress || 'unknown',
})
tunnelDashboardUpgrade(req, socket, head, upstreamWsUrl, instanceId, controlUiOrigin)
return return
} }
@@ -653,47 +875,42 @@ server.on('upgrade', (req, socket, head) => {
socket.destroy() socket.destroy()
}) })
dashboardWsProxyServer.on('upgrade', (req, socket, head) => { if (dashboardWsProxyServer) {
if ((req.url || '').startsWith(terminalProxyPath)) { dashboardWsProxyServer.on('upgrade', (req, socket, head) => {
if (!isAuthenticatedUpgrade(req)) { if ((req.url || '').startsWith(terminalProxyPath)) {
rejectUnauthorizedUpgrade(req, socket, req.url || '/') if (!isAuthenticatedUpgrade(req)) {
rejectUnauthorizedUpgrade(req, socket, req.url || '/')
return
}
logBridge('terminal-sidecar-upgrade-accepted', {
path: req.url || '/',
remoteAddress: req.socket.remoteAddress || 'unknown',
})
clientWss.handleUpgrade(req, socket, head, (ws) => {
clientWss.emit('connection', ws, req)
})
return return
} }
logBridge('terminal-sidecar-upgrade-accepted', {
if (
(req.url || '').startsWith(legacyDashboardProxyPrefix) ||
(req.url || '').startsWith(instancesProxyPrefix)
) {
if (!isAuthenticatedUpgrade(req)) {
rejectUnauthorizedUpgrade(req, socket, req.url || '/')
return
}
handleDashboardProxyUpgrade(req, socket, head, 'dashboard-sidecar-upgrade-accepted')
return
}
logBridge('dashboard-sidecar-upgrade-rejected', {
path: req.url || '/', path: req.url || '/',
remoteAddress: req.socket.remoteAddress || 'unknown', remoteAddress: req.socket.remoteAddress || 'unknown',
}) })
clientWss.handleUpgrade(req, socket, head, (ws) => { socket.destroy()
clientWss.emit('connection', ws, req)
})
return
}
if (
(req.url || '').startsWith(legacyDashboardProxyPrefix) ||
(req.url || '').startsWith(instancesProxyPrefix)
) {
if (!isAuthenticatedUpgrade(req)) {
rejectUnauthorizedUpgrade(req, socket, req.url || '/')
return
}
const { upstreamWsUrl, instanceId, controlUiOrigin } = 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, controlUiOrigin)
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}`)
@@ -702,12 +919,16 @@ server.listen(port, hostname, () => {
port, port,
terminalServerUrl: terminalServerUrl.toString(), terminalServerUrl: terminalServerUrl.toString(),
soleOwnerPath: terminalProxyPath, soleOwnerPath: terminalProxyPath,
dashboardWebSocketPath: legacyDashboardProxyPrefix,
dashboardSidecarPort: dashboardWsProxyPort,
}) })
}) })
dashboardWsProxyServer.listen(dashboardWsProxyPort, hostname, () => { if (dashboardWsProxyServer) {
logBridge('dashboard-sidecar-listening', { dashboardWsProxyServer.listen(dashboardWsProxyPort, hostname, () => {
hostname, logBridge('dashboard-sidecar-listening', {
port: dashboardWsProxyPort, hostname,
port: dashboardWsProxyPort,
})
}) })
}) }
+78
View File
@@ -0,0 +1,78 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import vm from 'node:vm'
import ts from 'typescript'
import { createRequire } from 'node:module'
const root = process.cwd()
const sourcePath = path.join(root, 'app/lib/controlAuth.ts')
const source = readFileSync(sourcePath, 'utf8')
const compiled = ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
esModuleInterop: true,
},
}).outputText
function mockRequest(protocol, headers = {}) {
return {
nextUrl: { protocol },
headers: {
get(name) {
return headers[name.toLowerCase()] || null
},
},
}
}
const originalEnv = {
cookieSecure: process.env.OPENSHELL_CONTROL_COOKIE_SECURE,
publicBaseUrl: process.env.PUBLIC_BASE_URL,
}
try {
delete process.env.OPENSHELL_CONTROL_COOKIE_SECURE
delete process.env.PUBLIC_BASE_URL
const module = { exports: {} }
vm.runInNewContext(compiled, {
require: createRequire(sourcePath),
exports: module.exports,
module,
process,
URL,
}, { filename: sourcePath })
assert.equal(module.exports.shouldUseSecureSessionCookie(mockRequest('http:')), false)
assert.equal(module.exports.sessionCookieOptionsForRequest(mockRequest('http:')).secure, false)
assert.equal(module.exports.shouldUseSecureSessionCookie(mockRequest('https:')), true)
assert.equal(
module.exports.shouldUseSecureSessionCookie(mockRequest('http:', { 'x-forwarded-proto': 'https' })),
true,
)
process.env.PUBLIC_BASE_URL = 'https://control.example.test'
assert.equal(module.exports.shouldUseSecureSessionCookie(), true)
process.env.OPENSHELL_CONTROL_COOKIE_SECURE = 'false'
assert.equal(module.exports.shouldUseSecureSessionCookie(mockRequest('https:')), false)
process.env.OPENSHELL_CONTROL_COOKIE_SECURE = 'true'
assert.equal(module.exports.shouldUseSecureSessionCookie(mockRequest('http:')), true)
} finally {
if (originalEnv.cookieSecure === undefined) {
delete process.env.OPENSHELL_CONTROL_COOKIE_SECURE
} else {
process.env.OPENSHELL_CONTROL_COOKIE_SECURE = originalEnv.cookieSecure
}
if (originalEnv.publicBaseUrl === undefined) {
delete process.env.PUBLIC_BASE_URL
} else {
process.env.PUBLIC_BASE_URL = originalEnv.publicBaseUrl
}
}
console.log('control-auth-cookie-check: PASS request-aware secure cookie assertions')
+40
View File
@@ -0,0 +1,40 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
const root = process.cwd()
const helperPath = path.join(root, 'app/lib/nemoclawCli.ts')
const healthRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/health/route.ts')
const restartRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/restart/route.ts')
const [helperSource, healthRouteSource, restartRouteSource] = await Promise.all([
readFile(helperPath, 'utf8'),
readFile(healthRoutePath, 'utf8'),
readFile(restartRoutePath, 'utf8'),
])
assert.match(helperSource, /const NEMOCLAW_RECOVERY_MIN_VERSION = "0\.0\.37"/, 'NemoClaw doctor/recover integration must be gated behind the v0.0.37 CLI surface')
assert.match(helperSource, /NEMOCLAW_BIN, NODE_BIN, commandExists, hostCommandEnv/, 'NemoClaw helper must use the shared host command resolver')
assert.match(helperSource, /parseVersion/, 'NemoClaw helper must parse CLI versions instead of assuming latest behavior')
assert.match(helperSource, /versionGte/, 'NemoClaw helper must compare semantic versions before using newer commands')
assert.match(helperSource, /export async function getNemoClawDoctorReport/, 'NemoClaw helper must expose a doctor JSON probe')
assert.match(helperSource, /\[sandboxName, "doctor", "--json"\]/, 'doctor probe must use the structured NemoClaw doctor JSON command')
assert.match(helperSource, /export async function recoverSandboxWithNemoClaw/, 'NemoClaw helper must expose sandbox recovery')
assert.match(helperSource, /\[sandboxName, "recover"\]/, 'sandbox recovery must use the new NemoClaw recover command')
assert.match(helperSource, /supported: false,[\s\S]*attempted: false/, 'unsupported old NemoClaw versions must skip newer commands without failing')
assert.match(healthRouteSource, /getNemoClawDoctorReport/, 'sandbox health must include NemoClaw doctor integration when available')
assert.match(healthRouteSource, /key: "nemoclaw-doctor"/, 'sandbox health must surface NemoClaw doctor as a health check')
assert.match(healthRouteSource, /Using OpenShell compatibility checks/, 'sandbox health must explicitly fall back for current NemoClaw versions')
assert.match(healthRouteSource, /minimumVersion/, 'sandbox health response must expose the minimum version for doctor support')
assert.match(restartRouteSource, /recoverSandboxWithNemoClaw/, 'sandbox restart must try NemoClaw recover when supported')
assert.ok(
restartRouteSource.indexOf('recoverSandboxWithNemoClaw(sandboxName)') < restartRouteSource.indexOf('runSandboxShell(sandboxName, restartOpenClawGatewayScript()'),
'sandbox restart must try NemoClaw recover before the legacy OpenClaw runtime restart fallback',
)
assert.match(restartRouteSource, /restartMode: "nemoclaw-recover"/, 'restart route must report when the new NemoClaw recovery path succeeds')
assert.match(restartRouteSource, /restartMode: "openclaw-runtime"/, 'restart route must retain the current OpenShell/OpenClaw runtime fallback')
assert.match(restartRouteSource, /NemoClaw recover did not complete[\s\S]*fell back/, 'restart route must report fallback when modern recovery is attempted but fails')
console.log('nemoclaw-compat-check: PASS NemoClaw old/new compatibility assertions')
@@ -13,13 +13,23 @@ assert.match(
) )
assert.match( assert.match(
proxySource, proxySource,
/const sidecarGatewayUrl = protocol \+ '\/\/' \+ sidecarHost \+ proxyPrefix/, /const baseWsUrl = process\.env\.OPENCLAW_DASHBOARD_BASE_WS_URL\?\.trim\(\) \|\| process\.env\.BASE_WS_URL\?\.trim\(\) \|\| ''/,
'dashboard bootstrap should know the dedicated websocket sidecar gateway scope' 'dashboard bootstrap should accept a fully qualified websocket base URL override'
) )
assert.match( assert.match(
proxySource, proxySource,
/const gatewayUrl = \(hashParams\.get\('gatewayUrl'\) \|\| ''\)\.trim\(\) \|\| sidecarGatewayUrl/, /const portGatewayUrl = wsProxyPort \? protocol \+ '\/\/' \+ window\.location\.hostname \+ ':' \+ wsProxyPort \+ proxyPrefix : ''/,
'dashboard bootstrap should honor the tokenized launch gateway URL' 'dashboard bootstrap should keep the dedicated websocket sidecar as an explicit opt-in scope'
)
assert.match(
proxySource,
/const defaultGatewayUrl = configuredGatewayUrl \|\| portGatewayUrl \|\| pageGatewayUrl/,
'dashboard bootstrap should prefer configured, explicit sidecar, then same-origin websocket gateways'
)
assert.match(
proxySource,
/const gatewayUrl = normalizeGatewayUrl\(hashParams\.get\('gatewayUrl'\)\) \|\| defaultGatewayUrl/,
'dashboard bootstrap should honor and normalize the tokenized launch gateway URL'
) )
assert.match( assert.match(
proxySource, proxySource,
@@ -28,8 +38,13 @@ assert.match(
) )
assert.match( assert.match(
proxySource, proxySource,
/const gatewayScopes = uniqueScopes\(\[gatewayUrl, sidecarGatewayUrl, pageGatewayUrl\]\)/, /const gatewayScopes = uniqueScopes\(\[gatewayUrl, configuredGatewayUrl, portGatewayUrl, pageGatewayUrl\]\)/,
'dashboard bootstrap should seed token scopes for launch, sidecar, and page gateways' 'dashboard bootstrap should seed token scopes for launch, configured, sidecar, and page gateways'
)
assert.doesNotMatch(
proxySource,
/\|\| '3001'/,
'dashboard bootstrap must not hardcode the dedicated websocket sidecar port'
) )
assert.match( assert.match(
proxySource, proxySource,
@@ -13,7 +13,20 @@ assert.match(proxySource, /controlUiOrigin: authority\.openclaw\.controlUiOrigin
assert.match(proxySource, /lowerKey !== 'origin'/, 'HTTP proxy must not forward browser Origin to OpenClaw') assert.match(proxySource, /lowerKey !== 'origin'/, 'HTTP proxy must not forward browser Origin to OpenClaw')
assert.match(proxySource, /headers\.set\('origin', controlUiOrigin\)/, 'HTTP proxy must rewrite Origin to the gateway control UI origin') assert.match(proxySource, /headers\.set\('origin', controlUiOrigin\)/, 'HTTP proxy must rewrite Origin to the gateway control UI origin')
assert.match(proxySource, /headers\.set\('referer', `\$\{controlUiOrigin\}\/`\)/, 'HTTP proxy must rewrite Referer to the gateway control UI origin') assert.match(proxySource, /headers\.set\('referer', `\$\{controlUiOrigin\}\/`\)/, 'HTTP proxy must rewrite Referer to the gateway control UI origin')
assert.match(proxySource, /CONTROL_AUTH_COOKIE_NAME = 'openshell_control_session'/, 'HTTP proxy must know the controller auth cookie name')
assert.match(proxySource, /lowerKey === 'cookie' \? filterCookieHeader\(value\) : value/, 'HTTP proxy must strip controller auth cookies before forwarding to OpenClaw')
assert.match(proxySource, /OPENCLAW_DASHBOARD_TOKEN_COOKIE/, 'HTTP proxy must know the dashboard token bridge cookie name')
assert.match(proxySource, /headers\.set\('authorization', `Bearer \$\{dashboardToken\}`\)/, 'HTTP proxy must bridge the dashboard token cookie into upstream Authorization')
assert.match(serverSource, /controlUiOrigin: process\.env\.OPENCLAW_SANDBOX_CONTROL_UI_ORIGIN \|\| 'http:\/\/127\.0\.0\.1:18789'/, 'sandbox instances must preserve the gateway internal control UI origin') assert.match(serverSource, /controlUiOrigin: process\.env\.OPENCLAW_SANDBOX_CONTROL_UI_ORIGIN \|\| 'http:\/\/127\.0\.0\.1:18789'/, 'sandbox instances must preserve the gateway internal control UI origin')
assert.match(serverSource, /openClawDashboardTokenCookieName = 'openclaw_dashboard_token'/, 'WebSocket tunnel must know the dashboard token bridge cookie name')
assert.match(serverSource, /withDashboardTokenQuery\(upstreamWsUrl, dashboardToken\)/, 'WebSocket tunnel must add the dashboard token to the upstream websocket handshake URL')
assert.match(serverSource, /redactSensitiveUrl\(upstreamUrlWithToken\)/, 'WebSocket tunnel logs must redact tokenized upstream URLs')
assert.match(serverSource, /const upstreamUrl = withDashboardTokenQuery\(context\.upstreamWsUrl, dashboardToken\)/, 'WebSocket bridge must add the dashboard token to the upstream websocket URL')
assert.match(serverSource, /const redactedUpstreamUrl = redactSensitiveUrl\(upstreamUrl\)/, 'WebSocket bridge logs must redact tokenized upstream URLs')
assert.match(serverSource, /headers\.push\(`Host: \$\{upstreamWsUrl\.host\}`\)[\s\S]*headers\.push\(`Upgrade:/, 'WebSocket tunnel must normalize handshake headers with Host before upgrade fields for OpenClaw')
assert.match(serverSource, /headers\.push\(`Origin: \$\{controlUiOrigin\}`\)/, 'WebSocket tunnel must rewrite Origin to the gateway control UI origin') assert.match(serverSource, /headers\.push\(`Origin: \$\{controlUiOrigin\}`\)/, 'WebSocket tunnel must rewrite Origin to the gateway control UI origin')
assert.match(serverSource, /rawHeaders\.get\('cookie'\)[\s\S]*filterCookieHeader\(header\.value\)/, 'WebSocket tunnel must strip controller auth cookies before forwarding to OpenClaw')
assert.match(serverSource, /headers\.push\(`Authorization: Bearer \$\{dashboardToken\}`\)/, 'WebSocket tunnel must bridge the dashboard token cookie into upstream Authorization')
assert.match(serverSource, /function handleDashboardProxyUpgrade[\s\S]*dashboardWss\.handleUpgrade/, 'dashboard websocket upgrades must use the authenticated WebSocket bridge')
console.log('openclaw-dashboard-origin-rewrite-check: PASS dashboard proxy origin rewrite assertions') console.log('openclaw-dashboard-origin-rewrite-check: PASS dashboard proxy origin rewrite assertions')
+7 -3
View File
@@ -36,6 +36,8 @@ assert.match(dashboardOpenSource, /authority:\s*\{[\s\S]*sandboxAuthority:/, 'da
assert.match(dashboardOpenSource, /bootstrapUrl: probe\.bootstrapUrl/, 'dashboard open route must surface the resolved bootstrap URL explicitly') assert.match(dashboardOpenSource, /bootstrapUrl: probe\.bootstrapUrl/, 'dashboard open route must surface the resolved bootstrap URL explicitly')
assert.match(dashboardOpenSource, /bootstrapAuthority: probe\.bootstrapAuthority/, 'dashboard open route must surface tokenized bootstrap authority explicitly') assert.match(dashboardOpenSource, /bootstrapAuthority: probe\.bootstrapAuthority/, 'dashboard open route must surface tokenized bootstrap authority explicitly')
assert.match(dashboardOpenSource, /probe\.bootstrapAuthority === 'tokenized-cli'/, 'dashboard open route truth must prefer tokenized bootstrap evidence over raw loopback fetch alone') assert.match(dashboardOpenSource, /probe\.bootstrapAuthority === 'tokenized-cli'/, 'dashboard open route truth must prefer tokenized bootstrap evidence over raw loopback fetch alone')
assert.match(dashboardOpenSource, /process\.env\.OPENCLAW_DASHBOARD_BASE_WS_URL\?\.trim\(\) \|\| process\.env\.BASE_WS_URL\?\.trim\(\) \|\| null/, 'dashboard open route must allow a fully qualified browser websocket base URL')
assert.match(dashboardOpenSource, /const wsProxyPort = process\.env\.OPENCLAW_DASHBOARD_WS_PROXY_PORT\?\.trim\(\) \|\| ''/, 'dashboard open route must not hardcode the dedicated websocket sidecar port')
assert.match(dashboardProxySource, /resolveRuntimeAuthority\(\{[\s\S]*sandboxId: requestUrl\.searchParams\.get\('sandboxId'\)/, 'dashboard proxy must resolve target from shared authority source') assert.match(dashboardProxySource, /resolveRuntimeAuthority\(\{[\s\S]*sandboxId: requestUrl\.searchParams\.get\('sandboxId'\)/, 'dashboard proxy must resolve target from shared authority source')
assert.match(dashboardProxySource, /x-openclaw-dashboard-bootstrap-contract/, 'dashboard proxy must mark the tokenized bootstrap bridge contract in response headers') assert.match(dashboardProxySource, /x-openclaw-dashboard-bootstrap-contract/, 'dashboard proxy must mark the tokenized bootstrap bridge contract in response headers')
@@ -54,9 +56,11 @@ assert.match(openshellHostSource, /const canMintBootstrapFromCli = instance\.id
assert.match(openshellHostSource, /readSandboxOpenClawDashboardToken/, 'sandbox dashboard bootstrap must fall back to the sandbox OpenClaw token when CLI output is bare') assert.match(openshellHostSource, /readSandboxOpenClawDashboardToken/, 'sandbox dashboard bootstrap must fall back to the sandbox OpenClaw token when CLI output is bare')
assert.match(openshellHostSource, /openclaw dashboard', 15000\)\.catch/, 'sandbox dashboard bootstrap should let OpenClaw initialize before reading the fallback token') assert.match(openshellHostSource, /openclaw dashboard', 15000\)\.catch/, 'sandbox dashboard bootstrap should let OpenClaw initialize before reading the fallback token')
assert.match(openshellHostSource, /withDashboardToken\(tokenizedBootstrapUrl, token\)/, 'sandbox dashboard bootstrap should synthesize a tokenized launch URL from the fallback token') assert.match(openshellHostSource, /withDashboardToken\(tokenizedBootstrapUrl, token\)/, 'sandbox dashboard bootstrap should synthesize a tokenized launch URL from the fallback token')
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_ENV=development node server\.mjs"/, 'development script must run through the custom server so websocket proxy bridges are active')
assert.match(serverSource, /const dashboardWsProxyServer = http\.createServer/, 'custom server must provision a dedicated dashboard websocket sidecar') assert.match(packageJsonSource, /"start": "NODE_ENV=production node server\.mjs"/, 'production start must run the custom server without Next dev-mode heap growth')
assert.match(serverSource, /dashboard-sidecar-listening/, 'custom server must expose the dashboard websocket sidecar listener') assert.match(serverSource, /const dashboardWsProxyPort = parseOptionalPort\(process\.env\.OPENCLAW_DASHBOARD_WS_PROXY_PORT/, 'custom server must make the dedicated dashboard websocket sidecar opt-in')
assert.match(serverSource, /const dashboardWsProxyServer = dashboardWsProxyPort\s*\?\s*http\.createServer/, 'custom server must only provision the sidecar when explicitly configured')
assert.match(serverSource, /dashboard-sidecar-listening/, 'custom server must still expose the optional 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')
+8 -1
View File
@@ -139,6 +139,9 @@ assert.match(inferenceRouteSource, /\["provider", "delete", name\]/, 'inference
assert.match(inferenceRouteSource, /\["inference", "set", "--provider", name, "--model", model\]/, 'inference route must set the active OpenShell inference route') assert.match(inferenceRouteSource, /\["inference", "set", "--provider", name, "--model", model\]/, 'inference route must set the active OpenShell inference route')
assert.match(inferenceRouteSource, /isVllmEndpoint\(name, baseUrl\)/, 'inference route must skip verification for vLLM-compatible endpoints') assert.match(inferenceRouteSource, /isVllmEndpoint\(name, baseUrl\)/, 'inference route must skip verification for vLLM-compatible endpoints')
assert.match(inferenceRouteSource, /normalizeProviderType\(requestedType, name, baseUrl\)/, 'inference route must force vLLM endpoints through the OpenAI-compatible provider type') assert.match(inferenceRouteSource, /normalizeProviderType\(requestedType, name, baseUrl\)/, 'inference route must force vLLM endpoints through the OpenAI-compatible provider type')
assert.match(inferenceRouteSource, /isOllamaEndpoint\(name, baseUrl\)/, 'inference route must detect local Ollama endpoints')
assert.match(inferenceRouteSource, /isVllmEndpoint\(name, baseUrl\) \|\| isOllamaEndpoint\(name, baseUrl\)/, 'inference route must force local Ollama endpoints through the OpenAI-compatible provider type')
assert.match(inferenceRouteSource, /body\?\.noVerify !== false \|\| isVllmEndpoint\(name, baseUrl\) \|\| isOllamaEndpoint\(name, baseUrl\)/, 'inference route must skip verification for local Ollama endpoints')
assert.match(inferenceRouteSource, /normalizeInferenceBaseUrlForGateway\(\s*baseUrl,/, 'inference route must normalize endpoint URLs for the OpenShell gateway pod') assert.match(inferenceRouteSource, /normalizeInferenceBaseUrlForGateway\(\s*baseUrl,/, 'inference route must normalize endpoint URLs for the OpenShell gateway pod')
assert.match(inferenceRouteSource, /OPENAI_BASE_URL=\$\{normalizedBaseUrl\}/, 'inference route must pass the normalized endpoint URL as provider config') assert.match(inferenceRouteSource, /OPENAI_BASE_URL=\$\{normalizedBaseUrl\}/, 'inference route must pass the normalized endpoint URL as provider config')
assert.match(inferenceEndpointUrlSource, /host\.docker\.internal/, 'endpoint normalization must rewrite host-local URLs to a gateway-reachable host alias') assert.match(inferenceEndpointUrlSource, /host\.docker\.internal/, 'endpoint normalization must rewrite host-local URLs to a gateway-reachable host alias')
@@ -150,7 +153,11 @@ assert.match(inferencePanelSource, /host\.docker\.internal:8000\/v1/, 'vLLM pres
assert.doesNotMatch(inferencePanelSource, /nvidia\/NVIDIA-Nemotron-3-Super-120B-A12B-NVFP4/, 'settings UI must not default rebuilt inference routes to the NVIDIA Nemotron model') assert.doesNotMatch(inferencePanelSource, /nvidia\/NVIDIA-Nemotron-3-Super-120B-A12B-NVFP4/, 'settings UI must not default rebuilt inference routes to the NVIDIA Nemotron model')
assert.match(inferencePanelSource, /method: "DELETE"/, 'settings UI must expose provider deletion') assert.match(inferencePanelSource, /method: "DELETE"/, 'settings UI must expose provider deletion')
assert.match(inferencePanelSource, /\/api\/ollama\/models/, 'settings UI must poll local Ollama models') assert.match(inferencePanelSource, /\/api\/ollama\/models/, 'settings UI must poll local Ollama models')
assert.match(inferencePanelSource, /window\.setInterval\(\(\) => loadOllamaModels\(\{ silent: true \}\), 10000\)/, 'settings UI must autopoll Ollama while selected') assert.match(inferencePanelSource, /window\.setInterval\(\(\) => loadOllamaModels\(\{ silent: true \}\), 10000\)/, 'settings UI must autopoll Ollama while the endpoint panel is open')
assert.match(inferencePanelSource, /function applyOllamaModelPreset\(modelName: string\)/, 'settings UI must provide a click preset for local Ollama models')
assert.match(inferencePanelSource, /setName\(OLLAMA_PROVIDER_NAME\)[\s\S]*setType\("openai"\)[\s\S]*setModel\(modelName\)[\s\S]*setBaseUrl\(OLLAMA_BASE_URL\)/, 'Ollama model preset must fill provider name, provider type, model, and endpoint URL')
assert.match(inferencePanelSource, /onClick=\{\(\) => applyOllamaModelPreset\(item\.name\)\}/, 'clicking an Ollama model must load the endpoint preset')
assert.match(inferencePanelSource, /const OLLAMA_BASE_URL = "http:\/\/host\.docker\.internal:11434\/v1"/, 'Ollama preset must use the host-reachable OpenAI-compatible endpoint')
assert.match(ollamaModelsRouteSource, /\/api\/tags/, 'Ollama models route must query the Ollama tags API') assert.match(ollamaModelsRouteSource, /\/api\/tags/, 'Ollama models route must query the Ollama tags API')
assert.match(ollamaModelsRouteSource, /OLLAMA_BASE_URL/, 'Ollama models route must support a configurable Ollama base URL') assert.match(ollamaModelsRouteSource, /OLLAMA_BASE_URL/, 'Ollama models route must support a configurable Ollama base URL')
assert.match(sandboxInferenceRouteSource, /parseRoutes/, 'sandbox inference route must accept multiple provider/model routes') assert.match(sandboxInferenceRouteSource, /parseRoutes/, 'sandbox inference route must accept multiple provider/model routes')