From ad8e25c0563e39e72c31cb875ed65830ad479a4c Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 24 Apr 2026 20:52:44 +0000 Subject: [PATCH] Add OpenShell Control auth and installer --- .env.example | 7 + README.md | 317 ++++++++++---- app/api/auth/login/route.ts | 24 + app/api/auth/logout/route.ts | 15 + app/api/auth/recover/route.ts | 27 ++ app/api/auth/setup/route.ts | 44 ++ .../[sandboxId]/files/download/route.ts | 34 ++ .../sandbox/[sandboxId]/files/upload/route.ts | 29 ++ .../sandbox/[sandboxId]/permissions/route.ts | 41 ++ app/components/AuthShell.tsx | 30 ++ app/components/ConfigurationPanel.tsx | 25 +- app/components/SandboxFilesPanel.tsx | 160 +++++++ app/components/SandboxInferencePanel.tsx | 59 ++- app/components/SandboxList.tsx | 411 ++++++++++++++---- app/components/Sidebar.tsx | 39 ++ app/forgot-password/page.tsx | 93 ++++ app/lib/controlAuth.ts | 105 +++++ app/lib/controlAuthConfig.ts | 43 ++ app/lib/sandboxFiles.ts | 125 ++++++ app/lib/sandboxPermissions.ts | 133 ++++++ app/login/page.tsx | 72 +++ app/operator-terminal/page.tsx | 43 +- app/page.tsx | 15 +- app/setup-account/page.tsx | 92 ++++ install.sh | 229 ++++++---- middleware.ts | 58 +++ server.mjs | 85 ++++ 27 files changed, 2057 insertions(+), 298 deletions(-) create mode 100644 app/api/auth/login/route.ts create mode 100644 app/api/auth/logout/route.ts create mode 100644 app/api/auth/recover/route.ts create mode 100644 app/api/auth/setup/route.ts create mode 100644 app/api/sandbox/[sandboxId]/files/download/route.ts create mode 100644 app/api/sandbox/[sandboxId]/files/upload/route.ts create mode 100644 app/api/sandbox/[sandboxId]/permissions/route.ts create mode 100644 app/components/AuthShell.tsx create mode 100644 app/components/SandboxFilesPanel.tsx create mode 100644 app/forgot-password/page.tsx create mode 100644 app/lib/controlAuth.ts create mode 100644 app/lib/controlAuthConfig.ts create mode 100644 app/lib/sandboxFiles.ts create mode 100644 app/lib/sandboxPermissions.ts create mode 100644 app/login/page.tsx create mode 100644 app/setup-account/page.tsx create mode 100644 middleware.ts diff --git a/.env.example b/.env.example index 8cd78e3..908ee0d 100644 --- a/.env.example +++ b/.env.example @@ -10,6 +10,13 @@ OPEN_SHELL_CONTAINER=openshell-cluster-openshell # Dashboard port NEXT_PUBLIC_DASHBOARD_PORT=3000 +# Simple operator login for the dashboard +# Generate both values before exposing the UI beyond localhost. +OPENSHELL_CONTROL_PASSWORD=change-this-password +OPENSHELL_CONTROL_AUTH_SECRET=change-this-random-32-byte-secret +OPENSHELL_CONTROL_RECOVERY_TOKEN=change-this-local-recovery-token +# OPENSHELL_CONTROL_AUTH_DISABLED=false + # API endpoints NEXT_PUBLIC_API_BASE=/api diff --git a/README.md b/README.md index f02a8ad..6e7f5c2 100644 --- a/README.md +++ b/README.md @@ -1,134 +1,279 @@ -# OpenShell/NemoClaw Dashboard +# OpenShell Control -A web-based control plane dashboard for managing OpenShell and NemoClaw instances, with live telemetry and one-click actions. +OpenShell Control is a local, development-stage dashboard for operating OpenShell sandboxes and their OpenClaw gateway dashboards. + +It is currently built for active development and lab use. It includes a simple password gate, but it is not a hardened production control plane yet. + +## Current Status + +- Development software. Expect fast-moving APIs and sharp edges. +- Designed to run near the OpenShell gateway host. +- Uses local shell/CLI access for sandbox lifecycle, network policy grants, file transfer, and OpenClaw dashboard proxying. +- Authentication is intentionally simple so a future dev team can replace it with a real identity provider. ## Features -- **Live Telemetry**: Real-time CPU, memory, disk, and GPU monitoring -- **One-Click Actions**: Quick actions to start/stop sandbox, create NemoClaw instances, and switch models -- **Configuration Management**: Update OpenShell, NemoClaw, and Ollama settings -- **Model Switcher**: Select and switch between available Ollama models -- **Local-first**: Runs entirely on your local machine +- View live OpenShell sandbox inventory. +- Create, destroy, and restart sandboxes. +- Launch a sandbox-specific OpenClaw Gateway Dashboard through the local proxy. +- Approve or reject pending OpenShell network permission requests. +- Configure per-sandbox inference routes for Ollama, NIM, vLLM, and external endpoints. +- Poll Ollama for available models. +- Upload files into sandboxes and download files back out. +- Open an operator terminal for the selected sandbox. +- Simple local login, setup account, forgot password, and recovery token flow. -## Installation +## Version Requirements -### Quick Install (Recommended) +Tested on the current development host with: -Run the installer script which checks prerequisites and sets up everything: +- Ubuntu/Linux host +- Node.js `v22.22.2` +- npm `10.9.7` +- Docker `29.1.3` +- OpenShell CLI `0.0.24` +- OpenShell cluster image `ghcr.io/nvidia/openshell/cluster:0.0.24` + +Minimum expected versions: + +- Node.js `20+` +- npm `10+` +- Docker `24+` +- OpenShell CLI and gateway compatible with OpenShell `0.0.24` + +The app uses Next.js `14.2.15`, React `18.3.1`, TypeScript, Tailwind CSS, `ws`, and `node-pty`. + +## Prerequisites + +Install and verify: + +```bash +node -v +npm -v +docker ps +openshell --version +``` + +OpenShell must already be installed and able to reach its gateway. On this host the active gateway metadata lives under: + +```bash +~/.config/openshell/gateways/ +``` + +The installer does not create an OpenShell gateway for you. Start or connect OpenShell first, then install this dashboard. + +## Installer + +From the repository root: ```bash ./install.sh ``` -The installer will: -- ✅ Verify Node.js, npm, and Docker are installed -- ✅ Check that your OpenShell-Mark container is running -- ✅ Install npm dependencies -- ✅ Build the dashboard -- ✅ Create `.env.local` configuration file +The installer: -### Manual Install +- checks Node, npm, Docker, and OpenShell CLI availability; +- installs npm dependencies; +- creates `.env.local` if needed; +- generates a local dashboard password, signing secret, and recovery token if they are missing; +- runs `npm run build` as a verification step; +- removes `.next` afterward so the development server starts cleanly. + +Options: -1. Navigate to the project directory: ```bash -cd nemo-shell-dashboard +./install.sh --no-build +./install.sh --start +./install.sh --help ``` -2. Install dependencies: +After install, read the generated local password from: + ```bash -npm install +grep OPENSHELL_CONTROL_PASSWORD .env.local ``` -## Prerequisites +## Run -- **Node.js** 18+ -- **npm** 9+ -- **Docker** (Docker Desktop on Mac, or native Docker on Linux) -- **OpenShell-Mark fork running**: `ghcr.io/nvidia/openshell/cluster:dev` - -## Running the Dashboard - -After running `./install.sh`: - -1. Start the development server: ```bash npm run dev ``` -2. Open your browser and navigate to: -``` +Open: + +```text http://localhost:3000 ``` -> **Important**: Make sure your OpenShell-Mark container is running before starting the dashboard! +Default ports: + +- `3000`: dashboard HTTP server +- `3001`: OpenClaw dashboard websocket sidecar +- `3011`: operator terminal upstream + +## Authentication + +This project currently uses a simple local password and signed HTTP-only cookie. + +Configuration keys: -### On Mac ```bash -# Start OpenShell first -/Applications/Docker.app/Contents/Resources/bin/docker run -d --name openshell-cluster -p 8080:30051 ghcr.io/nvidia/openshell/cluster:dev +OPENSHELL_CONTROL_PASSWORD=... +OPENSHELL_CONTROL_AUTH_SECRET=... +OPENSHELL_CONTROL_RECOVERY_TOKEN=... +``` -# Then start the dashboard +Pages: + +- `/login` +- `/setup-account` +- `/forgot-password` + +There is no email sender. Forgot-password uses `OPENSHELL_CONTROL_RECOVERY_TOKEN` from `.env.local`, which means it is a host-admin recovery flow. Anyone who can read `.env.local` can reset the dashboard password. + +After changing `.env.local`, restart the server: + +```bash +pkill -f 'node server.mjs|npm run dev' || true npm run dev ``` -### On Linux -```bash -# Start OpenShell first -docker run -d --name openshell-cluster -p 8080:30051 ghcr.io/nvidia/openshell/cluster:dev +## OpenShell And OpenClaw Notes -# Then start the dashboard +The dashboard shells out to the OpenShell CLI for several operations: + +- `openshell list` +- `openshell sandbox exec` +- `openshell sandbox delete` +- `openshell rule get` +- `openshell rule approve` +- `openshell rule reject` + +OpenClaw dashboard access is loopback-only inside the host/sandbox context, so the UI uses local proxy routes: + +- `/api/openshell/dashboard/proxy` +- `/api/openshell/instances/[instanceId]/dashboard/proxy` + +The custom server in `server.mjs` also handles websocket upgrades for: + +- operator terminal websocket traffic; +- OpenClaw dashboard websocket traffic. + +Those upgrade paths are protected by the same auth cookie as the HTTP routes. + +## Inference Endpoints + +Inference endpoint configuration is development-stage. + +The UI supports per-sandbox route profiles and can apply them live to OpenClaw where possible. Depending on the sandbox and provider, changes may require a sandbox restart to fully take effect inside the container. + +Supported provider categories in the UI: + +- Ollama +- NVIDIA NIM +- vLLM +- external HTTP-compatible endpoints + +## File Transfer + +The file transfer UI is scoped to safe sandbox paths: + +- `/sandbox` +- `/tmp` + +The default max transfer size is `128 MiB`. Override with: + +```bash +SANDBOX_FILE_TRANSFER_MAX_BYTES=134217728 +``` + +## Development Commands + +```bash +npm run dev +npm run lint +npx tsc --noEmit +npm run build +``` + +After running `npm run build` during development, restart cleanly: + +```bash +pkill -f 'node server.mjs|npm run dev' || true +rm -rf .next npm run dev ``` ## Configuration -The dashboard will attempt to connect to: +Copy or edit `.env.local`: -- **OpenShell**: `http://localhost:8080` -- **Ollama**: `http://localhost:11434` - -You can update these URLs in the configuration panel at the top of the dashboard. - -## API Endpoints - -The dashboard provides the following API endpoints (all mocked for development): - -- `GET /api/telemetry` - Get system telemetry -- `GET /api/config/openshell` - Get OpenShell configuration -- `POST /api/config/openshell` - Update OpenShell configuration -- `GET /api/config/nemoclaw` - Get NemoClaw configuration -- `POST /api/config/nemoclaw` - Update NemoClaw configuration -- `GET /api/config/ollama` - Get Ollama configuration -- `POST /api/config/ollama` - Update Ollama configuration -- `POST /api/actions/sandbox-start` - Start the sandbox -- `POST /api/actions/sandbox-stop` - Stop the sandbox -- `POST /api/actions/nemoclaw-create` - Create a NemoClaw instance -- `POST /api/actions/model-switch` - Switch to a different model - -## Development - -This project uses: -- **Next.js 14** - React framework with App Router -- **TypeScript** - Type safety -- **Tailwind CSS** - Utility-first styling -- **React Use** - Custom hooks -- **Zustand** - State management -- **Axios** - HTTP client - -## Production Build - -Build the project for production: ```bash -npm run build -npm start +cp .env.example .env.local ``` -## Notes +Common keys: -- This is a development prototype. In production, you'll need to connect to real OpenShell and Ollama APIs. -- All API endpoints are currently mocked for demonstration purposes. -- Telemetry data is randomly generated for testing purposes. +```bash +NEXT_PUBLIC_DASHBOARD_PORT=3000 +NEXT_PUBLIC_API_BASE=/api +NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS=true +OPEN_SHELL_CONTAINER=openshell-cluster-nemoclaw +OPENSHELL_GATEWAY=nemoclaw +OPENSHELL_CONTROL_PASSWORD=change-this-password +OPENSHELL_CONTROL_AUTH_SECRET=change-this-random-secret +OPENSHELL_CONTROL_RECOVERY_TOKEN=change-this-recovery-token +``` + +## Security Limitations + +This is not production hardened. + +Known limitations: + +- single shared local password; +- no user accounts or roles; +- no email reset flow; +- no rate limiting; +- no audit log persistence beyond process/container logs; +- local recovery token can reset the password; +- assumes a trusted operator host and trusted local filesystem. + +Before exposing this outside a trusted lab network, replace auth with a real identity provider, add role-based access control, add audit logging, use TLS, and review every shell-out path. + +## Troubleshooting + +Check OpenShell: + +```bash +openshell --version +openshell list +docker ps | grep openshell +``` + +Check auth: + +```bash +grep OPENSHELL_CONTROL_PASSWORD .env.local +grep OPENSHELL_CONTROL_RECOVERY_TOKEN .env.local +``` + +Check dashboard: + +```bash +npm run lint +npx tsc --noEmit +npm run build +``` + +If the UI behaves oddly after a production build: + +```bash +pkill -f 'node server.mjs|npm run dev' || true +rm -rf .next +npm run dev +``` ## License -MIT \ No newline at end of file +Internal development prototype. Add the appropriate license before distribution. diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.ts new file mode 100644 index 0000000..e9959c3 --- /dev/null +++ b/app/api/auth/login/route.ts @@ -0,0 +1,24 @@ +import { NextRequest, NextResponse } from "next/server" +import { createSessionCookieValue, getAuthSettings, sessionCookieOptions, verifyPassword } from "@/app/lib/controlAuth" + +export async function POST(request: NextRequest) { + const settings = getAuthSettings() + if (!settings.configured) { + return NextResponse.json({ + ok: false, + error: "Dashboard auth is not configured. Set OPENSHELL_CONTROL_PASSWORD and restart the dashboard.", + }, { status: 503 }) + } + + const body = await request.json().catch(() => ({})) + const password = typeof body?.password === "string" ? body.password : "" + const nextPath = typeof body?.next === "string" && body.next.startsWith("/") ? body.next : "/" + + if (!await verifyPassword(password)) { + return NextResponse.json({ ok: false, error: "Invalid password" }, { status: 401 }) + } + + const response = NextResponse.json({ ok: true, next: nextPath }) + response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions) + return response +} diff --git a/app/api/auth/logout/route.ts b/app/api/auth/logout/route.ts new file mode 100644 index 0000000..70db2d2 --- /dev/null +++ b/app/api/auth/logout/route.ts @@ -0,0 +1,15 @@ +import { NextResponse } from "next/server" +import { getAuthSettings } from "@/app/lib/controlAuth" + +export async function POST() { + const settings = getAuthSettings() + const response = NextResponse.json({ ok: true }) + response.cookies.set(settings.cookieName, "", { + httpOnly: true, + sameSite: "lax", + secure: process.env.NODE_ENV === "production", + path: "/", + maxAge: 0, + }) + return response +} diff --git a/app/api/auth/recover/route.ts b/app/api/auth/recover/route.ts new file mode 100644 index 0000000..3193eb8 --- /dev/null +++ b/app/api/auth/recover/route.ts @@ -0,0 +1,27 @@ +import { NextRequest, NextResponse } from "next/server" +import { createSessionCookieValue, getAuthSettings, sessionCookieOptions, verifyRecoveryToken } from "@/app/lib/controlAuth" +import { updateLocalAuthCredentials } from "@/app/lib/controlAuthConfig" + +export async function POST(request: NextRequest) { + const body = await request.json().catch(() => ({})) + const token = typeof body?.recoveryToken === "string" ? body.recoveryToken : "" + const password = typeof body?.password === "string" ? body.password : "" + + if (password.length < 8) { + return NextResponse.json({ ok: false, error: "Password must be at least 8 characters." }, { status: 400 }) + } + + if (!await verifyRecoveryToken(token)) { + return NextResponse.json({ ok: false, error: "Invalid recovery token." }, { status: 401 }) + } + + const result = await updateLocalAuthCredentials(password) + const settings = getAuthSettings() + const response = NextResponse.json({ + ok: true, + recoveryToken: result.recoveryToken, + note: "Password reset. Save the new recovery token from .env.local.", + }) + response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions) + return response +} diff --git a/app/api/auth/setup/route.ts b/app/api/auth/setup/route.ts new file mode 100644 index 0000000..feff8fe --- /dev/null +++ b/app/api/auth/setup/route.ts @@ -0,0 +1,44 @@ +import { NextRequest, NextResponse } from "next/server" +import { + createSessionCookieValue, + getAuthSettings, + sessionCookieOptions, + verifyPassword, + verifyRecoveryToken, + verifySessionCookieValue, +} from "@/app/lib/controlAuth" +import { updateLocalAuthCredentials } from "@/app/lib/controlAuthConfig" + +function validPassword(password: string) { + return password.length >= 8 +} + +export async function POST(request: NextRequest) { + const settings = getAuthSettings() + const body = await request.json().catch(() => ({})) + const password = typeof body?.password === "string" ? body.password : "" + const currentPassword = typeof body?.currentPassword === "string" ? body.currentPassword : "" + const recoveryToken = typeof body?.recoveryToken === "string" ? body.recoveryToken : "" + + if (!validPassword(password)) { + return NextResponse.json({ ok: false, error: "Password must be at least 8 characters." }, { status: 400 }) + } + + const signedIn = await verifySessionCookieValue(request.cookies.get(settings.cookieName)?.value) + const currentPasswordOk = currentPassword ? await verifyPassword(currentPassword) : false + const recoveryOk = recoveryToken ? await verifyRecoveryToken(recoveryToken) : false + const firstRun = !settings.configured + + if (!firstRun && !signedIn && !currentPasswordOk && !recoveryOk) { + return NextResponse.json({ ok: false, error: "Current password or recovery token required." }, { status: 401 }) + } + + const result = await updateLocalAuthCredentials(password) + const response = NextResponse.json({ + ok: true, + recoveryToken: result.recoveryToken, + note: "Password updated. Save the new recovery token from .env.local.", + }) + response.cookies.set(settings.cookieName, await createSessionCookieValue(), sessionCookieOptions) + return response +} diff --git a/app/api/sandbox/[sandboxId]/files/download/route.ts b/app/api/sandbox/[sandboxId]/files/download/route.ts new file mode 100644 index 0000000..9dee173 --- /dev/null +++ b/app/api/sandbox/[sandboxId]/files/download/route.ts @@ -0,0 +1,34 @@ +import { NextResponse } from "next/server" +import { downloadSandboxFile } from "@/app/lib/sandboxFiles" + +function contentDisposition(fileName: string) { + const fallback = fileName.replace(/[^\w.-]/g, "_") || "download.bin" + return `attachment; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(fileName)}` +} + +export async function GET( + request: Request, + { params }: { params: Promise<{ sandboxId: string }> } +) { + try { + const { sandboxId } = await params + const requestUrl = new URL(request.url) + const sourcePath = requestUrl.searchParams.get("path") || "" + const downloaded = await downloadSandboxFile(sandboxId, sourcePath) + + return new NextResponse(new Uint8Array(downloaded.bytes), { + status: 200, + headers: { + "cache-control": "no-store", + "content-disposition": contentDisposition(downloaded.fileName), + "content-length": String(downloaded.bytes.byteLength), + "content-type": "application/octet-stream", + "x-sandbox-name": downloaded.sandboxName, + "x-sandbox-path": downloaded.path, + }, + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to download file" + return NextResponse.json({ ok: false, error: message }, { status: /required|path|large|exist/.test(message) ? 400 : 500 }) + } +} diff --git a/app/api/sandbox/[sandboxId]/files/upload/route.ts b/app/api/sandbox/[sandboxId]/files/upload/route.ts new file mode 100644 index 0000000..edfa05f --- /dev/null +++ b/app/api/sandbox/[sandboxId]/files/upload/route.ts @@ -0,0 +1,29 @@ +import { NextResponse } from "next/server" +import { uploadSandboxFile } from "@/app/lib/sandboxFiles" + +export async function POST( + request: Request, + { params }: { params: Promise<{ sandboxId: string }> } +) { + try { + const { sandboxId } = await params + const form = await request.formData() + const file = form.get("file") + const rawPath = form.get("path") + if (!(file instanceof File)) throw new Error("file is required") + const destinationPath = typeof rawPath === "string" && rawPath.trim() + ? rawPath.trim() + : `/sandbox/${file.name}` + const payload = Buffer.from(await file.arrayBuffer()) + const uploaded = await uploadSandboxFile(sandboxId, destinationPath, file.name, payload) + + return NextResponse.json({ + ok: true, + uploaded, + note: `Uploaded ${file.name} to ${uploaded.path}.`, + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to upload file" + return NextResponse.json({ ok: false, error: message }, { status: /required|path|large|exist/.test(message) ? 400 : 500 }) + } +} diff --git a/app/api/sandbox/[sandboxId]/permissions/route.ts b/app/api/sandbox/[sandboxId]/permissions/route.ts new file mode 100644 index 0000000..4f3ce73 --- /dev/null +++ b/app/api/sandbox/[sandboxId]/permissions/route.ts @@ -0,0 +1,41 @@ +import { NextResponse } from "next/server" +import { getSandboxPermissionFeed, resolveSandboxNetworkRule } from "@/app/lib/sandboxPermissions" + +export async function GET( + _request: Request, + { params }: { params: Promise<{ sandboxId: string }> } +) { + try { + const { sandboxId } = await params + const feed = await getSandboxPermissionFeed(sandboxId) + return NextResponse.json({ + ok: true, + feed, + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to read permission feed" + return NextResponse.json({ ok: false, error: message }, { status: 500 }) + } +} + +export async function POST( + request: Request, + { params }: { params: Promise<{ sandboxId: string }> } +) { + try { + const { sandboxId } = await params + const body = await request.json() + const action = typeof body?.action === "string" ? body.action : "" + const chunkId = typeof body?.chunkId === "string" ? body.chunkId : "" + const reason = typeof body?.reason === "string" ? body.reason : "" + const result = await resolveSandboxNetworkRule(sandboxId, action, chunkId, reason) + return NextResponse.json({ + ok: true, + result, + note: `Network rule ${result.action === "approve" ? "approved" : "rejected"} for ${result.sandboxName}.`, + }) + } catch (error) { + const message = error instanceof Error ? error.message : "Failed to resolve permission request" + return NextResponse.json({ ok: false, error: message }, { status: /unsupported|invalid/.test(message) ? 400 : 500 }) + } +} diff --git a/app/components/AuthShell.tsx b/app/components/AuthShell.tsx new file mode 100644 index 0000000..c765f14 --- /dev/null +++ b/app/components/AuthShell.tsx @@ -0,0 +1,30 @@ +"use client" + +import type { ReactNode } from "react" + +export default function AuthShell({ + title, + description, + children, +}: { + title: string + description: string + children: ReactNode +}) { + return ( +
+
+
+
+ +
+

{title}

+

{description}

+
+ {children} +
+
+ ) +} diff --git a/app/components/ConfigurationPanel.tsx b/app/components/ConfigurationPanel.tsx index 2a44cb3..fc73bf1 100644 --- a/app/components/ConfigurationPanel.tsx +++ b/app/components/ConfigurationPanel.tsx @@ -27,6 +27,8 @@ interface ConfigurationPanelProps { sandboxId: string mode?: 'existing' | 'create' onCreateSuccess?: (sandboxId: string) => void | Promise + embedded?: boolean + showHeader?: boolean } function FieldHelp({ text }: { text: string }) { @@ -74,7 +76,7 @@ function blocksToPolicy(blocks: NetworkPolicyBlock[]): OpenShellPolicy["network_ return out } -export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCreateSuccess }: ConfigurationPanelProps) { +export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCreateSuccess, embedded = false, showHeader = true }: ConfigurationPanelProps) { const [policy, setPolicy] = useState(defaultPolicy) const [blocks, setBlocks] = useState([]) const [loading, setLoading] = useState(mode === 'existing') @@ -153,21 +155,24 @@ export default function ConfigurationPanel({ sandboxId, mode = 'existing', onCre 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 ( -
-
-

- {mode === 'create' ? 'New Sandbox' : `${sandboxId} — OpenShell Policy`} -

- -
+
+ {showHeader && ( +
+

+ {mode === 'create' ? 'New Sandbox' : `${sandboxId} - OpenShell Policy`} +

+ +
+ )} {loading ?
Loading policy…
:
{mode === 'create' &&
Create Sandbox

Choose a template and enter a sandbox name.

{blueprints.map((bp) => )}
setSandboxName(e.target.value)} placeholder={selectedBlueprint === 'nemoclaw-blueprint' ? 'my-assistant' : 'custom-sandbox'} className="mt-2 w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)]" />
{activeBlueprint?.supportsTailscale && }{enableTailscale &&
Tailscale-enabled creation requires NVIDIA_API_KEY in the dashboard process environment.
}
}
Security Presets

Use a canned profile for new sandboxes or switch an existing sandbox policy baseline on the fly.

{activePreset &&
{activePreset.label}

{activePreset.summary}

}
Filesystem Policy
Static
setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_only: v } })} placeholder="/usr\n/lib\n/etc" /> setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_write: v } })} placeholder="/sandbox\n/tmp" />
Network Policies
Dynamic
{mode === 'existing' &&
Policy JSON
{JSON.stringify(assembledPolicy, null, 2)}
} + {!showHeader && } {message &&
{message}
}
}
diff --git a/app/components/SandboxFilesPanel.tsx b/app/components/SandboxFilesPanel.tsx new file mode 100644 index 0000000..71aafcd --- /dev/null +++ b/app/components/SandboxFilesPanel.tsx @@ -0,0 +1,160 @@ +"use client" + +import { useMemo, useState } from "react" +import type { SandboxInventoryItem } from "../hooks/useSandboxInventory" + +export default function SandboxFilesPanel({ + sandbox, + embedded = false, + showHeader = true, +}: { + sandbox: SandboxInventoryItem + embedded?: boolean + showHeader?: boolean +}) { + const [selectedFile, setSelectedFile] = useState(null) + const [uploadPath, setUploadPath] = useState("/sandbox/") + const [downloadPath, setDownloadPath] = useState("/sandbox/") + const [busy, setBusy] = useState<"upload" | "download" | null>(null) + const [message, setMessage] = useState("") + + const suggestedUploadPath = useMemo(() => { + if (!selectedFile) return uploadPath + return uploadPath.endsWith("/") ? `${uploadPath}${selectedFile.name}` : uploadPath + }, [selectedFile, uploadPath]) + + async function uploadFile() { + if (!selectedFile || busy) return + try { + setBusy("upload") + setMessage("") + const form = new FormData() + form.set("file", selectedFile) + form.set("path", uploadPath) + 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) + } catch (error) { + setMessage(error instanceof Error ? error.message : "Failed to upload file") + } finally { + setBusy(null) + } + } + + async function downloadFile() { + if (!downloadPath.trim() || busy) return + try { + setBusy("download") + setMessage("") + const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/files/download?${new URLSearchParams({ path: downloadPath.trim() })}`) + if (!response.ok) { + const data = await response.json().catch(() => ({})) + throw new Error(data.error || "Failed to download file") + } + + const blob = await response.blob() + const contentDisposition = response.headers.get("content-disposition") || "" + const fileName = decodeURIComponent(contentDisposition.match(/filename\*=UTF-8''([^;]+)/)?.[1] || "") + || contentDisposition.match(/filename="([^"]+)"/)?.[1] + || downloadPath.split("/").filter(Boolean).pop() + || "download.bin" + const url = window.URL.createObjectURL(blob) + const anchor = document.createElement("a") + anchor.href = url + anchor.download = fileName + document.body.appendChild(anchor) + anchor.click() + anchor.remove() + window.URL.revokeObjectURL(url) + setMessage(`Downloaded ${downloadPath.trim()}.`) + } catch (error) { + setMessage(error instanceof Error ? error.message : "Failed to download file") + } finally { + setBusy(null) + } + } + + return ( +
+ {showHeader && ( +
+
+

+ {sandbox.name} - FILE TRANSFER +

+

+ Move files through scoped sandbox paths. +

+
+
+ )} + +
+
+
+
Upload
+

Destination must be under /sandbox or /tmp.

+
+ setSelectedFile(event.target.files?.[0] || 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)]" + /> +
+ + setUploadPath(event.target.value)} + placeholder="/sandbox/file.txt" + className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)] focus:outline-none focus:border-[var(--nvidia-green)]" + /> + {selectedFile && ( +

Target: {suggestedUploadPath}

+ )} +
+ +
+ +
+
+
Download
+

Enter a regular file path under /sandbox or /tmp.

+
+
+ + setDownloadPath(event.target.value)} + placeholder="/sandbox/file.txt" + className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background)] px-3 py-2 text-xs font-mono text-[var(--foreground)] focus:outline-none focus:border-[var(--nvidia-green)]" + /> +
+ +
+
+ + {message && ( +
+ {message} +
+ )} +
+ ) +} diff --git a/app/components/SandboxInferencePanel.tsx b/app/components/SandboxInferencePanel.tsx index 620a394..6d36a22 100644 --- a/app/components/SandboxInferencePanel.tsx +++ b/app/components/SandboxInferencePanel.tsx @@ -54,7 +54,15 @@ function dedupeRoutes(routes: SandboxInferenceRoute[]) { .map((route) => [route.id || routeKey(route), { ...route, id: route.id || routeKey(route) }])).values()) } -export default function SandboxInferencePanel({ sandbox }: { sandbox: SandboxInventoryItem }) { +export default function SandboxInferencePanel({ + sandbox, + embedded = false, + showHeader = true, +}: { + sandbox: SandboxInventoryItem + embedded?: boolean + showHeader?: boolean +}) { const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [applying, setApplying] = useState(false) @@ -221,29 +229,42 @@ export default function SandboxInferencePanel({ sandbox }: { sandbox: SandboxInv } return ( -
-
-
-

- {sandbox.name} - INFERENCE ROUTES -

-

- Enable multiple endpoint/model routes for this sandbox. -

+
+ {showHeader && ( +
+
+

+ {sandbox.name} - INFERENCE ROUTES +

+

+ Enable multiple endpoint/model routes for this sandbox. +

+
+
- -
+ )} {loading ? (
Loading inference routes...
) : ( -
+
+ {!showHeader && ( +
+ +
+ )} {primaryRoute && (

Primary Route

diff --git a/app/components/SandboxList.tsx b/app/components/SandboxList.tsx index 9ca1722..2460460 100644 --- a/app/components/SandboxList.tsx +++ b/app/components/SandboxList.tsx @@ -1,9 +1,10 @@ "use client" import { useEffect, useState } from 'react' +import type { ReactNode } from 'react' import ConfigurationPanel from './ConfigurationPanel' +import SandboxFilesPanel from './SandboxFilesPanel' import SandboxInferencePanel from './SandboxInferencePanel' import type { NemoClawSummary, SandboxInventoryItem } from '../hooks/useSandboxInventory' -import { buildOperatorTerminalRoute } from '../lib/dashboardSession' interface TelemetryData { cpu: number @@ -18,7 +19,6 @@ interface TelemetryData { interface SandboxListProps { sandboxes: SandboxInventoryItem[] nemoclaw: NemoClawSummary | null - dashboardSessionId: string selectedSandboxId: string | null selectedSandbox: SandboxInventoryItem | null onSandboxSelect: (id: string | null) => void @@ -26,6 +26,25 @@ interface SandboxListProps { onInventoryRefresh: () => Promise } +type DrawerKey = 'operations' | 'files' | 'inference' | 'policy' +type NetworkRuleRequest = { + chunkId: string + status: string + rule: string + binary: string + confidence: string + rationale: string + endpoints: string[] + binaries: string[] +} +type PermissionFeed = { + latest?: { status?: string; chunkId?: string; error?: string } | null + pending?: NetworkRuleRequest[] + recent?: NetworkRuleRequest[] + pendingCount?: number + rejectedCount?: number +} + function renderDashboardTruthMessage(data: any) { if (data.reachable) return 'OpenClaw dashboard opened in a new tab.' return 'OpenClaw dashboard is not reachable from this host right now.' @@ -39,19 +58,70 @@ function openDashboardUrl(url: string, openInNewTab: boolean) { } } +function DrawerSection({ + title, + summary, + open, + onToggle, + children, +}: { + title: string + summary: string + open: boolean + onToggle: () => void + children: ReactNode +}) { + return ( +
+ + {open && ( +
+ {children} +
+ )} +
+ ) +} + export default function SandboxList({ sandboxes, nemoclaw: _nemoclaw, - dashboardSessionId, selectedSandboxId, selectedSandbox, onSandboxSelect, isDestroyMode, onInventoryRefresh, }: SandboxListProps) { - const [terminalMessage, setTerminalMessage] = useState('') const [dashboardMessage, setDashboardMessage] = useState('') const [restartInProgress, setRestartInProgress] = useState(false) + const [permissionMessage, setPermissionMessage] = useState('') + const [permissionFeeds, setPermissionFeeds] = useState>({}) + const [grantingSandboxId, setGrantingSandboxId] = useState(null) + const [openDrawers, setOpenDrawers] = useState>({ + operations: true, + files: false, + inference: false, + policy: false, + }) const [telemetry, setTelemetry] = useState({ cpu: 0, memory: 0, disk: 0, timestamp: new Date().toISOString() }) @@ -64,6 +134,34 @@ export default function SandboxList({ } }, [selectedSandboxId]) + useEffect(() => { + if (sandboxes.length === 0) { + setPermissionFeeds({}) + return + } + + let active = true + const loadPermissionFeeds = async () => { + const entries = await Promise.all(sandboxes.map(async (sandbox) => { + try { + const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/permissions`, { cache: 'no-store' }) + const data = await response.json() + return [sandbox.id, response.ok ? data.feed : { rejectedCount: 1, latest: { status: 'Unavailable', error: data.error } }] as const + } catch (error) { + return [sandbox.id, { rejectedCount: 1, latest: { status: 'Unavailable', error: error instanceof Error ? error.message : 'Permission feed unavailable' } }] as const + } + })) + if (active) setPermissionFeeds(Object.fromEntries(entries)) + } + + loadPermissionFeeds() + const interval = window.setInterval(loadPermissionFeeds, 12000) + return () => { + active = false + window.clearInterval(interval) + } + }, [sandboxes]) + const fetchTelemetry = async () => { try { const response = await fetch('/api/telemetry/combined') @@ -93,6 +191,33 @@ export default function SandboxList({ } } + const toggleDrawer = (key: DrawerKey) => { + setOpenDrawers((current) => ({ ...current, [key]: !current[key] })) + } + + const resolvePermissionRequest = async (sandbox: SandboxInventoryItem, action: 'approve' | 'reject', chunkId: string) => { + if (!chunkId) return + try { + setGrantingSandboxId(sandbox.id) + setPermissionMessage(`${action === 'approve' ? 'Approving' : 'Rejecting'} network request for ${sandbox.name}...`) + const response = await fetch(`/api/sandbox/${encodeURIComponent(sandbox.id)}/permissions`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ action, chunkId }), + }) + const data = await response.json() + if (!response.ok) throw new Error(data.error || 'Failed to resolve permission request') + if (data.result?.feed) { + setPermissionFeeds((current) => ({ ...current, [sandbox.id]: data.result.feed })) + } + setPermissionMessage(data.note || `Network request ${action === 'approve' ? 'approved' : 'rejected'} for ${sandbox.name}.`) + } catch (error) { + setPermissionMessage(error instanceof Error ? error.message : 'Failed to resolve permission request') + } finally { + setGrantingSandboxId(null) + } + } + return (
{sandboxes.length === 0 ? ( @@ -118,9 +243,8 @@ export default function SandboxList({
{sandboxes.map((sandbox) => ( - +
+
-
-
- Attach Target - {sandbox.ip} -
-
- Namespace - {sandbox.namespace} -
-
- Host Alias - {sandbox.sshHostAlias || 'N/A'} -
-
- Sandbox ID - {sandbox.id} -
-
- +
))}
+ {permissionMessage && ( +
+ {permissionMessage} +
+ )} + {!isDestroyMode && selectedSandbox && ( <> -
-
-

- {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 ( + +
+ + + + + + + {message && ( +
+ {message} +
+ )} + + + + Back to Sign In +
+
+ ) +} 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 ( + +
+ + + {message && ( +
+ {message} +
+ )} + + + + +
+
+ ) +} 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 ( + +
+ + + + + + + {message && ( +
+ {message} +
+ )} + + + + Back to Sign In +
+
+ ) +} 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 || '/',