Harden MCP broker sandbox handoff
This commit is contained in:
@@ -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<string, string> = {}) {
|
||||
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"
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -361,10 +361,10 @@ export default function McpConfigurationPanel({ sandboxes = [] }: McpConfigurati
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
{pagedRegistryResults.map((entry) => {
|
||||
{pagedRegistryResults.map((entry, index) => {
|
||||
const installed = installedIds.has(entry.id)
|
||||
return (
|
||||
<div key={`${entry.id}-${entry.command}`} className="metric flex min-h-44 flex-col p-4">
|
||||
<div key={`${entry.id}-${entry.command}-${entry.args.join("|")}-${index}`} className="metric flex min-h-44 flex-col p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<h3 className="truncate text-sm font-semibold text-[var(--foreground)]">{entry.name}</h3>
|
||||
|
||||
@@ -47,6 +47,8 @@ export default function SandboxFilesPanel({
|
||||
showHeader?: boolean
|
||||
}) {
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [selectedDirectoryFiles, setSelectedDirectoryFiles] = useState<File[]>([])
|
||||
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({
|
||||
</div>
|
||||
<input
|
||||
type="file"
|
||||
onChange={(event) => 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)]"
|
||||
/>
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
{...({ webkitdirectory: "", directory: "" } as Record<string, string>)}
|
||||
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)]"
|
||||
/>
|
||||
<div className="space-y-2">
|
||||
@@ -202,20 +231,25 @@ export default function SandboxFilesPanel({
|
||||
{selectedFile && (
|
||||
<p className="text-[11px] font-mono text-[var(--foreground-dim)]">Target: {suggestedUploadPath}</p>
|
||||
)}
|
||||
{uploadMode === "directory" && selectedDirectoryFiles.length > 0 && (
|
||||
<p className="text-[11px] font-mono text-[var(--foreground-dim)]">
|
||||
Directory upload: {selectedDirectoryFiles.length} file{selectedDirectoryFiles.length === 1 ? "" : "s"} into {uploadPath}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={uploadFile}
|
||||
disabled={!selectedFile || busy !== null}
|
||||
disabled={uploadCount === 0 || busy !== null}
|
||||
className="rounded-sm bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
|
||||
>
|
||||
{busy === "upload" ? "Uploading..." : "Upload File"}
|
||||
{busy === "upload" ? "Uploading..." : uploadMode === "directory" ? "Upload Directory" : "Upload File"}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-4">
|
||||
<div>
|
||||
<h5 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Download</h5>
|
||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Browse sandbox files or enter a regular file path under /sandbox or /tmp.</p>
|
||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Browse sandbox files or enter a file or directory path under /sandbox or /tmp.</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-2 md:grid-cols-[1fr_auto_auto]">
|
||||
<input
|
||||
@@ -282,11 +316,9 @@ export default function SandboxFilesPanel({
|
||||
type="button"
|
||||
onClick={() => {
|
||||
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"}
|
||||
</button>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
+115
-58
@@ -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({
|
||||
<button
|
||||
type="button"
|
||||
disabled={mcpSyncing}
|
||||
onClick={() => syncMcpManifest(selectedSandbox)}
|
||||
onClick={() => syncMcpManifest(selectedSandbox, allowedMcpServersForSandbox(selectedSandbox).length > 0 ? 'sync' : 'revoke')}
|
||||
className="action-button px-3 py-2 max-sm:w-full"
|
||||
>
|
||||
{mcpSyncing ? 'Issuing...' : 'Issue Broker Config'}
|
||||
{mcpSyncing ? 'Updating...' : 'Sync Broker Config'}
|
||||
</button>
|
||||
</div>
|
||||
{mcpMessage && (
|
||||
@@ -699,58 +705,109 @@ export default function SandboxList({
|
||||
Refresh Requests
|
||||
</button>
|
||||
</div>
|
||||
{(() => {
|
||||
const feed = permissionFeeds[selectedSandbox.id]
|
||||
const pending = feed?.pending || []
|
||||
if (pending.length === 0) {
|
||||
return (
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
|
||||
No pending network permission requests for this sandbox.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{(() => {
|
||||
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 && (
|
||||
<div className="space-y-3">
|
||||
<h4 className="text-[10px] font-semibold uppercase tracking-wider text-[var(--foreground-dim)]">Recent Network Rules</h4>
|
||||
<div className="max-h-[26rem] space-y-3 overflow-y-auto pr-1">
|
||||
{recentRules.map((request) => {
|
||||
const approved = /approved/i.test(request.status)
|
||||
const rejected = /rejected/i.test(request.status)
|
||||
return (
|
||||
<div key={`${request.status}-${request.chunkId}`} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4">
|
||||
<div className="flex items-start justify-between gap-4 max-md:flex-col">
|
||||
<div className="min-w-0 space-y-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="break-all text-xs font-mono font-semibold text-[var(--foreground)]">
|
||||
{request.endpoints.join(', ') || request.rule}
|
||||
</span>
|
||||
<span className={`status-chip px-2 py-1 ${approved ? 'bg-[var(--status-running-bg)] text-[var(--status-running)]' : rejected ? 'bg-[var(--status-stopped)] text-white' : 'bg-[var(--status-pending-bg)] text-[var(--status-pending)]'}`}>
|
||||
{request.status || 'unknown'}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-[var(--foreground-dim)]">{request.rationale || 'Sandbox network rule.'}</p>
|
||||
<p className="text-[10px] font-mono text-[var(--foreground-dim)]">
|
||||
{request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId}
|
||||
</p>
|
||||
</div>
|
||||
{(approved || rejected) && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={grantingSandboxId === selectedSandbox.id}
|
||||
onClick={() => resolvePermissionRequest(selectedSandbox, approved ? 'reject' : 'approve', request.chunkId)}
|
||||
className={`${rejected ? 'rounded-sm border border-[var(--nvidia-green)] bg-[var(--nvidia-green)] text-black' : 'rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] text-[var(--foreground)]'} px-3 py-2 text-xs font-mono uppercase tracking-wider disabled:opacity-50 max-md:w-full`}
|
||||
>
|
||||
{approved ? 'Revoke' : 'Approve'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
if (pending.length === 0) {
|
||||
return (
|
||||
<>
|
||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
|
||||
No pending network permission requests for this sandbox.
|
||||
</div>
|
||||
{renderRecentRules()}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return pending.map((request) => (
|
||||
<div key={request.chunkId} className="rounded-sm border border-amber-400/60 bg-amber-400/10 p-4">
|
||||
<div className="flex items-start justify-between gap-4 max-md:flex-col">
|
||||
<div className="min-w-0 space-y-2">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-xs font-mono font-semibold text-[var(--foreground)]">
|
||||
{request.endpoints.join(', ') || request.rule}
|
||||
</span>
|
||||
{request.confidence ? (
|
||||
<span className="rounded-sm border border-[var(--border-subtle)] px-1.5 py-0.5 text-[10px] text-[var(--foreground-dim)]">
|
||||
{request.confidence}
|
||||
</span>
|
||||
) : null}
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{pending.map((request) => (
|
||||
<div key={request.chunkId} className="rounded-sm border border-amber-400/60 bg-amber-400/10 p-4">
|
||||
<div className="flex items-start justify-between gap-4 max-md:flex-col">
|
||||
<div className="min-w-0 space-y-2">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-xs font-mono font-semibold text-[var(--foreground)]">
|
||||
{request.endpoints.join(', ') || request.rule}
|
||||
</span>
|
||||
{request.confidence ? (
|
||||
<span className="rounded-sm border border-[var(--border-subtle)] px-1.5 py-0.5 text-[10px] text-[var(--foreground-dim)]">
|
||||
{request.confidence}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-xs text-[var(--foreground-dim)]">{request.rationale || 'Sandbox requested a network policy rule.'}</p>
|
||||
<p className="text-[10px] font-mono text-[var(--foreground-dim)]">
|
||||
{request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2 max-md:w-full max-md:[&>button]:flex-1">
|
||||
<button
|
||||
type="button"
|
||||
disabled={grantingSandboxId === selectedSandbox.id}
|
||||
onClick={() => resolvePermissionRequest(selectedSandbox, 'approve', request.chunkId)}
|
||||
className="rounded-sm border border-[var(--nvidia-green)] bg-[var(--nvidia-green)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
|
||||
>
|
||||
Grant
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={grantingSandboxId === selectedSandbox.id}
|
||||
onClick={() => resolvePermissionRequest(selectedSandbox, 'reject', request.chunkId)}
|
||||
className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-[var(--foreground)] disabled:opacity-50"
|
||||
>
|
||||
Reject
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-[var(--foreground-dim)]">{request.rationale || 'Sandbox requested a network policy rule.'}</p>
|
||||
<p className="text-[10px] font-mono text-[var(--foreground-dim)]">
|
||||
{request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2 max-md:w-full max-md:[&>button]:flex-1">
|
||||
<button
|
||||
type="button"
|
||||
disabled={grantingSandboxId === selectedSandbox.id}
|
||||
onClick={() => resolvePermissionRequest(selectedSandbox, 'approve', request.chunkId)}
|
||||
className="rounded-sm border border-[var(--nvidia-green)] bg-[var(--nvidia-green)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
|
||||
>
|
||||
Grant
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={grantingSandboxId === selectedSandbox.id}
|
||||
onClick={() => resolvePermissionRequest(selectedSandbox, 'reject', request.chunkId)}
|
||||
className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-[var(--foreground)] disabled:opacity-50"
|
||||
>
|
||||
Reject
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
})()}
|
||||
))}
|
||||
{renderRecentRules()}
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
<ConfigurationPanel sandboxId={selectedSandbox.id} mode="existing" embedded showHeader={false} />
|
||||
</div>
|
||||
</DrawerSection>
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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<string, { Gateway?: string }>
|
||||
}
|
||||
}>
|
||||
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
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<string>) {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user