-
- {selectedSandbox.name} — TELEMETRY
-
+
toggleDrawer('operations')}
+ >
+
-
-
- {(dashboardMessage || terminalMessage) && (
-
- {dashboardMessage &&
{dashboardMessage}
}
- {terminalMessage &&
{terminalMessage}
}
-
- )}
+ {dashboardMessage && (
+
+ {dashboardMessage &&
{dashboardMessage}
}
+
+ )}
-
-
-
CPU
-
{telemetry.cpu.toFixed(1)}%
-
-
-
MEM
-
{telemetry.memory.toFixed(1)}%
-
-
-
DISK
-
{telemetry.disk.toFixed(1)}%
-
-
-
UPDATED
-
{new Date(telemetry.timestamp).toLocaleTimeString()}
+
+
+
CPU
+
{telemetry.cpu.toFixed(1)}%
+
+
+
MEM
+
{telemetry.memory.toFixed(1)}%
+
+
+
DISK
+
{telemetry.disk.toFixed(1)}%
+
+
+
UPDATED
+
{new Date(telemetry.timestamp).toLocaleTimeString()}
+
-
+
-
+
toggleDrawer('files')}
+ >
+
+
-
+
toggleDrawer('inference')}
+ >
+
+
+
+
toggleDrawer('policy')}
+ >
+
+ {(() => {
+ const feed = permissionFeeds[selectedSandbox.id]
+ const pending = feed?.pending || []
+ if (pending.length === 0) {
+ return (
+
+ No pending network permission requests for this sandbox.
+
+ )
+ }
+
+ 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}
+
+
+
+
+
+
+
+
+ ))
+ })()}
+
+
+
>
)}
>
diff --git a/app/components/Sidebar.tsx b/app/components/Sidebar.tsx
index ece0a28..2e8ad52 100644
--- a/app/components/Sidebar.tsx
+++ b/app/components/Sidebar.tsx
@@ -9,8 +9,11 @@ interface SidebarProps {
onSandboxesClick: () => void
onCreateClick: () => void
onDestroyClick: () => void
+ onTerminalClick: () => void
onSettingsClick: () => void
onExitMode: () => void
+ onLogout: () => void
+ terminalDisabled?: boolean
}
export default function Sidebar({
@@ -22,8 +25,11 @@ export default function Sidebar({
onSandboxesClick,
onCreateClick,
onDestroyClick,
+ onTerminalClick,
onSettingsClick,
onExitMode,
+ onLogout,
+ terminalDisabled = false,
}: SidebarProps) {
return (
)
}
diff --git a/app/forgot-password/page.tsx b/app/forgot-password/page.tsx
new file mode 100644
index 0000000..3396887
--- /dev/null
+++ b/app/forgot-password/page.tsx
@@ -0,0 +1,93 @@
+"use client"
+
+import { FormEvent, useState } from "react"
+import AuthShell from "../components/AuthShell"
+
+export default function ForgotPasswordPage() {
+ const [recoveryToken, setRecoveryToken] = useState("")
+ const [password, setPassword] = useState("")
+ const [confirmPassword, setConfirmPassword] = useState("")
+ const [message, setMessage] = useState("")
+ const [busy, setBusy] = useState(false)
+
+ const submit = async (event: FormEvent
) => {
+ event.preventDefault()
+ setMessage("")
+ if (password !== confirmPassword) {
+ setMessage("Passwords do not match.")
+ return
+ }
+
+ setBusy(true)
+ try {
+ const response = await fetch("/api/auth/recover", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ recoveryToken, password }),
+ })
+ const data = await response.json()
+ if (!response.ok) throw new Error(data.error || "Could not reset password.")
+ setMessage("Password reset. Redirecting...")
+ window.setTimeout(() => {
+ window.location.href = "/"
+ }, 600)
+ } catch (error) {
+ setMessage(error instanceof Error ? error.message : "Could not reset password.")
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+
+
+
+ )
+}
diff --git a/app/lib/controlAuth.ts b/app/lib/controlAuth.ts
new file mode 100644
index 0000000..f9c519e
--- /dev/null
+++ b/app/lib/controlAuth.ts
@@ -0,0 +1,105 @@
+const COOKIE_NAME = "openshell_control_session"
+const SESSION_TTL_SECONDS = 12 * 60 * 60
+
+type SessionPayload = {
+ sub: string
+ iat: number
+ exp: number
+}
+
+function base64UrlEncode(value: string) {
+ return btoa(value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "")
+}
+
+function base64UrlDecode(value: string) {
+ const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=")
+ return atob(padded)
+}
+
+function getSecret() {
+ return process.env.OPENSHELL_CONTROL_AUTH_SECRET || process.env.OPENSHELL_CONTROL_PASSWORD || ""
+}
+
+function isDisabled() {
+ return /^(1|true|yes|on)$/i.test(process.env.OPENSHELL_CONTROL_AUTH_DISABLED || "")
+}
+
+async function hmac(payload: string) {
+ const key = await crypto.subtle.importKey(
+ "raw",
+ new TextEncoder().encode(getSecret()),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign"],
+ )
+ const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payload))
+ const bytes = Array.from(new Uint8Array(signature), (byte) => String.fromCharCode(byte)).join("")
+ return base64UrlEncode(bytes)
+}
+
+function constantTimeEqual(left: string, right: string) {
+ if (left.length !== right.length) return false
+ let diff = 0
+ for (let index = 0; index < left.length; index += 1) {
+ diff |= left.charCodeAt(index) ^ right.charCodeAt(index)
+ }
+ return diff === 0
+}
+
+export function getAuthSettings() {
+ return {
+ cookieName: COOKIE_NAME,
+ ttlSeconds: SESSION_TTL_SECONDS,
+ disabled: isDisabled(),
+ configured: Boolean(process.env.OPENSHELL_CONTROL_PASSWORD || isDisabled()),
+ }
+}
+
+export async function createSessionCookieValue() {
+ const now = Math.floor(Date.now() / 1000)
+ const payload: SessionPayload = {
+ sub: "operator",
+ iat: now,
+ exp: now + SESSION_TTL_SECONDS,
+ }
+ const encodedPayload = base64UrlEncode(JSON.stringify(payload))
+ return `${encodedPayload}.${await hmac(encodedPayload)}`
+}
+
+export async function verifySessionCookieValue(value: string | undefined) {
+ const settings = getAuthSettings()
+ if (settings.disabled) return true
+ if (!settings.configured || !value) return false
+
+ const [payload, signature] = value.split(".")
+ if (!payload || !signature) return false
+ const expected = await hmac(payload)
+ if (!constantTimeEqual(signature, expected)) return false
+
+ try {
+ const parsed = JSON.parse(base64UrlDecode(payload)) as Partial
+ return typeof parsed.exp === "number" && parsed.exp > Math.floor(Date.now() / 1000)
+ } catch {
+ return false
+ }
+}
+
+export async function verifyPassword(password: string) {
+ const expected = process.env.OPENSHELL_CONTROL_PASSWORD || ""
+ if (!expected) return false
+ return constantTimeEqual(password, expected)
+}
+
+export async function verifyRecoveryToken(token: string) {
+ const expected = process.env.OPENSHELL_CONTROL_RECOVERY_TOKEN || ""
+ if (!expected) return false
+ return constantTimeEqual(token, expected)
+}
+
+export const sessionCookieOptions = {
+ httpOnly: true,
+ sameSite: "lax" as const,
+ secure: process.env.NODE_ENV === "production",
+ path: "/",
+ maxAge: SESSION_TTL_SECONDS,
+}
diff --git a/app/lib/controlAuthConfig.ts b/app/lib/controlAuthConfig.ts
new file mode 100644
index 0000000..a34b744
--- /dev/null
+++ b/app/lib/controlAuthConfig.ts
@@ -0,0 +1,43 @@
+import { randomBytes } from "node:crypto"
+import { existsSync } from "node:fs"
+import { readFile, writeFile } from "node:fs/promises"
+import path from "node:path"
+
+const ENV_PATH = path.join(process.cwd(), ".env.local")
+
+function quoteEnvValue(value: string) {
+ if (/^[A-Za-z0-9_./:@+-]+$/.test(value)) return value
+ return JSON.stringify(value)
+}
+
+async function readEnvFile() {
+ if (!existsSync(ENV_PATH)) return ""
+ return readFile(ENV_PATH, "utf8")
+}
+
+function upsertEnv(content: string, key: string, value: string) {
+ const line = `${key}=${quoteEnvValue(value)}`
+ const matcher = new RegExp(`^${key}=.*$`, "m")
+ if (matcher.test(content)) return content.replace(matcher, line)
+ return `${content.trimEnd()}${content.trim() ? "\n" : ""}${line}\n`
+}
+
+export function generateToken(bytes = 24) {
+ return randomBytes(bytes).toString("base64url")
+}
+
+export async function updateLocalAuthCredentials(password: string) {
+ const secret = generateToken(32)
+ const recoveryToken = generateToken(24)
+ let content = await readEnvFile()
+ content = upsertEnv(content, "OPENSHELL_CONTROL_PASSWORD", password)
+ content = upsertEnv(content, "OPENSHELL_CONTROL_AUTH_SECRET", secret)
+ content = upsertEnv(content, "OPENSHELL_CONTROL_RECOVERY_TOKEN", recoveryToken)
+ await writeFile(ENV_PATH, content, "utf8")
+
+ process.env.OPENSHELL_CONTROL_PASSWORD = password
+ process.env.OPENSHELL_CONTROL_AUTH_SECRET = secret
+ process.env.OPENSHELL_CONTROL_RECOVERY_TOKEN = recoveryToken
+
+ return { recoveryToken }
+}
diff --git a/app/lib/sandboxFiles.ts b/app/lib/sandboxFiles.ts
new file mode 100644
index 0000000..e963a4d
--- /dev/null
+++ b/app/lib/sandboxFiles.ts
@@ -0,0 +1,125 @@
+import { spawn } from "node:child_process"
+import path from "node:path"
+import { resolveSandboxRef } from "./openshellHost"
+
+const HOME = process.env.HOME || ""
+const OPENSHELL_BIN = process.env.OPENSHELL_BIN || `${HOME}/.local/bin/openshell`
+const HOST_PATH = [
+ `${HOME}/.local/bin`,
+ `${HOME}/.nvm/versions/node/v22.22.2/bin`,
+ `${HOME}/.nvm/versions/node/v22.22.1/bin`,
+ "/usr/local/bin",
+ "/usr/bin",
+ "/bin",
+ process.env.PATH || "",
+].filter(Boolean).join(":")
+
+const MAX_FILE_BYTES = Number.parseInt(process.env.SANDBOX_FILE_TRANSFER_MAX_BYTES || String(128 * 1024 * 1024), 10)
+const ALLOWED_ROOTS = ["/sandbox", "/tmp"]
+
+function shellQuote(value: string) {
+ return `'${value.replace(/'/g, `'\\''`)}'`
+}
+
+function sanitizeFileName(value: string) {
+ const base = path.posix.basename(value.trim() || "upload.bin")
+ return base.replace(/[^\w.@:+-]/g, "_") || "upload.bin"
+}
+
+export function normalizeSandboxPath(input: string, fallbackFileName?: string) {
+ const raw = input.trim()
+ if (!raw) throw new Error("sandbox path is required")
+ if (raw.includes("\0")) throw new Error("sandbox path contains unsupported characters")
+
+ const absolute = raw.startsWith("/") ? raw : path.posix.join("/sandbox", raw)
+ const withFileName = absolute.endsWith("/") && fallbackFileName
+ ? path.posix.join(absolute, sanitizeFileName(fallbackFileName))
+ : absolute
+ const normalized = path.posix.normalize(withFileName)
+ const allowed = ALLOWED_ROOTS.some((root) => normalized === root || normalized.startsWith(`${root}/`))
+ if (!allowed) throw new Error("sandbox path must be under /sandbox or /tmp")
+ return normalized
+}
+
+function runSandboxExec(sandboxName: string, script: string, input?: Buffer, timeoutMs = 60000) {
+ return new Promise<{ stdout: Buffer; stderr: string; code: number | null }>((resolve, reject) => {
+ const child = spawn(OPENSHELL_BIN, ["sandbox", "exec", "-n", sandboxName, "--", "sh", "-lc", script], {
+ env: {
+ ...process.env,
+ PATH: HOST_PATH,
+ OPENSHELL_GATEWAY: process.env.OPENSHELL_GATEWAY || "nemoclaw",
+ NO_COLOR: "1",
+ CLICOLOR: "0",
+ CLICOLOR_FORCE: "0",
+ },
+ stdio: ["pipe", "pipe", "pipe"],
+ })
+ const stdout: Buffer[] = []
+ let stderr = ""
+ const timer = setTimeout(() => child.kill("SIGTERM"), timeoutMs)
+
+ child.stdout.on("data", (chunk) => stdout.push(Buffer.from(chunk)))
+ child.stderr.on("data", (chunk) => { stderr += String(chunk) })
+ child.on("error", (error) => {
+ clearTimeout(timer)
+ reject(error)
+ })
+ child.on("close", (code) => {
+ clearTimeout(timer)
+ resolve({ stdout: Buffer.concat(stdout), stderr: stderr.trim(), code })
+ })
+
+ if (input) child.stdin.end(input)
+ else child.stdin.end()
+ })
+}
+
+export async function resolveSandboxName(sandboxId: string) {
+ const resolved = await resolveSandboxRef(sandboxId)
+ return resolved.name
+}
+
+export async function uploadSandboxFile(sandboxId: string, destinationPath: string, fileName: string, payload: Buffer) {
+ if (payload.byteLength > MAX_FILE_BYTES) {
+ throw new Error(`file is too large; max transfer size is ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MiB`)
+ }
+
+ const sandboxName = await resolveSandboxName(sandboxId)
+ const targetPath = normalizeSandboxPath(destinationPath, fileName)
+ const targetDir = path.posix.dirname(targetPath)
+ const script = [
+ `mkdir -p ${shellQuote(targetDir)}`,
+ `cat > ${shellQuote(targetPath)}`,
+ `chmod 0644 ${shellQuote(targetPath)}`,
+ ].join(" && ")
+ const result = await runSandboxExec(sandboxName, script, payload, 120000)
+ if (result.code !== 0) throw new Error(result.stderr || "failed to upload file to sandbox")
+
+ return {
+ sandboxName,
+ path: targetPath,
+ bytes: payload.byteLength,
+ }
+}
+
+export async function downloadSandboxFile(sandboxId: string, sourcePath: string) {
+ const sandboxName = await resolveSandboxName(sandboxId)
+ const targetPath = normalizeSandboxPath(sourcePath)
+ const statScript = `test -f ${shellQuote(targetPath)} && wc -c < ${shellQuote(targetPath)}`
+ const stat = await runSandboxExec(sandboxName, statScript, undefined, 30000)
+ if (stat.code !== 0) throw new Error(stat.stderr || "sandbox file does not exist or is not a regular file")
+ const size = Number.parseInt(stat.stdout.toString("utf8").trim(), 10)
+ if (Number.isFinite(size) && size > MAX_FILE_BYTES) {
+ throw new Error(`file is too large; max transfer size is ${Math.floor(MAX_FILE_BYTES / 1024 / 1024)} MiB`)
+ }
+
+ const result = await runSandboxExec(sandboxName, `cat ${shellQuote(targetPath)}`, undefined, 120000)
+ if (result.code !== 0) throw new Error(result.stderr || "failed to download file from sandbox")
+
+ return {
+ sandboxName,
+ path: targetPath,
+ fileName: path.posix.basename(targetPath) || "download.bin",
+ bytes: result.stdout,
+ }
+}
diff --git a/app/lib/sandboxPermissions.ts b/app/lib/sandboxPermissions.ts
new file mode 100644
index 0000000..39c9f15
--- /dev/null
+++ b/app/lib/sandboxPermissions.ts
@@ -0,0 +1,133 @@
+import { execFile } from "node:child_process"
+import { promisify } from "node:util"
+import { resolveSandboxRef } from "./openshellHost"
+
+const execFileAsync = promisify(execFile)
+const HOME = process.env.HOME || ""
+const OPENSHELL_BIN = process.env.OPENSHELL_BIN || `${HOME}/.local/bin/openshell`
+const HOST_PATH = [
+ `${HOME}/.local/bin`,
+ `${HOME}/.nvm/versions/node/v22.22.2/bin`,
+ `${HOME}/.nvm/versions/node/v22.22.1/bin`,
+ "/usr/local/bin",
+ "/usr/bin",
+ "/bin",
+ process.env.PATH || "",
+].filter(Boolean).join(":")
+
+export type SandboxNetworkRule = {
+ chunkId: string
+ status: string
+ rule: string
+ binary: string
+ confidence: string
+ rationale: string
+ endpoints: string[]
+ binaries: string[]
+}
+
+function runOpenShell(args: string[], timeout = 60000) {
+ return 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,
+ maxBuffer: 10 * 1024 * 1024,
+ })
+}
+
+function stripAnsi(value: string) {
+ return value.replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
+}
+
+function parseList(value: string) {
+ return value
+ .split(",")
+ .map((item) => item.trim())
+ .filter(Boolean)
+}
+
+function parseNetworkRules(output: string): SandboxNetworkRule[] {
+ const clean = stripAnsi(output)
+ const chunks = clean.split(/\n\s*Chunk:\s+/).slice(1)
+
+ return chunks
+ .map((chunk) => {
+ const lines = chunk.split(/\r?\n/)
+ const chunkId = lines.shift()?.trim() || ""
+ const fields = new Map()
+
+ for (const line of lines) {
+ const match = line.match(/^\s*([^:]+):\s*(.*)$/)
+ if (!match) continue
+ fields.set(match[1].trim().toLowerCase(), match[2].trim())
+ }
+
+ return {
+ chunkId,
+ status: fields.get("status") || "unknown",
+ rule: fields.get("rule") || "",
+ binary: fields.get("binary") || "",
+ confidence: fields.get("confidence") || "",
+ rationale: fields.get("rationale") || "",
+ endpoints: parseList(fields.get("endpoints") || ""),
+ binaries: parseList(fields.get("binaries") || ""),
+ }
+ })
+ .filter((rule) => rule.chunkId)
+}
+
+async function listRulesForStatus(sandboxName: string, status: "pending" | "approved" | "rejected") {
+ const { stdout } = await runOpenShell(["rule", "get", "--status", status, sandboxName], 30000)
+ return parseNetworkRules(String(stdout))
+}
+
+export async function getSandboxPermissionFeed(sandboxId: string) {
+ const resolved = await resolveSandboxRef(sandboxId)
+ const [pending, approved, rejected] = await Promise.all([
+ listRulesForStatus(resolved.name, "pending"),
+ listRulesForStatus(resolved.name, "approved").catch(() => [] as SandboxNetworkRule[]),
+ listRulesForStatus(resolved.name, "rejected").catch(() => [] as SandboxNetworkRule[]),
+ ])
+
+ return {
+ sandboxId,
+ sandboxName: resolved.name,
+ pending,
+ recent: [...pending, ...approved, ...rejected].slice(0, 8),
+ pendingCount: pending.length,
+ approvedCount: approved.length,
+ rejectedCount: rejected.length,
+ latest: pending[0] ? { status: "Pending", chunkId: pending[0].chunkId } : { status: "Ready" },
+ }
+}
+
+export async function resolveSandboxNetworkRule(sandboxId: string, action: string, chunkId: string, reason = "") {
+ if (!/^[a-f0-9-]{8,}$/i.test(chunkId)) throw new Error("invalid network rule chunk id")
+ const resolved = await resolveSandboxRef(sandboxId)
+ const command = action === "reject" ? "reject" : action === "approve" ? "approve" : ""
+ if (!command) throw new Error("unsupported permission action")
+
+ const args = ["rule", command, "--chunk-id", chunkId]
+ if (command === "reject" && reason) args.push("--reason", reason)
+ args.push(resolved.name)
+
+ const { stdout, stderr } = await runOpenShell(args, 60000)
+ const feed = await getSandboxPermissionFeed(resolved.name).catch(() => null)
+
+ return {
+ sandboxId,
+ sandboxName: resolved.name,
+ action: command,
+ chunkId,
+ stdout: String(stdout).trim(),
+ stderr: String(stderr).trim(),
+ feed,
+ }
+}
diff --git a/app/login/page.tsx b/app/login/page.tsx
new file mode 100644
index 0000000..8d42357
--- /dev/null
+++ b/app/login/page.tsx
@@ -0,0 +1,72 @@
+"use client"
+
+import { FormEvent, useEffect, useState } from "react"
+import AuthShell from "../components/AuthShell"
+
+export default function LoginPage() {
+ const [nextPath, setNextPath] = useState("/")
+ const [password, setPassword] = useState("")
+ const [message, setMessage] = useState("")
+ const [busy, setBusy] = useState(false)
+
+ useEffect(() => {
+ setNextPath(new URLSearchParams(window.location.search).get("next") || "/")
+ }, [])
+
+ const submit = async (event: FormEvent) => {
+ event.preventDefault()
+ setBusy(true)
+ setMessage("")
+
+ try {
+ const response = await fetch("/api/auth/login", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ password, next: nextPath }),
+ })
+ const data = await response.json()
+ if (!response.ok) throw new Error(data.error || "Login failed")
+ window.location.href = data.next || "/"
+ } catch (error) {
+ setMessage(error instanceof Error ? error.message : "Login failed")
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+
+
+
+ )
+}
diff --git a/app/operator-terminal/page.tsx b/app/operator-terminal/page.tsx
index baa3cf7..bb2b80b 100644
--- a/app/operator-terminal/page.tsx
+++ b/app/operator-terminal/page.tsx
@@ -73,6 +73,7 @@ function OperatorTerminalInner() {
const [terminalState, setTerminalState] = useState<'idle' | 'connecting' | 'connected' | 'error'>('idle')
const [terminalStatus, setTerminalStatus] = useState('Terminal not connected yet.')
const [liveSession, setLiveSession] = useState(null)
+ const [showRecovery, setShowRecovery] = useState(false)
const terminalContainerRef = useRef(null)
const terminalRef = useRef(null)
@@ -267,43 +268,47 @@ function OperatorTerminalInner() {
const shellHint = data?.attach?.shellHint || DEFAULT_SHELL_HINT
return (
-
-
-
+
+
+
-
Operator path
-
Operator Terminal
-
{sandboxId ? 'Live operator terminal for the selected sandbox, brokered through the dashboard-owned terminal bridge.' : 'Live operator terminal for host mode, brokered through the dashboard-owned terminal bridge.'}
-
OpenShell operator terminal
+
OpenShell Control
+
Operator Terminal
Back to Dashboard
-
+
-
Sandbox
{sandboxId || 'HOST'}
-
Dashboard Session
{dashboardSessionId.slice(0, 8)}
-
Status
{readiness.label}
{lastCheckedAt &&
Last checked {lastCheckedAt}
}
+
+ Sandbox
+ {sandboxId || 'host'}
+
+
+ Status
+ {readiness.label}
+ {lastCheckedAt && checked {lastCheckedAt}}
+
- {readiness.detail}
-
Live Dashboard Terminal
Browser terminal backed by the dashboard terminal server.
+
Live Terminal
{terminalStatus}
-
+
+
{liveSession?.sessionId ? `session ${liveSession.sessionId.slice(0, 8)}` : 'no session'}
-
-
-
Direct Attach Fallbacks
If the live dashboard terminal is degraded, these remain the authoritative escape hatches.
+ {showRecovery && (
+
+ Recovery Commands
{readiness.detail}
Preferred attach command
{aliasCommand}
@@ -312,8 +317,8 @@ function OperatorTerminalInner() {
{copyMessage && {copyMessage}
}
-
-
+
+ )}
)
diff --git a/app/page.tsx b/app/page.tsx
index e3d8790..604df05 100644
--- a/app/page.tsx
+++ b/app/page.tsx
@@ -7,6 +7,7 @@ import InferenceEndpointPanel from './components/InferenceEndpointPanel'
import { useSandboxInventory } from './hooks/useSandboxInventory'
import {
createHydrationSafeDashboardSessionState,
+ buildOperatorTerminalRoute,
loadDashboardSessionState,
persistDashboardSessionState,
updateDashboardSessionSelection,
@@ -187,6 +188,14 @@ export default function Dashboard() {
setIsCreateMode(false)
setLifecycleMessage(null)
}}
+ onTerminalClick={() => {
+ const nextUrl = buildOperatorTerminalRoute({
+ sandboxId: selectedSandbox?.id,
+ dashboardSessionId: dashboardSession.dashboardSessionId,
+ })
+ window.open(nextUrl, '_blank', 'noopener,noreferrer')
+ }}
+ terminalDisabled={!selectedSandbox}
onSettingsClick={() => {
setActiveView('settings')
setIsCreateMode(false)
@@ -198,6 +207,10 @@ export default function Dashboard() {
setIsDestroyMode(false)
clearSelection()
}}
+ onLogout={async () => {
+ await fetch('/api/auth/logout', { method: 'POST' }).catch(() => null)
+ window.location.href = '/login'
+ }}
/>
@@ -281,7 +294,6 @@ export default function Dashboard() {
) => {
+ event.preventDefault()
+ setMessage("")
+ if (password !== confirmPassword) {
+ setMessage("Passwords do not match.")
+ return
+ }
+
+ setBusy(true)
+ try {
+ const response = await fetch("/api/auth/setup", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ currentPassword, password }),
+ })
+ const data = await response.json()
+ if (!response.ok) throw new Error(data.error || "Could not update account.")
+ setMessage("Account updated. Redirecting...")
+ window.setTimeout(() => {
+ window.location.href = "/"
+ }, 600)
+ } catch (error) {
+ setMessage(error instanceof Error ? error.message : "Could not update account.")
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+
+
+
+ )
+}
diff --git a/install.sh b/install.sh
index 9de309c..ffbcc73 100755
--- a/install.sh
+++ b/install.sh
@@ -1,105 +1,188 @@
-#!/bin/bash
-# NemoClaw Dashboard Installer
-# Installs and configures the OpenShell/NemoClaw control dashboard
+#!/usr/bin/env bash
+# OpenShell Control installer
+# Development installer for the local OpenShell sandbox control dashboard.
-set -e
+set -euo pipefail
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
-NC='\033[0m' # No Color
+NC='\033[0m'
-echo -e "${GREEN}=== NemoClaw Dashboard Installer ===${NC}"
+APP_NAME="OpenShell Control"
+ENV_FILE=".env.local"
+OPEN_SHELL_CONTAINER_DEFAULT="openshell-cluster-nemoclaw"
+MIN_NODE_MAJOR=20
-# Check for required tools
-check_command() {
- if ! command -v $1 &> /dev/null; then
- echo -e "${RED}Error: $1 is required but not installed.${NC}"
- exit 1
- fi
+DO_BUILD=1
+DO_START=0
+
+usage() {
+ cat <${NC} $*"
+}
+
+warn() {
+ echo -e "${YELLOW}WARN:${NC} $*"
+}
+
+fail() {
+ echo -e "${RED}ERROR:${NC} $*" >&2
+ exit 1
+}
+
+require_command() {
+ command -v "$1" >/dev/null 2>&1 || fail "$1 is required but was not found."
+}
+
+node_major() {
+ node -p "Number(process.versions.node.split('.')[0])"
+}
+
+random_token() {
+ node -e "console.log(require('node:crypto').randomBytes(Number(process.argv[1])).toString('base64url'))" "$1"
+}
+
+upsert_env() {
+ local key="$1"
+ local value="$2"
+ touch "$ENV_FILE"
+ if grep -qE "^${key}=" "$ENV_FILE"; then
+ return
+ fi
+ printf '%s=%s\n' "$key" "$value" >> "$ENV_FILE"
+}
+
+echo -e "${GREEN}=== ${APP_NAME} Installer ===${NC}"
+echo "Development build: expect sharp edges; do not expose this UI broadly without hardening."
+echo ""
+
+require_command node
+require_command npm
+require_command docker
+
+NODE_MAJOR="$(node_major)"
+if [[ "$NODE_MAJOR" -lt "$MIN_NODE_MAJOR" ]]; then
+ fail "Node.js ${MIN_NODE_MAJOR}+ is required. Found $(node -v)."
+fi
+
+log "Node $(node -v), npm $(npm -v)"
+
+if ! docker ps >/dev/null 2>&1; then
+ fail "Docker is not reachable. Start Docker and rerun the installer."
+fi
+log "Docker is reachable: $(docker --version)"
+
+if command -v openshell >/dev/null 2>&1; then
+ log "OpenShell CLI: $(openshell --version 2>/dev/null || echo installed)"
+elif [[ -x "$HOME/.local/bin/openshell" ]]; then
+ log "OpenShell CLI: $("$HOME/.local/bin/openshell" --version 2>/dev/null || echo "$HOME/.local/bin/openshell")"
else
- echo -e "${YELLOW}Detected Linux${NC}"
- DOCKER_CMD="docker"
- OPEN_SHELL_NS="agent-sandbox-system"
+ warn "OpenShell CLI was not found on PATH or at ~/.local/bin/openshell."
+ warn "Sandbox create/delete, policy grants, terminal, and dashboard proxy features require it."
fi
-# Check if Docker is running
-echo -e "${YELLOW}Checking Docker...${NC}"
-if ! $DOCKER_CMD ps &> /dev/null; then
- echo -e "${RED}Error: Docker is not running.${NC}"
- echo "Please start Docker Desktop and try again."
- exit 1
+if docker ps --format '{{.Names}}' | grep -Eq '^openshell-cluster-'; then
+ log "OpenShell gateway container detected:"
+ docker ps --format ' {{.Names}}\t{{.Image}}\t{{.Ports}}' | grep -E 'openshell-cluster-' || true
+else
+ warn "No openshell-cluster-* Docker container is currently running."
+ warn "Install can continue, but the UI will show limited inventory until OpenShell is started."
fi
-# Check if OpenShell container is running
-echo -e "${YELLOW}Checking OpenShell cluster...${NC}"
-if ! $DOCKER_CMD ps | grep -q openshell; then
- echo -e "${RED}Error: OpenShell cluster container not found.${NC}"
- echo "Please start your OpenShell-Mark fork first:"
- echo " $DOCKER_CMD run -d --name openshell-cluster -p 8080:30051 ghcr.io/nvidia/openshell/cluster:dev"
- exit 1
-fi
-
-# Install dependencies
-echo -e "${GREEN}Installing dependencies...${NC}"
+log "Installing npm dependencies"
npm install
-# Build the dashboard
-echo -e "${GREEN}Building dashboard...${NC}"
-npm run build
-
-# Configure environment
-if [ ! -f .env.local ]; then
- echo -e "${YELLOW}Creating .env.local...${NC}"
- cat > .env.local < "$ENV_FILE" < pathname === path || pathname.startsWith(`${path}/`))
+}
+
+function isAssetPath(pathname: string) {
+ return pathname.startsWith("/_next/") || pathname.startsWith("/public/")
+}
+
+export async function middleware(request: NextRequest) {
+ const { pathname } = request.nextUrl
+ const settings = getAuthSettings()
+ if (settings.disabled || isAssetPath(pathname)) {
+ if (pathname === "/login") {
+ return NextResponse.redirect(new URL("/", request.url))
+ }
+ return NextResponse.next()
+ }
+
+ if (isPublicPath(pathname)) {
+ if (pathname === "/login" && await verifySessionCookieValue(request.cookies.get(settings.cookieName)?.value)) {
+ return NextResponse.redirect(new URL("/", request.url))
+ }
+ return NextResponse.next()
+ }
+
+ const authenticated = await verifySessionCookieValue(request.cookies.get(settings.cookieName)?.value)
+ if (authenticated) {
+ return NextResponse.next()
+ }
+
+ if (pathname.startsWith("/api/")) {
+ return NextResponse.json({ ok: false, error: "Authentication required" }, { status: 401 })
+ }
+
+ const loginUrl = new URL("/login", request.url)
+ loginUrl.searchParams.set("next", `${pathname}${request.nextUrl.search}`)
+ return NextResponse.redirect(loginUrl)
+}
+
+export const config = {
+ matcher: ["/((?!_next/static|_next/image).*)"],
+}
diff --git a/server.mjs b/server.mjs
index 5597c2d..cf489a0 100644
--- a/server.mjs
+++ b/server.mjs
@@ -1,10 +1,25 @@
import http from 'node:http'
import crypto from 'node:crypto'
+import { existsSync, readFileSync } from 'node:fs'
import net from 'node:net'
import tls from 'node:tls'
import next from 'next'
import { WebSocketServer, WebSocket } from 'ws'
+function loadLocalEnvFile(pathname) {
+ if (!existsSync(pathname)) return
+ const lines = readFileSync(pathname, 'utf8').split(/\r?\n/)
+ for (const line of lines) {
+ const trimmed = line.trim()
+ if (!trimmed || trimmed.startsWith('#')) continue
+ const match = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/)
+ if (!match || process.env[match[1]]) continue
+ process.env[match[1]] = match[2].replace(/^['"]|['"]$/g, '')
+ }
+}
+
+loadLocalEnvFile('.env.local')
+
const dev = process.env.NODE_ENV !== 'production'
const hostname = process.env.HOSTNAME || process.env.HOST || '0.0.0.0'
const port = Number(process.env.PORT || 3000)
@@ -19,6 +34,7 @@ const defaultDashboardUrl = process.env.OPENCLAW_DASHBOARD_URL || 'http://127.0.
const defaultInstanceId = 'default'
const sandboxDashboardPortBase = Number.parseInt(process.env.OPENCLAW_SANDBOX_DASHBOARD_PORT_BASE || '19000', 10)
const sandboxDashboardPortRange = 2000
+const authCookieName = 'openshell_control_session'
function now() {
return new Date().toISOString()
@@ -32,6 +48,63 @@ function logBridge(event, fields = {}) {
console.log(`[terminal-bridge] ts=${now()} event=${event}${payload ? ` ${payload}` : ''}`)
}
+function isAuthDisabled() {
+ return /^(1|true|yes|on)$/i.test(process.env.OPENSHELL_CONTROL_AUTH_DISABLED || '')
+}
+
+function getAuthSecret() {
+ return process.env.OPENSHELL_CONTROL_AUTH_SECRET || process.env.OPENSHELL_CONTROL_PASSWORD || ''
+}
+
+function base64UrlDecode(value) {
+ const normalized = value.replace(/-/g, '+').replace(/_/g, '/')
+ return Buffer.from(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '='), 'base64').toString('utf8')
+}
+
+function hmac(payload) {
+ return crypto.createHmac('sha256', getAuthSecret()).update(payload).digest('base64url')
+}
+
+function safeEqual(left, right) {
+ const leftBuffer = Buffer.from(left || '')
+ const rightBuffer = Buffer.from(right || '')
+ return leftBuffer.length === rightBuffer.length && crypto.timingSafeEqual(leftBuffer, rightBuffer)
+}
+
+function parseCookies(req) {
+ return String(req.headers.cookie || '')
+ .split(';')
+ .reduce((cookies, part) => {
+ const [rawName, ...rawValue] = part.trim().split('=')
+ if (!rawName) return cookies
+ cookies[rawName] = decodeURIComponent(rawValue.join('=') || '')
+ return cookies
+ }, {})
+}
+
+function isAuthenticatedUpgrade(req) {
+ if (isAuthDisabled()) return true
+ if (!process.env.OPENSHELL_CONTROL_PASSWORD) return false
+ const value = parseCookies(req)[authCookieName]
+ if (!value) return false
+ const [payload, signature] = value.split('.')
+ if (!payload || !signature || !safeEqual(signature, hmac(payload))) return false
+ try {
+ const parsed = JSON.parse(base64UrlDecode(payload))
+ return typeof parsed.exp === 'number' && parsed.exp > Math.floor(Date.now() / 1000)
+ } catch {
+ return false
+ }
+}
+
+function rejectUnauthorizedUpgrade(req, socket, path) {
+ logBridge('upgrade-auth-rejected', {
+ path,
+ remoteAddress: req.socket.remoteAddress || 'unknown',
+ })
+ socket.end('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\nContent-Length: 0\r\n\r\n')
+}
+
function buildTerminalUpstreamUrl(req) {
const incoming = new URL(req.url || '/', `http://${req.headers.host || `${hostname}:${port}`}`)
const upstream = new URL('/ws', `${terminalWsProtocol}//${terminalServerUrl.host}`)
@@ -455,6 +528,10 @@ clientWss.on('connection', (client, req) => {
server.on('upgrade', (req, socket, head) => {
if ((req.url || '').startsWith(terminalProxyPath)) {
+ if (!isAuthenticatedUpgrade(req)) {
+ rejectUnauthorizedUpgrade(req, socket, req.url || '/')
+ return
+ }
logBridge('upgrade-accepted', {
path: req.url || '/',
remoteAddress: req.socket.remoteAddress || 'unknown',
@@ -469,6 +546,10 @@ server.on('upgrade', (req, socket, head) => {
(req.url || '').startsWith(legacyDashboardProxyPrefix) ||
(req.url || '').startsWith(instancesProxyPrefix)
) {
+ if (!isAuthenticatedUpgrade(req)) {
+ rejectUnauthorizedUpgrade(req, socket, req.url || '/')
+ return
+ }
const { upstreamWsUrl, instanceId, controlUiOrigin } = resolveDashboardUpstream(req)
logBridge('dashboard-upgrade-accepted', {
path: req.url || '/',
@@ -496,6 +577,10 @@ dashboardWsProxyServer.on('upgrade', (req, socket, head) => {
(req.url || '').startsWith(legacyDashboardProxyPrefix) ||
(req.url || '').startsWith(instancesProxyPrefix)
) {
+ if (!isAuthenticatedUpgrade(req)) {
+ rejectUnauthorizedUpgrade(req, socket, req.url || '/')
+ return
+ }
const { upstreamWsUrl, instanceId, controlUiOrigin } = resolveDashboardUpstream(req)
logBridge('dashboard-sidecar-upgrade-accepted', {
path: req.url || '/',