From fd0959d994e07f76ce30d551728c785bad0b1c16 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 27 Apr 2026 21:33:05 +0000 Subject: [PATCH] Harden MCP broker sandbox handoff --- README.md | 6 +- app/api/inference/route.ts | 20 +- .../[sandboxId]/files/download/route.ts | 6 +- .../sandbox/[sandboxId]/files/upload/route.ts | 32 +++- app/api/sandbox/[sandboxId]/mcp/route.ts | 32 +++- app/components/McpConfigurationPanel.tsx | 4 +- app/components/SandboxFilesPanel.tsx | 58 ++++-- app/components/SandboxList.tsx | 173 ++++++++++++------ app/lib/mcpBrokerStore.ts | 14 ++ app/lib/mcpBrokerUrl.ts | 82 +++++++++ app/lib/mcpServerStore.ts | 19 ++ app/lib/sandboxFiles.ts | 65 +++++++ app/lib/sandboxMcpManifest.ts | 39 +++- app/lib/sandboxPermissions.ts | 88 +++++++++ install.sh | 53 +++++- middleware.ts | 11 ++ tests/mcp-configuration-page-check.mjs | 21 ++- tests/portable-install-check.mjs | 12 ++ 18 files changed, 634 insertions(+), 101 deletions(-) create mode 100644 app/lib/mcpBrokerUrl.ts diff --git a/README.md b/README.md index b2e27d9..03238af 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ openshell --version Optional, but useful for stdio MCP servers installed through the broker: ```bash +npx --version uvx --version ``` @@ -81,6 +82,7 @@ From the repository root: The installer: - checks Node, npm, Docker, OpenShell CLI availability, sandbox inventory reachability, and default port occupancy; +- installs or verifies the MCP package runners used by bundled stdio servers: `npx` and `uvx`; - installs npm dependencies with `npm ci` when `package-lock.json` exists; - runs a non-blocking `npm audit` summary; - creates `.env.local` if needed; @@ -225,9 +227,9 @@ MCP_BROKER_REQUEST_TIMEOUT_MS=45000 OPENSHELL_CONTROL_MCP_BROKER_URL=http://localhost:3000/api/mcp/broker ``` -`OPENSHELL_CONTROL_MCP_BROKER_URL` is optional. Set it when sandboxes need a routable URL that differs from the dashboard request origin. +`OPENSHELL_CONTROL_MCP_BROKER_URL` is optional. Set it only when you need to override discovery. By default the dashboard discovers the active OpenShell Docker gateway and the selected sandbox's proxy environment before writing `/sandbox/openshell_control_mcp.md`. -Stdio MCP servers run on the control host. Make sure their launch commands, such as `uvx`, `npx`, `node`, or `python`, are available to the dashboard process. +Stdio MCP servers run on the control host. The installer verifies `npx` and installs `uvx` into `~/.local/bin` when it is missing. Custom MCP server launch commands, such as `node` or `python`, must also be available to the dashboard process. ## File Transfer diff --git a/app/api/inference/route.ts b/app/api/inference/route.ts index d29e9f9..79f7704 100644 --- a/app/api/inference/route.ts +++ b/app/api/inference/route.ts @@ -19,10 +19,11 @@ function stripAnsi(value: string) { return value.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "") } -async function runOpenShell(args: string[]) { +async function runOpenShell(args: string[], extraEnv: Record = {}) { const { stdout, stderr } = await execFileAsync(OPENSHELL_BIN, args, { env: { ...process.env, + ...extraEnv, PATH: HOST_PATH, OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw", NO_COLOR: "1", @@ -105,8 +106,12 @@ function optionalString(value: unknown) { return typeof value === "string" ? value.trim() : "" } -function providerCredentialArg(credentialKey: string, apiKey: string) { - return apiKey ? `${credentialKey}=${apiKey}` : credentialKey +function redactSecretOutput(value: string, secrets: string[] = []) { + let redacted = value + for (const secret of secrets) { + if (secret) redacted = redacted.split(secret).join("[redacted]") + } + return redacted.replace(/([A-Z_][A-Z0-9_]*=)([^\s]+)/g, "$1[redacted]") } export async function GET() { @@ -151,11 +156,12 @@ export async function POST(request: Request) { ? ["provider", "update", name] : ["provider", "create", "--name", name, "--type", type] + const providerEnv = apiKey ? { [credentialKey]: apiKey } : {} if (!existingNames.includes(name) && !apiKey) providerArgs.push("--from-existing") - if (apiKey) providerArgs.push("--credential", providerCredentialArg(credentialKey, apiKey)) + if (apiKey) providerArgs.push("--credential", credentialKey) if (baseUrl) providerArgs.push("--config", `OPENAI_BASE_URL=${baseUrl}`) - const providerResult = await runOpenShell(providerArgs) + const providerResult = await runOpenShell(providerArgs, providerEnv) let inferenceResult = null if (makeActive) { const routeArgs = ["inference", "set", "--provider", name, "--model", model] @@ -172,8 +178,8 @@ export async function POST(request: Request) { active: makeActive, gateway: parseRoute(refreshed.stdout, "Gateway inference"), system: parseRoute(refreshed.stdout, "System inference"), - stdout: [providerResult.stdout, inferenceResult?.stdout].filter(Boolean).join("\n\n"), - stderr: [providerResult.stderr, inferenceResult?.stderr].filter(Boolean).join("\n\n"), + stdout: redactSecretOutput([providerResult.stdout, inferenceResult?.stdout].filter(Boolean).join("\n\n"), [apiKey]), + stderr: redactSecretOutput([providerResult.stderr, inferenceResult?.stderr].filter(Boolean).join("\n\n"), [apiKey]), }) } catch (error) { const message = error instanceof Error ? error.message : "Failed to save inference endpoint" diff --git a/app/api/sandbox/[sandboxId]/files/download/route.ts b/app/api/sandbox/[sandboxId]/files/download/route.ts index 9dee173..e518d45 100644 --- a/app/api/sandbox/[sandboxId]/files/download/route.ts +++ b/app/api/sandbox/[sandboxId]/files/download/route.ts @@ -1,5 +1,5 @@ import { NextResponse } from "next/server" -import { downloadSandboxFile } from "@/app/lib/sandboxFiles" +import { downloadSandboxPath } from "@/app/lib/sandboxFiles" function contentDisposition(fileName: string) { const fallback = fileName.replace(/[^\w.-]/g, "_") || "download.bin" @@ -14,7 +14,7 @@ export async function GET( const { sandboxId } = await params const requestUrl = new URL(request.url) const sourcePath = requestUrl.searchParams.get("path") || "" - const downloaded = await downloadSandboxFile(sandboxId, sourcePath) + const downloaded = await downloadSandboxPath(sandboxId, sourcePath) return new NextResponse(new Uint8Array(downloaded.bytes), { status: 200, @@ -22,7 +22,7 @@ export async function GET( "cache-control": "no-store", "content-disposition": contentDisposition(downloaded.fileName), "content-length": String(downloaded.bytes.byteLength), - "content-type": "application/octet-stream", + "content-type": downloaded.archive ? "application/gzip" : "application/octet-stream", "x-sandbox-name": downloaded.sandboxName, "x-sandbox-path": downloaded.path, }, diff --git a/app/api/sandbox/[sandboxId]/files/upload/route.ts b/app/api/sandbox/[sandboxId]/files/upload/route.ts index 041b56b..bd81b53 100644 --- a/app/api/sandbox/[sandboxId]/files/upload/route.ts +++ b/app/api/sandbox/[sandboxId]/files/upload/route.ts @@ -1,5 +1,5 @@ import { NextResponse } from "next/server" -import { assertRequestContentLength, uploadSandboxFile } from "@/app/lib/sandboxFiles" +import { assertRequestContentLength, uploadSandboxFile, uploadSandboxFiles } from "@/app/lib/sandboxFiles" export async function POST( request: Request, @@ -10,13 +10,37 @@ export async function POST( assertRequestContentLength(request) const form = await request.formData() const file = form.get("file") + const files = form.getAll("files") const rawPath = form.get("path") - if (!(file instanceof File)) throw new Error("file is required") + const rawRelativePaths = form.get("relativePaths") const destinationPath = typeof rawPath === "string" && rawPath.trim() ? rawPath.trim() - : `/sandbox/${file.name}` + : "/sandbox/" + + if (files.length > 0) { + const relativePaths = typeof rawRelativePaths === "string" ? JSON.parse(rawRelativePaths) : [] + if (!Array.isArray(relativePaths)) throw new Error("relative paths are required for directory upload") + const payloads = await Promise.all(files.map(async (item, index) => { + if (!(item instanceof File)) throw new Error("files must contain only file uploads") + return { + fileName: item.name, + relativePath: typeof relativePaths[index] === "string" && relativePaths[index] ? relativePaths[index] : item.name, + payload: Buffer.from(await item.arrayBuffer()), + } + })) + const uploaded = await uploadSandboxFiles(sandboxId, destinationPath, payloads) + + return NextResponse.json({ + ok: true, + uploaded, + note: `Uploaded ${uploaded.files.length} file${uploaded.files.length === 1 ? "" : "s"} to ${destinationPath}.`, + }) + } + + if (!(file instanceof File)) throw new Error("file is required") + const targetPath = destinationPath.endsWith("/") ? destinationPath : rawPath ? destinationPath : `/sandbox/${file.name}` const payload = Buffer.from(await file.arrayBuffer()) - const uploaded = await uploadSandboxFile(sandboxId, destinationPath, file.name, payload) + const uploaded = await uploadSandboxFile(sandboxId, targetPath, file.name, payload) return NextResponse.json({ ok: true, diff --git a/app/api/sandbox/[sandboxId]/mcp/route.ts b/app/api/sandbox/[sandboxId]/mcp/route.ts index ad6e261..b01bce7 100644 --- a/app/api/sandbox/[sandboxId]/mcp/route.ts +++ b/app/api/sandbox/[sandboxId]/mcp/route.ts @@ -1,16 +1,13 @@ import { NextResponse } from "next/server" -import { syncSandboxMcpManifest } from "@/app/lib/sandboxMcpManifest" +import { brokerBaseUrlForSandbox } from "@/app/lib/mcpBrokerUrl" +import { revokeSandboxMcpManifest, syncSandboxMcpManifest } from "@/app/lib/sandboxMcpManifest" +import { revokeBrokerNetworkAccess, syncBrokerNetworkAccess } from "@/app/lib/sandboxPermissions" function readSandboxName(request: Request) { const requestUrl = new URL(request.url) return requestUrl.searchParams.get("sandboxName") || null } -function brokerBaseUrl(request: Request) { - const origin = new URL(request.url).origin - return process.env.OPENSHELL_CONTROL_MCP_BROKER_URL || `${origin}/api/mcp/broker` -} - export async function GET( request: Request, { params }: { params: Promise<{ sandboxId: string }> }, @@ -18,7 +15,7 @@ export async function GET( try { const { sandboxId } = await params const sandboxName = readSandboxName(request) - const brokerUrl = brokerBaseUrl(request) + const brokerUrl = await brokerBaseUrlForSandbox(request, { id: sandboxId, name: sandboxName }) return NextResponse.json({ ok: true, sandboxId, @@ -50,14 +47,33 @@ export async function POST( const { sandboxId } = await params const body = await request.json().catch(() => ({})) const sandboxName = typeof body?.sandboxName === "string" ? body.sandboxName : readSandboxName(request) + const action = typeof body?.action === "string" ? body.action : "sync" + const brokerUrl = await brokerBaseUrlForSandbox(request, { id: sandboxId, name: sandboxName }) + + if (action === "revoke") { + const [synced, network] = await Promise.all([ + revokeSandboxMcpManifest({ id: sandboxId, name: sandboxName }), + revokeBrokerNetworkAccess(sandboxId, brokerUrl), + ]) + return NextResponse.json({ + ok: true, + sandboxId, + synced, + network, + note: `Revoked MCP broker config for ${synced.sandboxName}.`, + }) + } + const synced = await syncSandboxMcpManifest( { id: sandboxId, name: sandboxName }, - { brokerBaseUrl: brokerBaseUrl(request) }, + { brokerBaseUrl: brokerUrl }, ) + const network = await syncBrokerNetworkAccess(sandboxId, brokerUrl) return NextResponse.json({ ok: true, sandboxId, synced, + network, note: `Issued MCP broker config at ${synced.path}.`, }) } catch (error) { diff --git a/app/components/McpConfigurationPanel.tsx b/app/components/McpConfigurationPanel.tsx index 4752be3..308a75a 100644 --- a/app/components/McpConfigurationPanel.tsx +++ b/app/components/McpConfigurationPanel.tsx @@ -361,10 +361,10 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
- {pagedRegistryResults.map((entry) => { + {pagedRegistryResults.map((entry, index) => { const installed = installedIds.has(entry.id) return ( -
+

{entry.name}

diff --git a/app/components/SandboxFilesPanel.tsx b/app/components/SandboxFilesPanel.tsx index 33d6d92..a13a5b6 100644 --- a/app/components/SandboxFilesPanel.tsx +++ b/app/components/SandboxFilesPanel.tsx @@ -47,6 +47,8 @@ export default function SandboxFilesPanel({ showHeader?: boolean }) { const [selectedFile, setSelectedFile] = useState(null) + const [selectedDirectoryFiles, setSelectedDirectoryFiles] = useState([]) + const [uploadMode, setUploadMode] = useState<"file" | "directory">("file") const [uploadPath, setUploadPath] = useState("/sandbox/") const [downloadPath, setDownloadPath] = useState("/sandbox/") const [busy, setBusy] = useState<"upload" | "download" | null>(null) @@ -59,6 +61,7 @@ export default function SandboxFilesPanel({ if (!selectedFile) return uploadPath return uploadPath.endsWith("/") ? `${uploadPath}${selectedFile.name}` : uploadPath }, [selectedFile, uploadPath]) + const uploadCount = uploadMode === "directory" ? selectedDirectoryFiles.length : selectedFile ? 1 : 0 const sortedEntries = useMemo(() => { return [...(listing?.entries || [])].sort((left, right) => { @@ -99,21 +102,32 @@ export default function SandboxFilesPanel({ }, [sandbox.id]) async function uploadFile() { - if (!selectedFile || busy) return + if (uploadCount === 0 || busy) return try { setBusy("upload") setMessage("") const form = new FormData() - form.set("file", selectedFile) form.set("path", uploadPath) + if (uploadMode === "directory") { + form.set("relativePaths", JSON.stringify(selectedDirectoryFiles.map((file) => file.webkitRelativePath || file.name))) + for (const file of selectedDirectoryFiles) { + form.append("files", file, file.name) + } + } else if (selectedFile) { + form.set("file", selectedFile) + } const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/files/upload`, { method: "POST", body: form, }) const data = await response.json() if (!response.ok) throw new Error(data.error || "Failed to upload file") - setMessage(data.note || `Uploaded to ${data.uploaded?.path || suggestedUploadPath}.`) - setDownloadPath(data.uploaded?.path || suggestedUploadPath) + setMessage(data.note || "Upload complete.") + if (uploadMode === "directory") { + setDownloadPath(uploadPath) + } else { + setDownloadPath(data.uploaded?.path || suggestedUploadPath) + } await loadFileList(listPath) } catch (error) { setMessage(error instanceof Error ? error.message : "Failed to upload file") @@ -188,7 +202,22 @@ export default function SandboxFilesPanel({
setSelectedFile(event.target.files?.[0] || null)} + onChange={(event) => { + setUploadMode("file") + setSelectedFile(event.target.files?.[0] || null) + setSelectedDirectoryFiles([]) + }} + className="block w-full text-xs text-[var(--foreground-dim)] file:mr-3 file:rounded-sm file:border file:border-[var(--border-subtle)] file:bg-[var(--background)] file:px-3 file:py-2 file:text-xs file:font-mono file:uppercase file:text-[var(--foreground)]" + /> + )} + onChange={(event) => { + setUploadMode("directory") + setSelectedDirectoryFiles(Array.from(event.target.files || [])) + setSelectedFile(null) + }} className="block w-full text-xs text-[var(--foreground-dim)] file:mr-3 file:rounded-sm file:border file:border-[var(--border-subtle)] file:bg-[var(--background)] file:px-3 file:py-2 file:text-xs file:font-mono file:uppercase file:text-[var(--foreground)]" />
@@ -202,20 +231,25 @@ export default function SandboxFilesPanel({ {selectedFile && (

Target: {suggestedUploadPath}

)} + {uploadMode === "directory" && selectedDirectoryFiles.length > 0 && ( +

+ Directory upload: {selectedDirectoryFiles.length} file{selectedDirectoryFiles.length === 1 ? "" : "s"} into {uploadPath} +

+ )}
Download
-

Browse sandbox files or enter a regular file path under /sandbox or /tmp.

+

Browse sandbox files or enter a file or directory path under /sandbox or /tmp.

{ setDownloadPath(entry.path) - if (entry.type !== "directory") { - downloadFile(entry.path) - } + downloadFile(entry.path) }} - disabled={entry.type === "directory" || busy !== null} + disabled={(entry.type !== "file" && entry.type !== "directory") || busy !== null} className="action-button px-2 py-1 text-right disabled:opacity-30" > Get @@ -315,7 +347,7 @@ export default function SandboxFilesPanel({ disabled={!downloadPath.trim() || busy !== null} className="action-button px-4 py-2" > - {busy === "download" ? "Downloading..." : "Download File"} + {busy === "download" ? "Downloading..." : "Download Path"}
diff --git a/app/components/SandboxList.tsx b/app/components/SandboxList.tsx index b56a26a..a769824 100644 --- a/app/components/SandboxList.tsx +++ b/app/components/SandboxList.tsx @@ -274,20 +274,25 @@ export default function SandboxList({ } } - const syncMcpManifest = async (sandbox: SandboxInventoryItem) => { + const syncMcpManifest = async (sandbox: SandboxInventoryItem, action: 'sync' | 'revoke' = 'sync') => { try { setMcpSyncing(true) - setMcpMessage(`Issuing MCP broker config for ${sandbox.name}...`) + setMcpMessage(action === 'revoke' ? `Revoking MCP broker config for ${sandbox.name}...` : `Issuing MCP broker config for ${sandbox.name}...`) const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/mcp`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ sandboxName: sandbox.name }), + body: JSON.stringify({ sandboxName: sandbox.name, action }), }) const data = await response.json() - if (!response.ok) throw new Error(data.error || 'Failed to issue MCP broker config') - setMcpMessage(data.note || 'MCP broker config issued.') + if (!response.ok) throw new Error(data.error || 'Failed to update MCP broker config') + const networkNote = data.network?.approved?.length + ? ` Approved ${data.network.approved.length} broker network rule${data.network.approved.length === 1 ? '' : 's'}.` + : data.network?.rejected?.length + ? ` Removed ${data.network.rejected.length} broker network rule${data.network.rejected.length === 1 ? '' : 's'}.` + : '' + setMcpMessage(`${data.note || 'MCP broker config updated.'}${networkNote}`) } catch (error) { - setMcpMessage(error instanceof Error ? error.message : 'Failed to issue MCP broker config') + setMcpMessage(error instanceof Error ? error.message : 'Failed to update MCP broker config') } finally { setMcpSyncing(false) } @@ -304,6 +309,7 @@ export default function SandboxList({ } const revokeMcpForSandbox = (sandbox: SandboxInventoryItem, server: McpServerAccess) => { + const hasOtherMcpAccess = mcpServers.some((candidate) => candidate.id !== server.id && sandboxCanAccessMcpServer(sandbox, candidate)) const current = new Set(server.allowedSandboxIds) current.delete(sandbox.id) current.delete(sandbox.name) @@ -315,7 +321,7 @@ export default function SandboxList({ return updateMcpServerAccess(server, { accessMode: 'allow_only', allowedSandboxIds: Array.from(current), - }, `${server.name} revoked from ${sandbox.name}.`).then(() => syncMcpManifest(sandbox)) + }, `${server.name} revoked from ${sandbox.name}.`).then(() => syncMcpManifest(sandbox, hasOtherMcpAccess ? 'sync' : 'revoke')) } const resolvePermissionRequest = async (sandbox: SandboxInventoryItem, action: 'approve' | 'reject', chunkId: string) => { @@ -613,10 +619,10 @@ export default function SandboxList({
{mcpMessage && ( @@ -699,58 +705,109 @@ export default function SandboxList({ Refresh Requests
- {(() => { - const feed = permissionFeeds[selectedSandbox.id] - const pending = feed?.pending || [] - if (pending.length === 0) { - return ( -
- No pending network permission requests for this sandbox. -
- ) - } + {(() => { + const feed = permissionFeeds[selectedSandbox.id] + const pending = feed?.pending || [] + const recent = feed?.recent || [] + const recentRules = recent.filter((request) => !pending.some((pendingRequest) => pendingRequest.chunkId === request.chunkId)) + const renderRecentRules = () => recentRules.length > 0 && ( +
+

Recent Network Rules

+
+ {recentRules.map((request) => { + const approved = /approved/i.test(request.status) + const rejected = /rejected/i.test(request.status) + return ( +
+
+
+
+ + {request.endpoints.join(', ') || request.rule} + + + {request.status || 'unknown'} + +
+

{request.rationale || 'Sandbox network rule.'}

+

+ {request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId} +

+
+ {(approved || rejected) && ( + + )} +
+
+ ) + })} +
+
+ ) + if (pending.length === 0) { + return ( + <> +
+ No pending network permission requests for this sandbox. +
+ {renderRecentRules()} + + ) + } - return pending.map((request) => ( -
-
-
-
- - {request.endpoints.join(', ') || request.rule} - - {request.confidence ? ( - - {request.confidence} - - ) : null} + return ( +
+ {pending.map((request) => ( +
+
+
+
+ + {request.endpoints.join(', ') || request.rule} + + {request.confidence ? ( + + {request.confidence} + + ) : null} +
+

{request.rationale || 'Sandbox requested a network policy rule.'}

+

+ {request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId} +

+
+
+ + +
-

{request.rationale || 'Sandbox requested a network policy rule.'}

-

- {request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId} -

-
- - -
-
-
- )) - })()} + ))} + {renderRecentRules()} +
+ ) + })()}
diff --git a/app/lib/mcpBrokerStore.ts b/app/lib/mcpBrokerStore.ts index 1cb42a4..18f7318 100644 --- a/app/lib/mcpBrokerStore.ts +++ b/app/lib/mcpBrokerStore.ts @@ -86,6 +86,20 @@ export async function verifySandboxMcpBrokerToken(token: string) { return session } +export async function revokeSandboxMcpBrokerSession(sandboxId: string) { + const store = await readStore() + const existing = store.sessions[sandboxId] + if (!existing) return null + store.sessions[sandboxId] = { + ...existing, + enabled: false, + rotatedAt: new Date().toISOString(), + expiresAt: new Date().toISOString(), + } + await writeStore(store) + return store.sessions[sandboxId] +} + export async function listAllowedBrokerServers(session: SandboxMcpBrokerSession) { const inventory = await listMcpServers() return inventory.servers.filter((server) => sandboxCanAccessMcpServer(server, session.sandboxId, session.sandboxName)) diff --git a/app/lib/mcpBrokerUrl.ts b/app/lib/mcpBrokerUrl.ts new file mode 100644 index 0000000..7690d49 --- /dev/null +++ b/app/lib/mcpBrokerUrl.ts @@ -0,0 +1,82 @@ +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { HOST_PATH, OPENSHELL_BIN } from "./hostCommands" +import { resolveSandboxRef } from "./openshellHost" + +const execFileAsync = promisify(execFile) + +const LOCAL_HOSTNAMES = new Set(["localhost", "127.0.0.1", "0.0.0.0", "host.docker.internal", "host.openshell.internal"]) +const FALLBACK_SANDBOX_PROXY_ORIGIN = "http://10.200.0.1:3128" + +async function discoverOpenShellDockerGateway() { + const container = process.env.OPEN_SHELL_CONTAINER || "openshell-cluster-nemoclaw" + const { stdout } = await execFileAsync("docker", ["inspect", container], { + env: { ...process.env, PATH: HOST_PATH }, + timeout: 5000, + maxBuffer: 1024 * 1024, + }) + const [inspect] = JSON.parse(String(stdout)) as Array<{ + NetworkSettings?: { + Networks?: Record + } + }> + const networks = inspect?.NetworkSettings?.Networks || {} + return Object.values(networks).map((network) => network.Gateway).find(Boolean) || null +} + +function normalizeProxyOrigin(value: string) { + try { + const proxy = new URL(value) + if (proxy.protocol !== "http:" && proxy.protocol !== "https:") return null + return proxy.toString().replace(/\/+$/, "") + } catch { + return null + } +} + +async function runOpenShell(args: string[]) { + const { stdout } = await execFileAsync(OPENSHELL_BIN, args, { + env: { + ...process.env, + PATH: HOST_PATH, + OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw", + NO_COLOR: "1", + CLICOLOR: "0", + CLICOLOR_FORCE: "0", + TERM: "dumb", + }, + timeout: 15000, + maxBuffer: 1024 * 1024, + }) + return String(stdout) +} + +async function discoverSandboxProxyOrigin(sandboxId: string, sandboxName?: string | null) { + const resolvedName = sandboxName || (await resolveSandboxRef(sandboxId)).name + const script = "printf '%s\\n' \"${HTTP_PROXY:-${http_proxy:-${HTTPS_PROXY:-${https_proxy:-}}}}\"" + const output = await runOpenShell(["sandbox", "exec", "-n", resolvedName, "--", "sh", "-lc", script]) + return normalizeProxyOrigin(output.trim()) +} + +export async function brokerBaseUrlForSandbox( + request: Request, + sandbox?: { id: string, name?: string | null }, +) { + if (process.env.OPENSHELL_CONTROL_MCP_BROKER_URL) return process.env.OPENSHELL_CONTROL_MCP_BROKER_URL + + const origin = new URL(request.url).origin + const publicOrigin = new URL(origin) + if (LOCAL_HOSTNAMES.has(publicOrigin.hostname)) { + const gateway = await discoverOpenShellDockerGateway().catch(() => null) + publicOrigin.hostname = gateway || "host.docker.internal" + } + + const hostBrokerUrl = `${publicOrigin.toString().replace(/\/+$/, "")}/api/mcp/broker` + const proxyOrigin = sandbox + ? await discoverSandboxProxyOrigin(sandbox.id, sandbox.name).catch(() => null) + : null + + if (proxyOrigin) return `${proxyOrigin}/${hostBrokerUrl}` + if (LOCAL_HOSTNAMES.has(new URL(origin).hostname)) return `${FALLBACK_SANDBOX_PROXY_ORIGIN}/${hostBrokerUrl}` + return hostBrokerUrl +} diff --git a/app/lib/mcpServerStore.ts b/app/lib/mcpServerStore.ts index 04974b2..9d39612 100644 --- a/app/lib/mcpServerStore.ts +++ b/app/lib/mcpServerStore.ts @@ -85,6 +85,7 @@ export const MCP_SERVER_CATALOG: McpCatalogEntry[] = [ tags: ["web", "utility"], }, ] +const BASELINE_MCP_SERVER_IDS = ["memory"] function emptyStore(): StoreShape { return { servers: {} } @@ -164,6 +165,23 @@ async function writeStore(store: StoreShape) { await writeFile(STORE_PATH, JSON.stringify(store, null, 2), { mode: 0o600 }) } +async function ensureBaselineMcpServers(store: StoreShape) { + let changed = false + for (const id of BASELINE_MCP_SERVER_IDS) { + const entry = MCP_SERVER_CATALOG.find((candidate) => candidate.id === id) + if (!entry || store.servers[id]) continue + store.servers[id] = normalizeInstall({ + ...entry, + source: "catalog", + enabled: true, + accessMode: "disabled", + allowedSandboxIds: [], + }) + changed = true + } + if (changed) await writeStore(store) +} + export function buildMcpClientConfig(servers: McpServerInstall[]) { return { mcpServers: Object.fromEntries( @@ -195,6 +213,7 @@ export function sandboxCanAccessMcpServer(server: McpServerInstall, sandboxId: s export async function listMcpServers() { const store = await readStore() + await ensureBaselineMcpServers(store) const servers = Object.values(store.servers).sort((a, b) => a.name.localeCompare(b.name)) return { catalog: MCP_SERVER_CATALOG, diff --git a/app/lib/sandboxFiles.ts b/app/lib/sandboxFiles.ts index 854c298..88afa54 100644 --- a/app/lib/sandboxFiles.ts +++ b/app/lib/sandboxFiles.ts @@ -21,6 +21,16 @@ function sanitizeArchiveStem(value: string) { return value.trim().replace(/[^\w.@:+-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "") || "sandbox" } +function normalizeRelativeArchivePath(input: string, fallbackFileName: string) { + const raw = input.trim() || fallbackFileName + if (!raw || raw.includes("\0")) throw new Error("relative file path contains unsupported characters") + const normalized = path.posix.normalize(raw).replace(/^\/+/, "") + if (!normalized || normalized === "." || normalized.startsWith("../") || normalized.includes("/../")) { + throw new Error("relative file path must stay inside the uploaded directory") + } + return normalized +} + export function normalizeSandboxPath(input: string, fallbackFileName?: string) { const raw = input.trim() if (!raw) throw new Error("sandbox path is required") @@ -106,6 +116,31 @@ export async function uploadSandboxFile(sandboxId: string, destinationPath: stri } } +export async function uploadSandboxFiles( + sandboxId: string, + destinationDirectory: string, + files: Array<{ fileName: string; relativePath: string; payload: Buffer }> +) { + if (files.length === 0) throw new Error("at least one file is required") + const totalBytes = files.reduce((sum, file) => sum + file.payload.byteLength, 0) + if (totalBytes > MAX_FILE_BYTES) { + throw new Error(`directory upload is too large; max transfer size is ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MiB`) + } + + const uploaded = [] + for (const file of files) { + const relativePath = normalizeRelativeArchivePath(file.relativePath, file.fileName) + const targetPath = path.posix.join(destinationDirectory, relativePath) + uploaded.push(await uploadSandboxFile(sandboxId, targetPath, file.fileName, file.payload)) + } + + return { + sandboxName: uploaded[0]?.sandboxName || await resolveSandboxName(sandboxId), + files: uploaded, + bytes: totalBytes, + } +} + export async function downloadSandboxFile(sandboxId: string, sourcePath: string) { const sandboxName = await resolveSandboxName(sandboxId) const targetPath = normalizeSandboxPath(sourcePath) @@ -128,6 +163,36 @@ export async function downloadSandboxFile(sandboxId: string, sourcePath: string) } } +export async function downloadSandboxPath(sandboxId: string, sourcePath: string) { + const sandboxName = await resolveSandboxName(sandboxId) + const targetPath = normalizeSandboxPath(sourcePath) + const typeScript = `if [ -f ${shellQuote(targetPath)} ]; then echo file; elif [ -d ${shellQuote(targetPath)} ]; then echo directory; else exit 1; fi` + const typeResult = await runSandboxExec(sandboxName, typeScript, undefined, 30000) + if (typeResult.code !== 0) throw new Error("sandbox path does not exist or is not readable") + const type = typeResult.stdout.toString("utf8").trim() + + if (type === "file") { + return { ...(await downloadSandboxFile(sandboxId, targetPath)), archive: false } + } + + const parent = path.posix.dirname(targetPath) + const base = path.posix.basename(targetPath) || "sandbox" + const archiveName = `${sanitizeArchiveStem(base)}.tar.gz` + const result = await runSandboxExec(sandboxName, `tar -C ${shellQuote(parent)} -czf - ${shellQuote(base)}`, undefined, 120000) + if (result.code !== 0) throw new Error(result.stderr || "failed to archive sandbox directory") + if (result.stdout.byteLength > MAX_FILE_BYTES) { + throw new Error(`directory archive is too large; max transfer size is ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MiB`) + } + + return { + sandboxName, + path: targetPath, + fileName: archiveName, + bytes: result.stdout, + archive: true, + } +} + export type SandboxFileListEntry = { name: string path: string diff --git a/app/lib/sandboxMcpManifest.ts b/app/lib/sandboxMcpManifest.ts index d4943bf..9dd508e 100644 --- a/app/lib/sandboxMcpManifest.ts +++ b/app/lib/sandboxMcpManifest.ts @@ -1,4 +1,4 @@ -import { rotateSandboxMcpBrokerSession } from "./mcpBrokerStore" +import { revokeSandboxMcpBrokerSession, rotateSandboxMcpBrokerSession } from "./mcpBrokerStore" import { uploadSandboxFile } from "./sandboxFiles" export const SANDBOX_MCP_MANIFEST_PATH = "/sandbox/openshell_control_mcp.md" @@ -87,3 +87,40 @@ export async function syncSandboxMcpManifest( markdown: handoff.markdown, } } + +export async function revokeSandboxMcpManifest(sandbox: SandboxRef) { + const session = await revokeSandboxMcpBrokerSession(sandbox.id) + const now = new Date().toISOString() + const markdown = [ + "# OpenShell Control MCP Broker", + "", + `Generated: ${now}`, + `Sandbox: ${sandbox.name || sandbox.id}`, + `Sandbox ID: ${sandbox.id}`, + "", + "MCP access is currently disabled for this sandbox.", + "", + "The previous broker token has been revoked. Ask the operator to enable an MCP server and issue a new broker config if MCP access is needed.", + "", + ].join("\n") + const uploaded = await uploadSandboxFile( + sandbox.id, + SANDBOX_MCP_MANIFEST_PATH, + "openshell_control_mcp.md", + Buffer.from(markdown, "utf8"), + ) + + return { + path: uploaded.path, + sandboxName: uploaded.sandboxName, + bytes: uploaded.bytes, + brokerSession: session ? { + sandboxId: session.sandboxId, + sandboxName: session.sandboxName, + enabled: session.enabled, + rotatedAt: session.rotatedAt, + expiresAt: session.expiresAt, + } : null, + markdown, + } +} diff --git a/app/lib/sandboxPermissions.ts b/app/lib/sandboxPermissions.ts index 3dc4dc9..064285f 100644 --- a/app/lib/sandboxPermissions.ts +++ b/app/lib/sandboxPermissions.ts @@ -16,6 +16,13 @@ export type SandboxNetworkRule = { binaries: string[] } +type BrokerNetworkAction = { + action: "approve" | "reject" + chunkId: string + endpoint: string + status: string +} + function runOpenShell(args: string[], timeout = 60000) { return execFileAsync(OPENSHELL_BIN, args, { env: { @@ -73,6 +80,21 @@ function parseNetworkRules(output: string): SandboxNetworkRule[] { .filter((rule) => rule.chunkId) } +function brokerEndpointCandidates(brokerBaseUrl: string) { + const parsed = new URL(brokerBaseUrl) + const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80") + const hostPort = `${parsed.hostname}:${port}` + const candidates = new Set([hostPort]) + if (parsed.hostname === "host.docker.internal") candidates.add(`0.0.0.0:${port}`) + return candidates +} + +function ruleMatchesEndpoints(rule: SandboxNetworkRule, candidates: Set) { + return rule.endpoints.some((endpoint) => candidates.has(endpoint)) + || Array.from(candidates).some((endpoint) => rule.rule.includes(endpoint.replace(/[^a-zA-Z0-9]/g, "_"))) + || Array.from(candidates).some((endpoint) => rule.rationale.includes(endpoint)) +} + async function listRulesForStatus(sandboxName: string, status: "pending" | "approved" | "rejected") { const { stdout } = await runOpenShell(["rule", "get", "--status", status, sandboxName], 30000) return parseNetworkRules(String(stdout)) @@ -121,3 +143,69 @@ export async function resolveSandboxNetworkRule(sandboxId: string, action: strin feed, } } + +async function probeBrokerEndpoint(sandboxName: string, brokerBaseUrl: string) { + const capabilitiesUrl = `${brokerBaseUrl.replace(/\/+$/, "")}/capabilities` + const script = `curl --noproxy '*' -sS --max-time 5 ${JSON.stringify(capabilitiesUrl)} >/dev/null || true` + await runOpenShell(["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", script], 15000).catch(() => null) +} + +export async function syncBrokerNetworkAccess(sandboxId: string, brokerBaseUrl: string) { + const resolved = await resolveSandboxRef(sandboxId) + const candidates = brokerEndpointCandidates(brokerBaseUrl) + await probeBrokerEndpoint(resolved.name, brokerBaseUrl) + const pending = await listRulesForStatus(resolved.name, "pending").catch(() => [] as SandboxNetworkRule[]) + const matchingPending = pending.filter((rule) => ruleMatchesEndpoints(rule, candidates)) + const approved: BrokerNetworkAction[] = [] + + for (const rule of matchingPending) { + await resolveSandboxNetworkRule(resolved.name, "approve", rule.chunkId) + approved.push({ + action: "approve", + chunkId: rule.chunkId, + endpoint: rule.endpoints.find((endpoint) => candidates.has(endpoint)) || Array.from(candidates)[0] || "", + status: rule.status, + }) + } + + const currentlyApproved = await listRulesForStatus(resolved.name, "approved").catch(() => [] as SandboxNetworkRule[]) + return { + sandboxId, + sandboxName: resolved.name, + brokerBaseUrl, + approved, + alreadyApproved: currentlyApproved.filter((rule) => ruleMatchesEndpoints(rule, candidates)).map((rule) => ({ + chunkId: rule.chunkId, + endpoints: rule.endpoints, + status: rule.status, + })), + } +} + +export async function revokeBrokerNetworkAccess(sandboxId: string, brokerBaseUrl: string) { + const resolved = await resolveSandboxRef(sandboxId) + const candidates = brokerEndpointCandidates(brokerBaseUrl) + const [pending, approved] = await Promise.all([ + listRulesForStatus(resolved.name, "pending").catch(() => [] as SandboxNetworkRule[]), + listRulesForStatus(resolved.name, "approved").catch(() => [] as SandboxNetworkRule[]), + ]) + const matching = [...pending, ...approved].filter((rule) => ruleMatchesEndpoints(rule, candidates)) + const rejected: BrokerNetworkAction[] = [] + + for (const rule of matching) { + await resolveSandboxNetworkRule(resolved.name, "reject", rule.chunkId, "MCP broker access revoked") + rejected.push({ + action: "reject", + chunkId: rule.chunkId, + endpoint: rule.endpoints.find((endpoint) => candidates.has(endpoint)) || Array.from(candidates)[0] || "", + status: rule.status, + }) + } + + return { + sandboxId, + sandboxName: resolved.name, + brokerBaseUrl, + rejected, + } +} diff --git a/install.sh b/install.sh index 9f9fd55..e202865 100755 --- a/install.sh +++ b/install.sh @@ -100,6 +100,55 @@ optional_command() { fi } +prepend_user_bin() { + if [[ -n "${HOME:-}" && ":$PATH:" != *":$HOME/.local/bin:"* ]]; then + export PATH="$HOME/.local/bin:$PATH" + fi +} + +ensure_npx() { + if command -v npx >/dev/null 2>&1; then + log "npx MCP package runner: $(command -v npx)" + return + fi + + log "Installing npx MCP package runner with npm" + npm install -g npx + command -v npx >/dev/null 2>&1 || fail "npx installation completed, but npx is still not on PATH." + log "npx MCP package runner: $(command -v npx)" +} + +ensure_uvx() { + prepend_user_bin + if command -v uvx >/dev/null 2>&1; then + log "uvx MCP package runner: $(command -v uvx)" + return + fi + + log "Installing uvx MCP package runner" + local installed=0 + if command -v python3 >/dev/null 2>&1 && python3 -m pip --version >/dev/null 2>&1; then + if python3 -m pip install --user --upgrade uv; then + installed=1 + else + warn "Python pip could not install uv for this user; trying the standalone uv installer." + fi + fi + + if [[ "$installed" -ne 1 ]] && command -v curl >/dev/null 2>&1; then + curl -LsSf https://astral.sh/uv/install.sh | sh + installed=1 + fi + + if [[ "$installed" -ne 1 ]]; then + fail "uvx is required for uvx-based MCP servers. Install Python pip or curl, then rerun the installer." + fi + + prepend_user_bin + command -v uvx >/dev/null 2>&1 || fail "uvx installation completed, but uvx is still not on PATH." + log "uvx MCP package runner: $(command -v uvx)" +} + port_owner() { local port="$1" if command -v lsof >/dev/null 2>&1; then @@ -255,6 +304,7 @@ fi require_command node require_command npm require_command docker +prepend_user_bin NODE_MAJOR="$(node_major)" if [[ "$NODE_MAJOR" -lt "$MIN_NODE_MAJOR" ]]; then @@ -262,7 +312,8 @@ if [[ "$NODE_MAJOR" -lt "$MIN_NODE_MAJOR" ]]; then fi log "Node $(node -v), npm $(npm -v)" -optional_command uvx "uvx MCP package runner" +ensure_npx +ensure_uvx if ! docker ps >/dev/null 2>&1; then fail "Docker is not reachable. Start Docker and rerun the installer." diff --git a/middleware.ts b/middleware.ts index 95d3d75..5ca1370 100644 --- a/middleware.ts +++ b/middleware.ts @@ -13,11 +13,18 @@ const PUBLIC_PATHS = [ "/favicon.svg", "/favicon-32.png", ] +const BROKER_PATHS = [ + "/api/mcp/broker", +] function isPublicPath(pathname: string) { return PUBLIC_PATHS.some((path) => pathname === path || pathname.startsWith(`${path}/`)) } +function isBrokerPath(pathname: string) { + return BROKER_PATHS.some((path) => pathname === path || pathname.startsWith(`${path}/`)) +} + function isAssetPath(pathname: string) { return pathname.startsWith("/_next/") || pathname.startsWith("/public/") } @@ -97,6 +104,10 @@ export async function middleware(request: NextRequest) { return withSecurityHeaders(NextResponse.next()) } + if (isBrokerPath(pathname)) { + return withSecurityHeaders(NextResponse.next()) + } + if (isPublicPath(pathname)) { if (pathname === "/login" && await verifySessionCookieValue(request.cookies.get(settings.cookieName)?.value)) { return withSecurityHeaders(NextResponse.redirect(new URL("/", request.url))) diff --git a/tests/mcp-configuration-page-check.mjs b/tests/mcp-configuration-page-check.mjs index 631d34b..c9cc825 100644 --- a/tests/mcp-configuration-page-check.mjs +++ b/tests/mcp-configuration-page-check.mjs @@ -13,12 +13,14 @@ const registryRoutePath = path.join(root, 'app/api/mcp/registry/route.ts') const brokerCapabilitiesRoutePath = path.join(root, 'app/api/mcp/broker/capabilities/route.ts') const brokerCallRoutePath = path.join(root, 'app/api/mcp/broker/call/route.ts') const sandboxMcpRoutePath = path.join(root, 'app/api/sandbox/[sandboxId]/mcp/route.ts') +const brokerUrlPath = path.join(root, 'app/lib/mcpBrokerUrl.ts') +const middlewarePath = path.join(root, 'middleware.ts') const panelPath = path.join(root, 'app/components/McpConfigurationPanel.tsx') const sidebarPath = path.join(root, 'app/components/Sidebar.tsx') const sandboxListPath = path.join(root, 'app/components/SandboxList.tsx') const pagePath = path.join(root, 'app/page.tsx') -const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, routeSource, registryRouteSource, brokerCapabilitiesRouteSource, brokerCallRouteSource, sandboxMcpRouteSource, panelSource, sidebarSource, sandboxListSource, pageSource] = await Promise.all([ +const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, routeSource, registryRouteSource, brokerCapabilitiesRouteSource, brokerCallRouteSource, sandboxMcpRouteSource, brokerUrlSource, middlewareSource, panelSource, sidebarSource, sandboxListSource, pageSource] = await Promise.all([ readFile(storePath, 'utf8'), readFile(brokerStorePath, 'utf8'), readFile(brokerClientPath, 'utf8'), @@ -28,6 +30,8 @@ const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, route readFile(brokerCapabilitiesRoutePath, 'utf8'), readFile(brokerCallRoutePath, 'utf8'), readFile(sandboxMcpRoutePath, 'utf8'), + readFile(brokerUrlPath, 'utf8'), + readFile(middlewarePath, 'utf8'), readFile(panelPath, 'utf8'), readFile(sidebarPath, 'utf8'), readFile(sandboxListPath, 'utf8'), @@ -37,6 +41,8 @@ const [storeSource, brokerStoreSource, brokerClientSource, manifestSource, route assert.match(storeSource, /export const MCP_SERVER_CATALOG/, 'MCP store must expose an install catalog') assert.match(storeSource, /blendermcp\.org/, 'MCP catalog must include the requested BlenderMCP site') assert.match(storeSource, /args:\s*\["blender-mcp"\]/, 'MCP catalog must install BlenderMCP via uvx blender-mcp') +assert.match(storeSource, /BASELINE_MCP_SERVER_IDS = \["memory"\]/, 'MCP dashboard should install Memory as the baseline test server') +assert.match(storeSource, /ensureBaselineMcpServers/, 'MCP store must seed baseline servers into dashboard state') assert.match(storeSource, /mcp-servers\.json/, 'MCP installs must persist to dashboard state') assert.match(storeSource, /accessMode/, 'MCP installs must persist sandbox access mode') assert.match(storeSource, /allowedSandboxIds/, 'MCP installs must persist allowed sandbox lists') @@ -59,7 +65,17 @@ assert.match(brokerCapabilitiesRouteSource, /listBrokerServerTools/, 'MCP broker assert.match(brokerCallRouteSource, /Requested MCP capability is unavailable/, 'MCP broker denied calls must not disclose blocked server names') assert.match(brokerCallRouteSource, /callBrokerServerTool/, 'MCP broker call route must forward allowed calls') assert.match(sandboxMcpRouteSource, /export async function POST/, 'Sandbox MCP route must write the broker handoff') +assert.match(sandboxMcpRouteSource, /action === "revoke"/, 'Sandbox MCP route must revoke broker handoff when MCP access is removed') +assert.match(sandboxMcpRouteSource, /syncBrokerNetworkAccess/, 'Sandbox MCP route must synchronize broker network access when MCP is enabled') +assert.match(sandboxMcpRouteSource, /revokeBrokerNetworkAccess/, 'Sandbox MCP route must remove broker network access when MCP is revoked') assert.match(sandboxMcpRouteSource, /export async function GET/, 'Sandbox MCP route must preview the broker handoff') +assert.match(sandboxMcpRouteSource, /brokerBaseUrlForSandbox/, 'Sandbox MCP broker handoff must build a sandbox-routable broker URL') +assert.match(brokerUrlSource, /discoverOpenShellDockerGateway/, 'Sandbox MCP broker handoff must discover the active OpenShell network gateway') +assert.match(brokerUrlSource, /LOCAL_HOSTNAMES/, 'Sandbox MCP broker handoff must rewrite local-only browser origins') +assert.match(brokerUrlSource, /discoverSandboxProxyOrigin/, 'Sandbox MCP broker handoff must discover each sandbox proxy endpoint') +assert.match(brokerUrlSource, /HTTP_PROXY/, 'Sandbox MCP broker handoff must derive the proxy endpoint from sandbox environment') +assert.match(brokerUrlSource, /FALLBACK_SANDBOX_PROXY_ORIGIN/, 'Sandbox MCP broker handoff may keep a fallback for older OpenShell layouts') +assert.match(middlewareSource, /\/api\/mcp\/broker/, 'MCP broker endpoints must bypass dashboard cookie auth and rely on broker token auth') assert.match(routeSource, /export async function GET/, 'MCP API must list server configuration') assert.match(routeSource, /export async function POST/, 'MCP API must install and update server configuration') assert.match(routeSource, /installMcpServer/, 'MCP API must support installing servers') @@ -85,7 +101,8 @@ assert.match(panelSource, /Allow Only/, 'MCP security must support allow-list ac assert.match(panelSource, /Setup Guide/, 'MCP catalog cards should link out to app setup guides') assert.match(panelSource, /Client JSON/, 'MCP page must surface generated client JSON') assert.match(sandboxListSource, /Allowed MCP Server Access/, 'Sandbox page must expose allowed MCP server access accordion') -assert.match(sandboxListSource, /Issue Broker Config/, 'Sandbox MCP access controls must issue broker config') +assert.match(sandboxListSource, /Sync Broker Config/, 'Sandbox MCP access controls must sync broker config') +assert.match(sandboxListSource, /hasOtherMcpAccess/, 'Sandbox MCP access controls must revoke broker config when no MCP servers remain') assert.match(sandboxListSource, /\/sandbox\/openshell_control_mcp\.md/, 'Sandbox MCP access controls must name the manifest path') assert.match(sandboxListSource, /sandboxCanAccessMcpServer/, 'Sandbox page must derive MCP access per sandbox') assert.match(sandboxListSource, /MCP access allowed/, 'Sandbox cards must show a lit MCP access indicator') diff --git a/tests/portable-install-check.mjs b/tests/portable-install-check.mjs index 6788f11..f746cd3 100644 --- a/tests/portable-install-check.mjs +++ b/tests/portable-install-check.mjs @@ -15,6 +15,7 @@ const [ sandboxPermissionsSource, inferenceSource, supportBundleSource, + mcpBrokerUrlSource, ] = await Promise.all([ readFile(path.join(root, 'install.sh'), 'utf8'), readFile(path.join(root, 'app/lib/hostCommands.ts'), 'utf8'), @@ -26,6 +27,7 @@ const [ readFile(path.join(root, 'app/lib/sandboxPermissions.ts'), 'utf8'), readFile(path.join(root, 'app/api/inference/route.ts'), 'utf8'), readFile(path.join(root, 'app/api/support-bundle/route.ts'), 'utf8'), + readFile(path.join(root, 'app/lib/mcpBrokerUrl.ts'), 'utf8'), ]) assert.match(installSource, /find_nemoclaw_bin\(\)/, 'installer must discover NemoClaw CLI') @@ -37,6 +39,11 @@ assert.match(installSource, /set_env "NEMOCLAW_SETUP"/, 'installer must persist assert.match(installSource, /set_env "NEMOCLAW_BIN"/, 'installer must persist discovered NemoClaw CLI path') assert.match(installSource, /set_env "OPENSHELL_BIN"/, 'installer must persist discovered OpenShell path') assert.match(installSource, /upsert_env "TERMINAL_SERVER_AUTOSTART" "true"/, 'installer must enable terminal bridge autostart by default') +assert.match(installSource, /ensure_npx\(\)/, 'installer must install or verify npx for stdio MCP servers') +assert.match(installSource, /ensure_uvx\(\)/, 'installer must install or verify uvx for stdio MCP servers') +assert.match(installSource, /python3 -m pip install --user --upgrade uv/, 'installer must support user-scoped uvx installation') +assert.match(installSource, /standalone uv installer/, 'installer must fall back when Python blocks user-scoped uv installs') +assert.match(installSource, /prepend_user_bin\(\)/, 'installer must put ~/.local/bin on PATH for user-scoped MCP runners') assert.match(hostCommandsSource, /export const HOST_PATH/, 'host command resolution must centralize PATH construction') assert.match(hostCommandsSource, /\.nemoclaw\/source\/bin\/nemoclaw\.js/, 'host command resolution must support standard ~/.nemoclaw installs') @@ -45,6 +52,11 @@ assert.match(hostCommandsSource, /discoverHomeFiles\("scripts\/setup\.sh"\)/, 'r assert.match(hostCommandsSource, /discoverHomeFiles\("bin\/nemoclaw\.js"\)/, 'runtime command resolution must scan user home directories for nemoclaw.js') assert.match(hostCommandsSource, /export const NEMOCLAW_SETUP_CANDIDATES/, 'runtime command resolution must expose searched setup candidates') assert.doesNotMatch(hostCommandsSource, /\/Users\/markmckeen|\/home\/nvidia/, 'host command resolution must not bake in developer machine paths') +assert.match(mcpBrokerUrlSource, /discoverOpenShellDockerGateway/, 'MCP broker URL generation must discover the active OpenShell Docker gateway') +assert.match(mcpBrokerUrlSource, /OPEN_SHELL_CONTAINER/, 'MCP broker URL generation must respect the configured cluster container') +assert.match(mcpBrokerUrlSource, /host\.docker\.internal/, 'MCP broker URL generation must keep a fallback for hosts without Docker inspect') +assert.match(mcpBrokerUrlSource, /discoverSandboxProxyOrigin/, 'MCP broker URL generation must discover each sandbox proxy endpoint') +assert.match(mcpBrokerUrlSource, /HTTP_PROXY/, 'MCP broker URL generation must use the sandbox proxy environment when available') assert.match(createRouteSource, /buildNemoClawCreateCommand\(\)/, 'NemoClaw blueprint create must resolve a current CLI command') assert.match(createRouteSource, /"onboard", "--non-interactive"/, 'NemoClaw blueprint create must use the supported onboard CLI flow')