"use client"
import { useEffect, useMemo, useState } from "react"
import { SECURITY_PRESETS, getSecurityPreset, type OpenShellPolicyShape, type SecurityPresetId } from "../lib/securityPresets"
type LandlockCompatibility = "best_effort" | "hard_requirement"
type EndpointProtocol = "" | "rest"
type EndpointTls = "" | "terminate" | "passthrough"
type EndpointEnforcement = "" | "enforce" | "audit"
type EndpointAccess = "" | "read-only" | "read-write" | "full"
interface NetworkRule {
method: string
path: string
}
interface NetworkEndpoint {
host: string
port: string
protocol: EndpointProtocol
tls: EndpointTls
enforcement: EndpointEnforcement
access: EndpointAccess
rules: NetworkRule[]
}
interface NetworkBinary {
path: string
}
interface NetworkPolicyBlock {
key: string
name: string
endpoints: NetworkEndpoint[]
binaries: NetworkBinary[]
}
type OpenShellPolicy = OpenShellPolicyShape
interface ConfigurationPanelProps {
sandboxId: string
mode?: 'existing' | 'create'
}
function FieldHelp({ text }: { text: string }) {
return (
?
{text}
)
}
function Badge({ children, tone }: { children: React.ReactNode; tone: "dynamic" | "static" | "danger" }) {
const cls = tone === "dynamic"
? "bg-[rgba(118,185,0,0.12)] text-[var(--nvidia-green)] border-[rgba(118,185,0,0.35)]"
: tone === "danger"
? "bg-[rgba(220,38,38,0.12)] text-red-400 border-[rgba(220,38,38,0.35)]"
: "bg-[rgba(245,158,11,0.10)] text-amber-400 border-[rgba(245,158,11,0.35)]"
return {children}
}
function TextListEditor({ label, tooltipText, value, onChange, placeholder }: {
label: string
tooltipText: string
value: string[]
onChange: (v: string[]) => void
placeholder: string
}) {
return (
)
}
const defaultPolicy: OpenShellPolicy = {
version: 1,
filesystem_policy: {
include_workdir: true,
read_only: ["/usr", "/lib", "/etc", "/proc", "/dev/urandom"],
read_write: ["/sandbox", "/tmp", "/dev/null"],
},
landlock: {
compatibility: "best_effort",
},
process: {
run_as_user: "sandbox",
run_as_group: "sandbox",
},
network_policies: {},
}
function normalizeFromApi(data: any): OpenShellPolicy {
const current = data?.currentConfig || data?.policy || data || {}
return {
version: Number(current.version ?? 1),
filesystem_policy: {
include_workdir: Boolean(current.filesystem_policy?.include_workdir ?? true),
read_only: Array.isArray(current.filesystem_policy?.read_only) ? current.filesystem_policy.read_only : defaultPolicy.filesystem_policy.read_only,
read_write: Array.isArray(current.filesystem_policy?.read_write) ? current.filesystem_policy.read_write : defaultPolicy.filesystem_policy.read_write,
},
landlock: {
compatibility: current.landlock?.compatibility === "hard_requirement" ? "hard_requirement" : "best_effort",
},
process: {
run_as_user: String(current.process?.run_as_user ?? "sandbox"),
run_as_group: String(current.process?.run_as_group ?? "sandbox"),
},
network_policies: current.network_policies && typeof current.network_policies === "object" ? current.network_policies : {},
}
}
function policyBlocksFromPolicy(policy: OpenShellPolicy): NetworkPolicyBlock[] {
return Object.entries(policy.network_policies).map(([key, value]) => ({
key,
name: value.name || key,
endpoints: (value.endpoints || []).map((ep) => ({
host: ep.host || "",
port: String(ep.port ?? "443"),
protocol: ep.protocol === "rest" ? "rest" : "",
tls: ep.tls === "terminate" || ep.tls === "passthrough" ? ep.tls : "",
enforcement: ep.enforcement === "enforce" || ep.enforcement === "audit" ? ep.enforcement : "",
access: ep.access === "read-only" || ep.access === "read-write" || ep.access === "full" ? ep.access : "",
rules: Array.isArray(ep.rules) ? ep.rules.map((r) => ({ method: r.allow?.method || "GET", path: r.allow?.path || "/**" })) : [],
})),
binaries: (value.binaries || []).map((b) => ({ path: b.path || "" })),
}))
}
function blocksToPolicy(blocks: NetworkPolicyBlock[]): OpenShellPolicy["network_policies"] {
const out: OpenShellPolicy["network_policies"] = {}
for (const block of blocks) {
const key = block.key.trim()
if (!key) continue
out[key] = {
name: block.name.trim() || key,
endpoints: block.endpoints.filter((ep) => ep.host.trim() && ep.port.trim()).map((ep) => ({
host: ep.host.trim(),
port: Number(ep.port),
...(ep.protocol ? { protocol: ep.protocol } : {}),
...(ep.tls ? { tls: ep.tls } : {}),
...(ep.enforcement ? { enforcement: ep.enforcement } : {}),
...(ep.access ? { access: ep.access } : {}),
...(!ep.access && ep.rules.length ? { rules: ep.rules.filter((r) => r.method.trim() && r.path.trim()).map((r) => ({ allow: { method: r.method.trim(), path: r.path.trim() } })) } : {}),
})),
binaries: block.binaries.filter((b) => b.path.trim()).map((b) => ({ path: b.path.trim() })),
}
}
return out
}
export default function ConfigurationPanel({ sandboxId, mode = 'existing' }: ConfigurationPanelProps) {
const [policy, setPolicy] = useState(defaultPolicy)
const [blocks, setBlocks] = useState([])
const [loading, setLoading] = useState(mode === 'existing')
const [saving, setSaving] = useState(false)
const [message, setMessage] = useState("")
const [selectedPreset, setSelectedPreset] = useState('')
useEffect(() => {
if (mode === 'create') {
setLoading(false)
return
}
let active = true
;(async () => {
try {
setLoading(true)
const res = await fetch(`/api/sandbox/${encodeURIComponent(sandboxId)}/config`, { cache: "no-store" })
const data = await res.json()
if (!res.ok) throw new Error(data.error || "Failed to fetch configuration")
const normalized = normalizeFromApi(data)
if (!active) return
setPolicy(normalized)
setBlocks(policyBlocksFromPolicy(normalized))
} catch (err) {
if (!active) return
setMessage(err instanceof Error ? err.message : "Failed to fetch configuration")
} finally {
if (active) setLoading(false)
}
})()
return () => { active = false }
}, [sandboxId, mode])
const assembledPolicy = useMemo(() => ({ ...policy, network_policies: blocksToPolicy(blocks) }), [policy, blocks])
const activePreset = selectedPreset ? getSecurityPreset(selectedPreset) : null
const showDangerWarning = activePreset?.id === 'spicy' || activePreset?.id === 'ultra-lobster'
function applyPreset(presetId: SecurityPresetId) {
const preset = getSecurityPreset(presetId)
if (!preset) return
setSelectedPreset(presetId)
setPolicy(preset.policy)
setBlocks(policyBlocksFromPolicy(preset.policy))
setMessage(`${preset.label} applied. Review before saving.${preset.id === 'spicy' || preset.id === 'ultra-lobster' ? ' Warning: this preset is intentionally permissive.' : ''}`)
}
async function savePolicy() {
try {
setSaving(true)
setMessage("")
const res = await fetch(`/api/sandbox/${encodeURIComponent(sandboxId)}/config`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ policy: assembledPolicy, preset: selectedPreset || null, mode }),
})
const data = await res.json()
if (!res.ok) throw new Error(data.error || "Failed to save policy")
setMessage(mode === 'create'
? 'Preset and policy prepared for new sandbox creation. Static sections will apply at create time.'
: 'Policy saved. Dynamic network policy can apply live; static sections require sandbox recreation.')
} catch (err) {
setMessage(err instanceof Error ? err.message : "Failed to save policy")
} finally {
setSaving(false)
}
}
function updateBlock(idx: number, next: NetworkPolicyBlock) {
setBlocks((prev) => prev.map((b, i) => (i === idx ? next : b)))
}
function addBlock() {
setBlocks((prev) => [...prev, {
key: `policy_${prev.length + 1}`,
name: `policy-${prev.length + 1}`,
endpoints: [{ host: "", port: "443", protocol: "", tls: "", enforcement: "", access: "read-only", rules: [] }],
binaries: [{ path: "" }],
}])
}
return (
{sandboxId} — {mode === 'create' ? 'NEW SANDBOX PRESET + POLICY' : 'OPENSHELL POLICY'}
Static / Recreate Required
Dynamic / Apply Live
{loading ?
Loading policy…
: (
Security Presets
Use a canned profile for new sandboxes or switch an existing sandbox policy baseline on the fly.
{activePreset && (
{activePreset.label}
{activePreset.danger.replace('-', ' ')}
{showDangerWarning && Dangerous / Permissive}
{activePreset.summary}
{(activePreset.id === 'spicy' || activePreset.id === 'ultra-lobster') && (
Warning: {activePreset.label} may be dangerous due to its permissive security stance. Use only on trusted lab workloads.
)}
Preset exec allowlist
{activePreset.execAllowlist.paths.join('\n')}
)}
Network Policies
Dynamic
Named endpoint + binary allowlists. These are hot-reloadable on running sandboxes via policy updates.
{blocks.length === 0 &&
No network policies defined.
}
{blocks.map((block, idx) => (
Endpoints
{block.endpoints.map((ep, epIdx) => (
{ const next = [...block.endpoints]; next[epIdx] = { ...ep, host: e.target.value }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono" />
{ const next = [...block.endpoints]; next[epIdx] = { ...ep, port: e.target.value }; updateBlock(idx, { ...block, endpoints: next }) }} className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-2 py-2 text-xs font-mono" />
))}
Binaries
{block.binaries.map((bin, binIdx) => (
{ const next = [...block.binaries]; next[binIdx] = { path: e.target.value }; updateBlock(idx, { ...block, binaries: next }) }} className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono" />))}
))}
Policy JSON Preview
{JSON.stringify(assembledPolicy, null, 2)}
{message && {message}
}
)}
)
}