From 372326b225657beb6d27bf823e84b043ea437074 Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 28 Apr 2026 21:44:53 +0000 Subject: [PATCH] Add gateway trust repair action --- app/api/openshell/gateway/repair/route.ts | 68 +++++++++++++++++++++++ app/page.tsx | 58 +++++++++++++++++++ tests/sandbox-lifecycle-check.mjs | 9 +++ 3 files changed, 135 insertions(+) create mode 100644 app/api/openshell/gateway/repair/route.ts diff --git a/app/api/openshell/gateway/repair/route.ts b/app/api/openshell/gateway/repair/route.ts new file mode 100644 index 0000000..e304fcb --- /dev/null +++ b/app/api/openshell/gateway/repair/route.ts @@ -0,0 +1,68 @@ +import { NextResponse } from "next/server" +import { execFile } from "node:child_process" +import { cp, mkdir, readFile } from "node:fs/promises" +import path from "node:path" +import { promisify } from "node:util" +import { OPENSHELL_BIN, OPENSHELL_XDG_CONFIG_HOME, hostCommandEnv } from "@/app/lib/hostCommands" + +const execFileAsync = promisify(execFile) +const OPENSHELL_GATEWAY = process.env.OPENSHELL_GATEWAY || "nemoclaw" + +function sanitizeGatewayName(value: string) { + const name = value.trim() + if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$/.test(name)) throw new Error("invalid gateway name") + return name +} + +async function activeGatewayName() { + try { + const raw = await readFile(path.join(OPENSHELL_XDG_CONFIG_HOME, "openshell/active_gateway"), "utf8") + return sanitizeGatewayName(raw) + } catch { + return sanitizeGatewayName(OPENSHELL_GATEWAY) + } +} + +async function runOpenShell(args: string[], timeout = 90000) { + const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, { + env: hostCommandEnv({ + OPENSHELL_GATEWAY, + }), + timeout, + maxBuffer: 10 * 1024 * 1024, + }) + return { stdout: String(stdout).trim(), stderr: String(stderr).trim() } +} + +async function backupOpenShellConfig() { + const source = path.join(OPENSHELL_XDG_CONFIG_HOME, "openshell") + const backupRoot = path.join(OPENSHELL_XDG_CONFIG_HOME, "openshell-dashboard-backups") + const backupPath = path.join(backupRoot, `openshell-${Date.now().toString(36)}`) + await mkdir(backupRoot, { recursive: true, mode: 0o700 }) + await cp(source, backupPath, { recursive: true, force: false }) + return backupPath +} + +export async function POST(request: Request) { + try { + const body = await request.json().catch(() => ({})) + const gateway = sanitizeGatewayName(typeof body?.gateway === "string" && body.gateway.trim() ? body.gateway : await activeGatewayName()) + const backupPath = await backupOpenShellConfig() + const start = await runOpenShell(["gateway", "start", "--name", gateway]) + const select = await runOpenShell(["gateway", "select", gateway], 30000) + const verify = await runOpenShell(["sandbox", "list"], 30000) + + return NextResponse.json({ + ok: true, + gateway, + backupPath, + warning: "OpenShell gateway trust repair backed up local OpenShell config, restarted the selected gateway, reselected it, and verified sandbox inventory. Use this only when gateway TLS trust is out of sync.", + start, + select, + verify, + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to repair OpenShell gateway trust" + return NextResponse.json({ ok: false, error: message }, { status: /invalid|required/.test(message) ? 400 : 500 }) + } +} diff --git a/app/page.tsx b/app/page.tsx index 03508e0..aa5c3e7 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -26,6 +26,7 @@ export default function Dashboard() { const [showDeleteConfirm, setShowDeleteConfirm] = useState(false) const [lifecycleMessage, setLifecycleMessage] = useState(null) const [deleteInProgress, setDeleteInProgress] = useState(false) + const [gatewayRepairing, setGatewayRepairing] = useState(false) const inventoryEnabled = activeView === 'sandboxes' || activeView === 'wizards' || activeView === 'help' || activeView === 'mcp' || isCreateMode || isDestroyMode const { sandboxes, nemoclaw, loading, error, refresh } = useSandboxInventory({ enabled: inventoryEnabled, @@ -94,6 +95,31 @@ export default function Dashboard() { const sleep = (ms: number) => new Promise((resolve) => window.setTimeout(resolve, ms)) + const gatewayTrustError = Boolean(error && /BadSignature|invalid peer certificate|transport error|certificate signature/i.test(error)) + + const repairGatewayTrust = async () => { + if (gatewayRepairing) return + try { + setGatewayRepairing(true) + setLifecycleMessage( + "Repairing OpenShell gateway trust. This backs up local OpenShell config, restarts the selected gateway, reselects it, and verifies sandbox inventory. It does not destroy sandboxes." + ) + const response = await fetch('/api/openshell/gateway/repair', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ reason: 'inventory BadSignature recovery' }), + }) + const data = await response.json() + if (!response.ok) throw new Error(data.error || 'Failed to repair OpenShell gateway trust') + setLifecycleMessage(`${data.warning || 'OpenShell gateway trust repaired.'}\nGateway: ${data.gateway}\nBackup: ${data.backupPath}`) + await refresh({ force: true }) + } catch (err) { + setLifecycleMessage(err instanceof Error ? err.message : 'Failed to repair OpenShell gateway trust') + } finally { + setGatewayRepairing(false) + } + } + const refreshUntilSandboxVisible = async (sandboxRef: string) => { for (let attempt = 0; attempt < 8; attempt += 1) { const latest = await refresh({ force: true }) @@ -316,6 +342,22 @@ export default function Dashboard() {

Inventory Unavailable

{error}

+ {gatewayTrustError && ( +
+

Gateway Trust Mismatch

+

+ OpenShell reached the gateway, but certificate verification failed. This usually means the gateway regenerated mTLS material while this controller still has stale trust files. +

+ +
+ )}
) : (

Inventory Unavailable

{error}

+ {gatewayTrustError && ( +
+

Gateway Trust Mismatch

+

+ OpenShell reached the gateway, but certificate verification failed. This usually means the gateway regenerated mTLS material while this controller still has stale trust files. +

+ +
+ )} ) : sandboxes.length === 0 ? (
diff --git a/tests/sandbox-lifecycle-check.mjs b/tests/sandbox-lifecycle-check.mjs index a9a9078..298b270 100644 --- a/tests/sandbox-lifecycle-check.mjs +++ b/tests/sandbox-lifecycle-check.mjs @@ -14,6 +14,7 @@ const sandboxInferenceApplyRoutePath = path.join(root, 'app/api/sandbox/[sandbox const sandboxInferenceApplyLibPath = path.join(root, 'app/lib/sandboxInferenceApply.ts') const sandboxInferenceStorePath = path.join(root, 'app/lib/sandboxInferenceStore.ts') const sandboxRestartRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/restart/route.ts') +const gatewayRepairRoutePath = path.join(root, 'app/api/openshell/gateway/repair/route.ts') const hookPath = path.join(root, 'app/hooks/useSandboxInventory.ts') const pagePath = path.join(root, 'app/page.tsx') const configPanelPath = path.join(root, 'app/components/ConfigurationPanel.tsx') @@ -33,6 +34,7 @@ const sandboxInferenceApplyRouteSource = await readFile(sandboxInferenceApplyRou const sandboxInferenceApplyLibSource = await readFile(sandboxInferenceApplyLibPath, 'utf8') const sandboxInferenceStoreSource = await readFile(sandboxInferenceStorePath, 'utf8') const sandboxRestartRouteSource = await readFile(sandboxRestartRoutePath, 'utf8') +const gatewayRepairRouteSource = await readFile(gatewayRepairRoutePath, 'utf8') const hookSource = await readFile(hookPath, 'utf8') const pageSource = await readFile(pagePath, 'utf8') const configPanelSource = await readFile(configPanelPath, 'utf8') @@ -110,6 +112,13 @@ assert.match(sandboxRestartRouteSource, /restartMode: "openclaw-runtime"/, 'rest assert.match(sandboxRestartRouteSource, /waitForSandboxReady\(sandboxName, 15000, 1000\)/, 'restart route must verify OpenShell reports the sandbox ready before runtime restart') assert.match(sandboxListSource, /Restart OpenClaw Runtime/, 'sandbox details must expose a scoped runtime restart button') assert.match(sandboxListSource, /\/api\/sandbox\/\$\{encodeURIComponent\(selectedSandbox\.id\)\}\/restart/, 'restart button must call the sandbox restart endpoint') +assert.match(gatewayRepairRouteSource, /gateway", "start", "--name", gateway/, 'gateway repair route must restart the selected OpenShell gateway') +assert.match(gatewayRepairRouteSource, /backupOpenShellConfig/, 'gateway repair route must back up OpenShell config before repair') +assert.match(gatewayRepairRouteSource, /\["sandbox", "list"\]/, 'gateway repair route must verify sandbox inventory after repair') +assert.match(pageSource, /BadSignature\|invalid peer certificate\|transport error\|certificate signature/, 'dashboard must detect gateway certificate trust failures') +assert.match(pageSource, /Repair Gateway Trust/, 'inventory error UI must expose a guarded gateway trust repair button') +assert.match(pageSource, /api\/openshell\/gateway\/repair/, 'gateway trust repair button must call the repair endpoint') +assert.match(pageSource, /It does not destroy sandboxes/, 'gateway trust repair warning must clarify sandboxes are not destroyed') assert.doesNotMatch(sandboxListSource, /setInterval\(loadPermissionFeeds/, 'sandbox list must not poll every sandbox permission feed') assert.match(sandboxListSource, /loadPermissionFeed\(selectedSandbox\)/, 'policy drawer must load the selected sandbox permission feed on demand') assert.match(sandboxListSource, /