Add OpenShell Control auth and installer
This commit is contained in:
@@ -10,6 +10,13 @@ OPEN_SHELL_CONTAINER=openshell-cluster-openshell
|
|||||||
# Dashboard port
|
# Dashboard port
|
||||||
NEXT_PUBLIC_DASHBOARD_PORT=3000
|
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
|
# API endpoints
|
||||||
NEXT_PUBLIC_API_BASE=/api
|
NEXT_PUBLIC_API_BASE=/api
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
## Features
|
||||||
|
|
||||||
- **Live Telemetry**: Real-time CPU, memory, disk, and GPU monitoring
|
- View live OpenShell sandbox inventory.
|
||||||
- **One-Click Actions**: Quick actions to start/stop sandbox, create NemoClaw instances, and switch models
|
- Create, destroy, and restart sandboxes.
|
||||||
- **Configuration Management**: Update OpenShell, NemoClaw, and Ollama settings
|
- Launch a sandbox-specific OpenClaw Gateway Dashboard through the local proxy.
|
||||||
- **Model Switcher**: Select and switch between available Ollama models
|
- Approve or reject pending OpenShell network permission requests.
|
||||||
- **Local-first**: Runs entirely on your local machine
|
- 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
|
```bash
|
||||||
./install.sh
|
./install.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
The installer will:
|
The installer:
|
||||||
- ✅ 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
|
|
||||||
|
|
||||||
### 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
|
```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
|
```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
|
```bash
|
||||||
npm run dev
|
npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Open your browser and navigate to:
|
Open:
|
||||||
```
|
|
||||||
|
```text
|
||||||
http://localhost:3000
|
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
|
```bash
|
||||||
# Start OpenShell first
|
OPENSHELL_CONTROL_PASSWORD=...
|
||||||
/Applications/Docker.app/Contents/Resources/bin/docker run -d --name openshell-cluster -p 8080:30051 ghcr.io/nvidia/openshell/cluster:dev
|
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
|
npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
### On Linux
|
## OpenShell And OpenClaw Notes
|
||||||
```bash
|
|
||||||
# Start OpenShell first
|
|
||||||
docker run -d --name openshell-cluster -p 8080:30051 ghcr.io/nvidia/openshell/cluster:dev
|
|
||||||
|
|
||||||
# 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
|
npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
## Configuration
|
## 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
|
```bash
|
||||||
npm run build
|
cp .env.example .env.local
|
||||||
npm start
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Notes
|
Common keys:
|
||||||
|
|
||||||
- This is a development prototype. In production, you'll need to connect to real OpenShell and Ollama APIs.
|
```bash
|
||||||
- All API endpoints are currently mocked for demonstration purposes.
|
NEXT_PUBLIC_DASHBOARD_PORT=3000
|
||||||
- Telemetry data is randomly generated for testing purposes.
|
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
|
## License
|
||||||
|
|
||||||
MIT
|
Internal development prototype. Add the appropriate license before distribution.
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 (
|
||||||
|
<main className="min-h-screen bg-[var(--background)] text-[var(--foreground)] flex items-center justify-center p-6">
|
||||||
|
<section className="panel w-full max-w-md p-8 space-y-6">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="w-9 h-9 bg-[var(--nvidia-green)] rounded-sm flex items-center justify-center">
|
||||||
|
<svg className="w-5 h-5 text-black" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M12 11V7a4 4 0 00-8 0v4m12 0V7a4 4 0 00-8 0m-2 4h12v10H6V11z" />
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<h1 className="text-lg font-semibold uppercase tracking-wider text-[var(--foreground)]">{title}</h1>
|
||||||
|
<p className="text-xs text-[var(--foreground-dim)]">{description}</p>
|
||||||
|
</div>
|
||||||
|
{children}
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -27,6 +27,8 @@ interface ConfigurationPanelProps {
|
|||||||
sandboxId: string
|
sandboxId: string
|
||||||
mode?: 'existing' | 'create'
|
mode?: 'existing' | 'create'
|
||||||
onCreateSuccess?: (sandboxId: string) => void | Promise<void>
|
onCreateSuccess?: (sandboxId: string) => void | Promise<void>
|
||||||
|
embedded?: boolean
|
||||||
|
showHeader?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
function FieldHelp({ text }: { text: string }) {
|
function FieldHelp({ text }: { text: string }) {
|
||||||
@@ -74,7 +76,7 @@ function blocksToPolicy(blocks: NetworkPolicyBlock[]): OpenShellPolicy["network_
|
|||||||
return out
|
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<OpenShellPolicy>(defaultPolicy)
|
const [policy, setPolicy] = useState<OpenShellPolicy>(defaultPolicy)
|
||||||
const [blocks, setBlocks] = useState<NetworkPolicyBlock[]>([])
|
const [blocks, setBlocks] = useState<NetworkPolicyBlock[]>([])
|
||||||
const [loading, setLoading] = useState(mode === 'existing')
|
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: "" }] }]) }
|
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 (
|
return (
|
||||||
<div className="panel p-6 mt-6 border-t-2 border-[var(--nvidia-green)]">
|
<div className={embedded ? "" : "panel p-6 mt-6 border-t-2 border-[var(--nvidia-green)]"}>
|
||||||
<div className="flex items-center justify-between mb-6 pb-4 border-b border-[var(--border-subtle)]">
|
{showHeader && (
|
||||||
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">
|
<div className="flex items-center justify-between mb-6 pb-4 border-b border-[var(--border-subtle)]">
|
||||||
{mode === 'create' ? 'New Sandbox' : `${sandboxId} — OpenShell Policy`}
|
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">
|
||||||
</h4>
|
{mode === 'create' ? 'New Sandbox' : `${sandboxId} - OpenShell Policy`}
|
||||||
<button onClick={savePolicy} disabled={saving} className="px-4 py-2 rounded-sm bg-[var(--nvidia-green)] text-white text-xs font-mono uppercase tracking-wider disabled:opacity-50">
|
</h4>
|
||||||
{saving ? "Working..." : mode === 'create' ? 'Create Sandbox' : 'Save Policy'}
|
<button onClick={savePolicy} disabled={saving} className="px-4 py-2 rounded-sm bg-[var(--nvidia-green)] text-white text-xs font-mono uppercase tracking-wider disabled:opacity-50">
|
||||||
</button>
|
{saving ? "Working..." : mode === 'create' ? 'Create Sandbox' : 'Save Policy'}
|
||||||
</div>
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{loading ? <div className="text-sm text-[var(--foreground-dim)]">Loading policy…</div> : <div className="space-y-8">
|
{loading ? <div className="text-sm text-[var(--foreground-dim)]">Loading policy…</div> : <div className="space-y-8">
|
||||||
{mode === 'create' && <section className="space-y-4 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4"><div><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Create Sandbox</h5><p className="text-xs text-[var(--foreground-dim)] mt-1">Choose a template and enter a sandbox name.</p></div><div className="grid grid-cols-1 md:grid-cols-2 gap-4">{blueprints.map((bp) => <button key={bp.id} type="button" onClick={() => setSelectedBlueprint(bp.id)} className={`rounded-sm border p-4 text-left ${selectedBlueprint === bp.id ? 'border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]' : 'border-[var(--border-subtle)] bg-[var(--background)]'}`}><div className="flex items-center justify-between gap-3"><span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{bp.label}</span><Badge tone={bp.type === 'custom' ? 'static' : 'dynamic'}>{bp.type}</Badge></div><p className="text-xs text-[var(--foreground-dim)] mt-2">{bp.description}</p></button>)}</div><div><label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Sandbox Name<FieldHelp text="Lowercase letters, numbers, and hyphens only." /></label><input value={sandboxName} onChange={(e) => 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)]" /></div>{activeBlueprint?.supportsTailscale && <label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono"><input type="checkbox" checked={enableTailscale} onChange={(e) => setEnableTailscale(e.target.checked)} /> Enable Tailscale</label>}{enableTailscale && <div className="rounded-sm border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-300">Tailscale-enabled creation requires NVIDIA_API_KEY in the dashboard process environment.</div>}</section>}
|
{mode === 'create' && <section className="space-y-4 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4"><div><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Create Sandbox</h5><p className="text-xs text-[var(--foreground-dim)] mt-1">Choose a template and enter a sandbox name.</p></div><div className="grid grid-cols-1 md:grid-cols-2 gap-4">{blueprints.map((bp) => <button key={bp.id} type="button" onClick={() => setSelectedBlueprint(bp.id)} className={`rounded-sm border p-4 text-left ${selectedBlueprint === bp.id ? 'border-[var(--nvidia-green)] bg-[rgba(118,185,0,0.08)]' : 'border-[var(--border-subtle)] bg-[var(--background)]'}`}><div className="flex items-center justify-between gap-3"><span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{bp.label}</span><Badge tone={bp.type === 'custom' ? 'static' : 'dynamic'}>{bp.type}</Badge></div><p className="text-xs text-[var(--foreground-dim)] mt-2">{bp.description}</p></button>)}</div><div><label className="text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Sandbox Name<FieldHelp text="Lowercase letters, numbers, and hyphens only." /></label><input value={sandboxName} onChange={(e) => 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)]" /></div>{activeBlueprint?.supportsTailscale && <label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono"><input type="checkbox" checked={enableTailscale} onChange={(e) => setEnableTailscale(e.target.checked)} /> Enable Tailscale</label>}{enableTailscale && <div className="rounded-sm border border-amber-500/40 bg-amber-500/10 p-3 text-sm text-amber-300">Tailscale-enabled creation requires NVIDIA_API_KEY in the dashboard process environment.</div>}</section>}
|
||||||
<section className="space-y-4"><div className="flex items-center justify-between gap-4 flex-wrap"><div><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Security Presets</h5><p className="text-xs text-[var(--foreground-dim)] mt-1">Use a canned profile for new sandboxes or switch an existing sandbox policy baseline on the fly.</p></div><div className="min-w-[260px]"><select value={selectedPreset} onChange={(e) => { const value = e.target.value as SecurityPresetId | ''; setSelectedPreset(value); if (value) applyPreset(value) }} className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)]"><option value="">Select preset…</option>{SECURITY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.label}</option>)}</select></div></div>{activePreset && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3"><div className="flex items-center gap-3 flex-wrap"><span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{activePreset.label}</span></div><p className="text-sm text-[var(--foreground-dim)]">{activePreset.summary}</p></div>}</section>
|
<section className="space-y-4"><div className="flex items-center justify-between gap-4 flex-wrap"><div><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Security Presets</h5><p className="text-xs text-[var(--foreground-dim)] mt-1">Use a canned profile for new sandboxes or switch an existing sandbox policy baseline on the fly.</p></div><div className="min-w-[260px]"><select value={selectedPreset} onChange={(e) => { const value = e.target.value as SecurityPresetId | ''; setSelectedPreset(value); if (value) applyPreset(value) }} className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono text-[var(--foreground)]"><option value="">Select preset…</option>{SECURITY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.label}</option>)}</select></div></div>{activePreset && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3"><div className="flex items-center gap-3 flex-wrap"><span className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{activePreset.label}</span></div><p className="text-sm text-[var(--foreground-dim)]">{activePreset.summary}</p></div>}</section>
|
||||||
<section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Filesystem Policy</h5><Badge tone="static">Static</Badge></div><label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono"><input type="checkbox" checked={policy.filesystem_policy.include_workdir} onChange={(e) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, include_workdir: e.target.checked } })} />Include workdir<FieldHelp text="Automatically adds the agent working directory to read_write. Static: changing this requires recreating the sandbox." /></label><div className="grid grid-cols-1 md:grid-cols-2 gap-4"><TextListEditor label="Read-only paths" tooltipText="Absolute paths the sandbox can read but not modify. Paths not listed are inaccessible." value={policy.filesystem_policy.read_only} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_only: v } })} placeholder="/usr\n/lib\n/etc" /><TextListEditor label="Read-write paths" tooltipText="Absolute paths the sandbox can read and write. Keep this scoped; broad paths are rejected." value={policy.filesystem_policy.read_write} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_write: v } })} placeholder="/sandbox\n/tmp" /></div></section>
|
<section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Filesystem Policy</h5><Badge tone="static">Static</Badge></div><label className="flex items-center gap-3 text-sm text-[var(--foreground)] font-mono"><input type="checkbox" checked={policy.filesystem_policy.include_workdir} onChange={(e) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, include_workdir: e.target.checked } })} />Include workdir<FieldHelp text="Automatically adds the agent working directory to read_write. Static: changing this requires recreating the sandbox." /></label><div className="grid grid-cols-1 md:grid-cols-2 gap-4"><TextListEditor label="Read-only paths" tooltipText="Absolute paths the sandbox can read but not modify. Paths not listed are inaccessible." value={policy.filesystem_policy.read_only} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_only: v } })} placeholder="/usr\n/lib\n/etc" /><TextListEditor label="Read-write paths" tooltipText="Absolute paths the sandbox can read and write. Keep this scoped; broad paths are rejected." value={policy.filesystem_policy.read_write} onChange={(v) => setPolicy({ ...policy, filesystem_policy: { ...policy.filesystem_policy, read_write: v } })} placeholder="/sandbox\n/tmp" /></div></section>
|
||||||
<section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Network Policies</h5><Badge tone="dynamic">Dynamic</Badge></div><button onClick={addBlock} className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Add policy block</button></section>
|
<section className="space-y-4"><div className="flex items-center gap-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Network Policies</h5><Badge tone="dynamic">Dynamic</Badge></div><button onClick={addBlock} className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Add policy block</button></section>
|
||||||
{mode === 'existing' && <section className="space-y-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Policy JSON</h5><pre className="overflow-auto rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-[11px] leading-5 text-[var(--foreground)]">{JSON.stringify(assembledPolicy, null, 2)}</pre></section>}
|
{mode === 'existing' && <section className="space-y-3"><h5 className="text-xs uppercase tracking-wider text-[var(--foreground)]">Policy JSON</h5><pre className="overflow-auto rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-[11px] leading-5 text-[var(--foreground)]">{JSON.stringify(assembledPolicy, null, 2)}</pre></section>}
|
||||||
|
{!showHeader && <button onClick={savePolicy} disabled={saving} className="px-4 py-2 rounded-sm bg-[var(--nvidia-green)] text-white text-xs font-mono uppercase tracking-wider disabled:opacity-50">{saving ? "Working..." : mode === 'create' ? 'Create Sandbox' : 'Save Policy'}</button>}
|
||||||
{message && <div className="text-sm text-[var(--foreground-dim)] whitespace-pre-wrap">{message}</div>}
|
{message && <div className="text-sm text-[var(--foreground-dim)] whitespace-pre-wrap">{message}</div>}
|
||||||
</div>}
|
</div>}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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<File | null>(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 (
|
||||||
|
<div className={embedded ? "" : "panel p-6"}>
|
||||||
|
{showHeader && (
|
||||||
|
<div className="flex items-center justify-between gap-4 border-b border-[var(--border-subtle)] pb-4">
|
||||||
|
<div>
|
||||||
|
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">
|
||||||
|
{sandbox.name} - FILE TRANSFER
|
||||||
|
</h4>
|
||||||
|
<p className="mt-1 text-xs text-[var(--foreground-dim)]">
|
||||||
|
Move files through scoped sandbox paths.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className={`${showHeader ? "mt-5" : ""} grid grid-cols-1 lg:grid-cols-2 gap-5`}>
|
||||||
|
<section className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-4">
|
||||||
|
<div>
|
||||||
|
<h5 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Upload</h5>
|
||||||
|
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Destination must be under /sandbox or /tmp.</p>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
onChange={(event) => 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)]"
|
||||||
|
/>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Destination Path</label>
|
||||||
|
<input
|
||||||
|
value={uploadPath}
|
||||||
|
onChange={(event) => 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 && (
|
||||||
|
<p className="text-[11px] font-mono text-[var(--foreground-dim)]">Target: {suggestedUploadPath}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={uploadFile}
|
||||||
|
disabled={!selectedFile || busy !== null}
|
||||||
|
className="px-4 py-2 rounded-sm bg-[var(--nvidia-green)] text-white text-xs font-mono uppercase tracking-wider disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{busy === "upload" ? "Uploading..." : "Upload File"}
|
||||||
|
</button>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-4">
|
||||||
|
<div>
|
||||||
|
<h5 className="text-xs font-semibold uppercase tracking-wider text-[var(--foreground)]">Download</h5>
|
||||||
|
<p className="mt-1 text-xs text-[var(--foreground-dim)]">Enter a regular file path under /sandbox or /tmp.</p>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Source Path</label>
|
||||||
|
<input
|
||||||
|
value={downloadPath}
|
||||||
|
onChange={(event) => 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)]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={downloadFile}
|
||||||
|
disabled={!downloadPath.trim() || busy !== null}
|
||||||
|
className="px-4 py-2 rounded-sm bg-[var(--background)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] border border-[var(--border-subtle)] disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{busy === "download" ? "Downloading..." : "Download File"}
|
||||||
|
</button>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{message && (
|
||||||
|
<div className="mt-4 rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)] whitespace-pre-wrap">
|
||||||
|
{message}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -54,7 +54,15 @@ function dedupeRoutes(routes: SandboxInferenceRoute[]) {
|
|||||||
.map((route) => [route.id || routeKey(route), { ...route, id: route.id || routeKey(route) }])).values())
|
.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 [loading, setLoading] = useState(true)
|
||||||
const [saving, setSaving] = useState(false)
|
const [saving, setSaving] = useState(false)
|
||||||
const [applying, setApplying] = useState(false)
|
const [applying, setApplying] = useState(false)
|
||||||
@@ -221,29 +229,42 @@ export default function SandboxInferencePanel({ sandbox }: { sandbox: SandboxInv
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="panel p-6">
|
<div className={embedded ? "" : "panel p-6"}>
|
||||||
<div className="flex items-center justify-between gap-4 border-b border-[var(--border-subtle)] pb-4">
|
{showHeader && (
|
||||||
<div>
|
<div className="flex items-center justify-between gap-4 border-b border-[var(--border-subtle)] pb-4">
|
||||||
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">
|
<div>
|
||||||
{sandbox.name} - INFERENCE ROUTES
|
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">
|
||||||
</h4>
|
{sandbox.name} - INFERENCE ROUTES
|
||||||
<p className="mt-1 text-xs text-[var(--foreground-dim)]">
|
</h4>
|
||||||
Enable multiple endpoint/model routes for this sandbox.
|
<p className="mt-1 text-xs text-[var(--foreground-dim)]">
|
||||||
</p>
|
Enable multiple endpoint/model routes for this sandbox.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={load}
|
||||||
|
disabled={loading || saving}
|
||||||
|
className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] border border-[var(--border-subtle)] disabled:opacity-50"
|
||||||
|
>
|
||||||
|
Refresh
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<button
|
)}
|
||||||
onClick={load}
|
|
||||||
disabled={loading || saving}
|
|
||||||
className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] border border-[var(--border-subtle)] disabled:opacity-50"
|
|
||||||
>
|
|
||||||
Refresh
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<div className="py-8 text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Loading inference routes...</div>
|
<div className="py-8 text-xs uppercase tracking-wider text-[var(--foreground-dim)]">Loading inference routes...</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="mt-5 space-y-5">
|
<div className={`${showHeader ? "mt-5" : ""} space-y-5`}>
|
||||||
|
{!showHeader && (
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<button
|
||||||
|
onClick={load}
|
||||||
|
disabled={loading || saving}
|
||||||
|
className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] border border-[var(--border-subtle)] disabled:opacity-50"
|
||||||
|
>
|
||||||
|
Refresh
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{primaryRoute && (
|
{primaryRoute && (
|
||||||
<div className="metric p-4">
|
<div className="metric p-4">
|
||||||
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Primary Route</p>
|
<p className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Primary Route</p>
|
||||||
|
|||||||
+322
-89
@@ -1,9 +1,10 @@
|
|||||||
"use client"
|
"use client"
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
import ConfigurationPanel from './ConfigurationPanel'
|
import ConfigurationPanel from './ConfigurationPanel'
|
||||||
|
import SandboxFilesPanel from './SandboxFilesPanel'
|
||||||
import SandboxInferencePanel from './SandboxInferencePanel'
|
import SandboxInferencePanel from './SandboxInferencePanel'
|
||||||
import type { NemoClawSummary, SandboxInventoryItem } from '../hooks/useSandboxInventory'
|
import type { NemoClawSummary, SandboxInventoryItem } from '../hooks/useSandboxInventory'
|
||||||
import { buildOperatorTerminalRoute } from '../lib/dashboardSession'
|
|
||||||
|
|
||||||
interface TelemetryData {
|
interface TelemetryData {
|
||||||
cpu: number
|
cpu: number
|
||||||
@@ -18,7 +19,6 @@ interface TelemetryData {
|
|||||||
interface SandboxListProps {
|
interface SandboxListProps {
|
||||||
sandboxes: SandboxInventoryItem[]
|
sandboxes: SandboxInventoryItem[]
|
||||||
nemoclaw: NemoClawSummary | null
|
nemoclaw: NemoClawSummary | null
|
||||||
dashboardSessionId: string
|
|
||||||
selectedSandboxId: string | null
|
selectedSandboxId: string | null
|
||||||
selectedSandbox: SandboxInventoryItem | null
|
selectedSandbox: SandboxInventoryItem | null
|
||||||
onSandboxSelect: (id: string | null) => void
|
onSandboxSelect: (id: string | null) => void
|
||||||
@@ -26,6 +26,25 @@ interface SandboxListProps {
|
|||||||
onInventoryRefresh: () => Promise<SandboxInventoryItem[]>
|
onInventoryRefresh: () => Promise<SandboxInventoryItem[]>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
function renderDashboardTruthMessage(data: any) {
|
||||||
if (data.reachable) return 'OpenClaw dashboard opened in a new tab.'
|
if (data.reachable) return 'OpenClaw dashboard opened in a new tab.'
|
||||||
return 'OpenClaw dashboard is not reachable from this host right now.'
|
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 (
|
||||||
|
<section className="panel overflow-hidden">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onToggle}
|
||||||
|
aria-expanded={open}
|
||||||
|
className="flex w-full items-center justify-between gap-4 p-5 text-left"
|
||||||
|
>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">{title}</h4>
|
||||||
|
<p className="mt-1 text-xs text-[var(--foreground-dim)]">{summary}</p>
|
||||||
|
</div>
|
||||||
|
<svg
|
||||||
|
className={`h-4 w-4 shrink-0 text-[var(--foreground-dim)] transition-transform ${open ? 'rotate-90' : ''}`}
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
{open && (
|
||||||
|
<div className="border-t border-[var(--border-subtle)] p-6">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
export default function SandboxList({
|
export default function SandboxList({
|
||||||
sandboxes,
|
sandboxes,
|
||||||
nemoclaw: _nemoclaw,
|
nemoclaw: _nemoclaw,
|
||||||
dashboardSessionId,
|
|
||||||
selectedSandboxId,
|
selectedSandboxId,
|
||||||
selectedSandbox,
|
selectedSandbox,
|
||||||
onSandboxSelect,
|
onSandboxSelect,
|
||||||
isDestroyMode,
|
isDestroyMode,
|
||||||
onInventoryRefresh,
|
onInventoryRefresh,
|
||||||
}: SandboxListProps) {
|
}: SandboxListProps) {
|
||||||
const [terminalMessage, setTerminalMessage] = useState<string>('')
|
|
||||||
const [dashboardMessage, setDashboardMessage] = useState<string>('')
|
const [dashboardMessage, setDashboardMessage] = useState<string>('')
|
||||||
const [restartInProgress, setRestartInProgress] = useState(false)
|
const [restartInProgress, setRestartInProgress] = useState(false)
|
||||||
|
const [permissionMessage, setPermissionMessage] = useState('')
|
||||||
|
const [permissionFeeds, setPermissionFeeds] = useState<Record<string, PermissionFeed>>({})
|
||||||
|
const [grantingSandboxId, setGrantingSandboxId] = useState<string | null>(null)
|
||||||
|
const [openDrawers, setOpenDrawers] = useState<Record<DrawerKey, boolean>>({
|
||||||
|
operations: true,
|
||||||
|
files: false,
|
||||||
|
inference: false,
|
||||||
|
policy: false,
|
||||||
|
})
|
||||||
const [telemetry, setTelemetry] = useState<TelemetryData>({
|
const [telemetry, setTelemetry] = useState<TelemetryData>({
|
||||||
cpu: 0, memory: 0, disk: 0, timestamp: new Date().toISOString()
|
cpu: 0, memory: 0, disk: 0, timestamp: new Date().toISOString()
|
||||||
})
|
})
|
||||||
@@ -64,6 +134,34 @@ export default function SandboxList({
|
|||||||
}
|
}
|
||||||
}, [selectedSandboxId])
|
}, [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 () => {
|
const fetchTelemetry = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/telemetry/combined')
|
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 (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
{sandboxes.length === 0 ? (
|
{sandboxes.length === 0 ? (
|
||||||
@@ -118,9 +243,8 @@ export default function SandboxList({
|
|||||||
|
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
{sandboxes.map((sandbox) => (
|
{sandboxes.map((sandbox) => (
|
||||||
<button
|
<div
|
||||||
key={sandbox.id}
|
key={sandbox.id}
|
||||||
onClick={() => onSandboxSelect(sandbox.id)}
|
|
||||||
className={`p-4 rounded-sm text-left transition-all border-2 ${
|
className={`p-4 rounded-sm text-left transition-all border-2 ${
|
||||||
isDestroyMode
|
isDestroyMode
|
||||||
? 'border-[var(--status-stopped)] hover:bg-[var(--status-stopped-bg)]'
|
? 'border-[var(--status-stopped)] hover:bg-[var(--status-stopped-bg)]'
|
||||||
@@ -129,60 +253,105 @@ export default function SandboxList({
|
|||||||
: 'panel hover:border-[var(--nvidia-green)]'
|
: 'panel hover:border-[var(--nvidia-green)]'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-between mb-3">
|
<button type="button" onClick={() => onSandboxSelect(sandbox.id)} className="w-full text-left">
|
||||||
<div className="flex items-center gap-2 min-w-0">
|
<div className="flex items-center justify-between mb-3">
|
||||||
<span className={`text-sm font-mono font-semibold truncate ${
|
<div className="flex items-center gap-2 min-w-0">
|
||||||
isDestroyMode ? 'text-[var(--status-stopped)]' : ''
|
{(() => {
|
||||||
|
const feed = permissionFeeds[sandbox.id]
|
||||||
|
const needsAttention = Boolean((feed?.pendingCount || 0) > 0 || /pending|fail|error|unavailable/i.test(feed?.latest?.status || ''))
|
||||||
|
return needsAttention ? (
|
||||||
|
<span className="inline-flex h-5 w-5 items-center justify-center rounded-full bg-amber-400 text-black animate-pulse" title={`Network permission: ${feed?.pendingCount || 0} pending`}>
|
||||||
|
<svg className="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M12 8v5m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="h-2.5 w-2.5 rounded-full bg-[var(--status-running)]" title={`Policy status: ${feed?.latest?.status || 'ok'}`} />
|
||||||
|
)
|
||||||
|
})()}
|
||||||
|
<span className={`text-sm font-mono font-semibold truncate ${
|
||||||
|
isDestroyMode ? 'text-[var(--status-stopped)]' : ''
|
||||||
|
}`}>
|
||||||
|
{sandbox.name}
|
||||||
|
</span>
|
||||||
|
{sandbox.isDefault ? (
|
||||||
|
<span className={`rounded-sm border px-1.5 py-0.5 text-[9px] uppercase tracking-wider ${selectedSandboxId === sandbox.id && !isDestroyMode ? 'border-black/30 text-black' : 'border-[var(--border-subtle)] text-[var(--foreground-dim)]'}`}>default</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div className={`px-2 py-0.5 rounded-sm text-[10px] font-mono uppercase ${
|
||||||
|
isDestroyMode
|
||||||
|
? 'bg-[var(--status-stopped)] text-white animate-pulse'
|
||||||
|
: sandbox.status === 'running' && sandbox.ready
|
||||||
|
? 'bg-[var(--status-running)] text-white'
|
||||||
|
: sandbox.status === 'stopped'
|
||||||
|
? 'bg-[var(--status-stopped)] text-white'
|
||||||
|
: sandbox.status === 'error'
|
||||||
|
? 'bg-red-500 text-white'
|
||||||
|
: 'bg-[var(--status-pending)] text-white'
|
||||||
}`}>
|
}`}>
|
||||||
{sandbox.name}
|
{isDestroyMode ? 'DESTROY' : sandbox.status === 'running' && sandbox.ready ? 'RUNNING' : sandbox.status.toUpperCase()}
|
||||||
</span>
|
</div>
|
||||||
{sandbox.isDefault ? (
|
|
||||||
<span className="rounded-sm border border-[var(--border-subtle)] px-1.5 py-0.5 text-[9px] uppercase tracking-wider text-[var(--foreground-dim)]">default</span>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
<div className={`px-2 py-0.5 rounded-sm text-[10px] font-mono uppercase ${
|
|
||||||
isDestroyMode
|
<div className="space-y-1">
|
||||||
? 'bg-[var(--status-stopped)] text-white animate-pulse'
|
{([
|
||||||
: sandbox.status === 'running' && sandbox.ready
|
['Attach Target', sandbox.ip, '180px'],
|
||||||
? 'bg-[var(--status-running)] text-white'
|
['Namespace', sandbox.namespace, '120px'],
|
||||||
: sandbox.status === 'stopped'
|
['Host Alias', sandbox.sshHostAlias || 'N/A', '140px'],
|
||||||
? 'bg-[var(--status-stopped)] text-white'
|
['Sandbox ID', sandbox.id, '140px'],
|
||||||
: sandbox.status === 'error'
|
] as Array<[string, string, string]>).map(([label, value, width]) => (
|
||||||
? 'bg-red-500 text-white'
|
<div key={label} className="flex items-center justify-between gap-3">
|
||||||
: 'bg-[var(--status-pending)] text-white'
|
<span className={`text-[10px] uppercase ${selectedSandboxId === sandbox.id && !isDestroyMode ? 'text-black' : 'text-[var(--foreground-dim)]'}`}>{label}</span>
|
||||||
}`}>
|
<span className={`text-xs font-mono truncate ${selectedSandboxId === sandbox.id && !isDestroyMode ? 'text-black' : ''}`} style={{ maxWidth: width }} title={value}>{value}</span>
|
||||||
{isDestroyMode ? 'DESTROY' : sandbox.status === 'running' && sandbox.ready ? 'RUNNING' : sandbox.status.toUpperCase()}
|
</div>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
</button>
|
||||||
|
<div className="mt-3 pt-3 border-t border-black/10">
|
||||||
|
<select
|
||||||
|
value=""
|
||||||
|
disabled={grantingSandboxId === sandbox.id}
|
||||||
|
onClick={(event) => event.stopPropagation()}
|
||||||
|
onChange={(event) => {
|
||||||
|
const value = event.target.value
|
||||||
|
event.currentTarget.value = ''
|
||||||
|
resolvePermissionRequest(sandbox, 'approve', value)
|
||||||
|
}}
|
||||||
|
className={`w-full rounded-sm border px-3 py-2 text-xs font-mono uppercase tracking-wider focus:outline-none ${selectedSandboxId === sandbox.id && !isDestroyMode ? 'border-black/30 bg-white/30 text-black' : 'border-[var(--border-subtle)] bg-[var(--background-tertiary)] text-[var(--foreground)]'}`}
|
||||||
|
>
|
||||||
|
<option value="">
|
||||||
|
{grantingSandboxId === sandbox.id
|
||||||
|
? 'Granting...'
|
||||||
|
: (permissionFeeds[sandbox.id]?.pendingCount || 0) > 0
|
||||||
|
? 'Grant Permission'
|
||||||
|
: 'No Permission Requests'}
|
||||||
|
</option>
|
||||||
|
{(permissionFeeds[sandbox.id]?.pending || []).map((request) => (
|
||||||
|
<option key={request.chunkId} value={request.chunkId}>
|
||||||
|
{(request.endpoints[0] || request.rule || request.chunkId).slice(0, 46)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-1">
|
</div>
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Attach Target</span>
|
|
||||||
<span className="text-xs font-mono truncate max-w-[180px]" title={sandbox.ip}>{sandbox.ip}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Namespace</span>
|
|
||||||
<span className="text-xs font-mono truncate max-w-[120px]">{sandbox.namespace}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between gap-3">
|
|
||||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Host Alias</span>
|
|
||||||
<span className="text-xs font-mono truncate max-w-[140px]">{sandbox.sshHostAlias || 'N/A'}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center justify-between gap-3">
|
|
||||||
<span className="text-[10px] text-[var(--foreground-dim)] uppercase">Sandbox ID</span>
|
|
||||||
<span className="text-xs font-mono truncate max-w-[140px]" title={sandbox.id}>{sandbox.id}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{permissionMessage && (
|
||||||
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">
|
||||||
|
{permissionMessage}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{!isDestroyMode && selectedSandbox && (
|
{!isDestroyMode && selectedSandbox && (
|
||||||
<>
|
<>
|
||||||
<div className="panel p-6">
|
<DrawerSection
|
||||||
<div className="flex items-center justify-between mb-6 pb-4 border-b border-[var(--border-subtle)] gap-4 flex-wrap">
|
title={`${selectedSandbox.name} - Operations`}
|
||||||
<h4 className="text-sm font-semibold text-[var(--foreground)] uppercase tracking-wider">
|
summary="Dashboard, terminal, restart, refresh, and live telemetry."
|
||||||
{selectedSandbox.name} — TELEMETRY
|
open={openDrawers.operations}
|
||||||
</h4>
|
onToggle={() => toggleDrawer('operations')}
|
||||||
|
>
|
||||||
|
<div className="space-y-6">
|
||||||
<div className="flex items-center gap-3 flex-wrap">
|
<div className="flex items-center gap-3 flex-wrap">
|
||||||
<button
|
<button
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
@@ -215,18 +384,6 @@ export default function SandboxList({
|
|||||||
>
|
>
|
||||||
{restartInProgress ? 'Restarting Sandbox...' : 'Restart Sandbox'}
|
{restartInProgress ? 'Restarting Sandbox...' : 'Restart Sandbox'}
|
||||||
</button>
|
</button>
|
||||||
<button
|
|
||||||
onClick={() => {
|
|
||||||
const nextUrl = buildOperatorTerminalRoute({
|
|
||||||
sandboxId: selectedSandbox.id,
|
|
||||||
dashboardSessionId,
|
|
||||||
})
|
|
||||||
window.open(nextUrl, '_blank', 'noopener,noreferrer')
|
|
||||||
}}
|
|
||||||
className="px-3 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] border border-[var(--border-subtle)]"
|
|
||||||
>
|
|
||||||
Open Operator Terminal
|
|
||||||
</button>
|
|
||||||
<button
|
<button
|
||||||
onClick={async () => {
|
onClick={async () => {
|
||||||
await onInventoryRefresh()
|
await onInventoryRefresh()
|
||||||
@@ -239,38 +396,114 @@ export default function SandboxList({
|
|||||||
LIVE
|
LIVE
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
{(dashboardMessage || terminalMessage) && (
|
{dashboardMessage && (
|
||||||
<div className="mb-4 space-y-2">
|
<div className="space-y-2">
|
||||||
{dashboardMessage && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">{dashboardMessage}</div>}
|
{dashboardMessage && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">{dashboardMessage}</div>}
|
||||||
{terminalMessage && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)] whitespace-pre-wrap font-mono">{terminalMessage}</div>}
|
</div>
|
||||||
</div>
|
)}
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||||
<div className="metric p-4">
|
<div className="metric p-4">
|
||||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">CPU</p>
|
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">CPU</p>
|
||||||
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.cpu.toFixed(1)}%</p>
|
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.cpu.toFixed(1)}%</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="metric p-4">
|
<div className="metric p-4">
|
||||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">MEM</p>
|
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">MEM</p>
|
||||||
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.memory.toFixed(1)}%</p>
|
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.memory.toFixed(1)}%</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="metric p-4">
|
<div className="metric p-4">
|
||||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">DISK</p>
|
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">DISK</p>
|
||||||
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.disk.toFixed(1)}%</p>
|
<p className="text-xl font-mono text-[var(--nvidia-green)] mt-1">{telemetry.disk.toFixed(1)}%</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="metric p-4">
|
<div className="metric p-4">
|
||||||
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">UPDATED</p>
|
<p className="text-[10px] text-[var(--foreground-dim)] uppercase tracking-wider">UPDATED</p>
|
||||||
<p className="text-sm font-mono text-[var(--foreground)] mt-1">{new Date(telemetry.timestamp).toLocaleTimeString()}</p>
|
<p className="text-sm font-mono text-[var(--foreground)] mt-1">{new Date(telemetry.timestamp).toLocaleTimeString()}</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</DrawerSection>
|
||||||
|
|
||||||
<SandboxInferencePanel sandbox={selectedSandbox} />
|
<DrawerSection
|
||||||
|
title="File Transfer"
|
||||||
|
summary="Upload files into the sandbox and download files back out."
|
||||||
|
open={openDrawers.files}
|
||||||
|
onToggle={() => toggleDrawer('files')}
|
||||||
|
>
|
||||||
|
<SandboxFilesPanel sandbox={selectedSandbox} embedded showHeader={false} />
|
||||||
|
</DrawerSection>
|
||||||
|
|
||||||
<ConfigurationPanel sandboxId={selectedSandbox.id} mode="existing" />
|
<DrawerSection
|
||||||
|
title="Inference Routes"
|
||||||
|
summary="Configure and apply provider/model routes for this sandbox."
|
||||||
|
open={openDrawers.inference}
|
||||||
|
onToggle={() => toggleDrawer('inference')}
|
||||||
|
>
|
||||||
|
<SandboxInferencePanel sandbox={selectedSandbox} embedded showHeader={false} />
|
||||||
|
</DrawerSection>
|
||||||
|
|
||||||
|
<DrawerSection
|
||||||
|
title="Sandbox Policy"
|
||||||
|
summary="Approve or reject network requests raised by the sandbox."
|
||||||
|
open={openDrawers.policy}
|
||||||
|
onToggle={() => toggleDrawer('policy')}
|
||||||
|
>
|
||||||
|
<div className="space-y-4">
|
||||||
|
{(() => {
|
||||||
|
const feed = permissionFeeds[selectedSandbox.id]
|
||||||
|
const pending = feed?.pending || []
|
||||||
|
if (pending.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 text-xs text-[var(--foreground-dim)]">
|
||||||
|
No pending network permission requests for this sandbox.
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return pending.map((request) => (
|
||||||
|
<div key={request.chunkId} className="rounded-sm border border-amber-400/60 bg-amber-400/10 p-4">
|
||||||
|
<div className="flex items-start justify-between gap-4">
|
||||||
|
<div className="min-w-0 space-y-2">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<span className="text-xs font-mono font-semibold text-[var(--foreground)]">
|
||||||
|
{request.endpoints.join(', ') || request.rule}
|
||||||
|
</span>
|
||||||
|
{request.confidence ? (
|
||||||
|
<span className="rounded-sm border border-[var(--border-subtle)] px-1.5 py-0.5 text-[10px] text-[var(--foreground-dim)]">
|
||||||
|
{request.confidence}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-[var(--foreground-dim)]">{request.rationale || 'Sandbox requested a network policy rule.'}</p>
|
||||||
|
<p className="text-[10px] font-mono text-[var(--foreground-dim)]">
|
||||||
|
{request.binary || request.binaries.join(', ') || 'unknown binary'} / {request.chunkId}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex shrink-0 items-center gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={grantingSandboxId === selectedSandbox.id}
|
||||||
|
onClick={() => resolvePermissionRequest(selectedSandbox, 'approve', request.chunkId)}
|
||||||
|
className="rounded-sm border border-[var(--nvidia-green)] bg-[var(--nvidia-green)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
|
||||||
|
>
|
||||||
|
Grant
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={grantingSandboxId === selectedSandbox.id}
|
||||||
|
onClick={() => resolvePermissionRequest(selectedSandbox, 'reject', request.chunkId)}
|
||||||
|
className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-xs font-mono uppercase tracking-wider text-[var(--foreground)] disabled:opacity-50"
|
||||||
|
>
|
||||||
|
Reject
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
})()}
|
||||||
|
<ConfigurationPanel sandboxId={selectedSandbox.id} mode="existing" embedded showHeader={false} />
|
||||||
|
</div>
|
||||||
|
</DrawerSection>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -9,8 +9,11 @@ interface SidebarProps {
|
|||||||
onSandboxesClick: () => void
|
onSandboxesClick: () => void
|
||||||
onCreateClick: () => void
|
onCreateClick: () => void
|
||||||
onDestroyClick: () => void
|
onDestroyClick: () => void
|
||||||
|
onTerminalClick: () => void
|
||||||
onSettingsClick: () => void
|
onSettingsClick: () => void
|
||||||
onExitMode: () => void
|
onExitMode: () => void
|
||||||
|
onLogout: () => void
|
||||||
|
terminalDisabled?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Sidebar({
|
export default function Sidebar({
|
||||||
@@ -22,8 +25,11 @@ export default function Sidebar({
|
|||||||
onSandboxesClick,
|
onSandboxesClick,
|
||||||
onCreateClick,
|
onCreateClick,
|
||||||
onDestroyClick,
|
onDestroyClick,
|
||||||
|
onTerminalClick,
|
||||||
onSettingsClick,
|
onSettingsClick,
|
||||||
onExitMode,
|
onExitMode,
|
||||||
|
onLogout,
|
||||||
|
terminalDisabled = false,
|
||||||
}: SidebarProps) {
|
}: SidebarProps) {
|
||||||
return (
|
return (
|
||||||
<aside className="fixed left-0 top-0 h-screen w-64 bg-[var(--background-secondary)] border-r border-[var(--border-subtle)] flex flex-col z-20">
|
<aside className="fixed left-0 top-0 h-screen w-64 bg-[var(--background-secondary)] border-r border-[var(--border-subtle)] flex flex-col z-20">
|
||||||
@@ -87,6 +93,17 @@ export default function Sidebar({
|
|||||||
<span className="text-sm">Destroy Sandbox</span>
|
<span className="text-sm">Destroy Sandbox</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={onTerminalClick}
|
||||||
|
disabled={terminalDisabled}
|
||||||
|
className="mt-1 w-full flex items-center gap-3 px-3 py-2 rounded-sm transition-colors hover:bg-[var(--background-tertiary)] text-[var(--foreground-dim)] disabled:opacity-40 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M4 17l6-6-6-6m8 14h8" />
|
||||||
|
</svg>
|
||||||
|
<span className="text-sm">Operator Terminal</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
{(isCreateMode || isDestroyMode) && (
|
{(isCreateMode || isDestroyMode) && (
|
||||||
<button
|
<button
|
||||||
onClick={onExitMode}
|
onClick={onExitMode}
|
||||||
@@ -112,7 +129,29 @@ export default function Sidebar({
|
|||||||
</svg>
|
</svg>
|
||||||
<span className="text-sm">Inference Endpoints</span>
|
<span className="text-sm">Inference Endpoints</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<a
|
||||||
|
href="/setup-account"
|
||||||
|
className="mt-1 w-full flex items-center gap-3 px-3 py-2 rounded-sm transition-colors hover:bg-[var(--background-tertiary)] text-[var(--foreground-dim)]"
|
||||||
|
>
|
||||||
|
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M12 12a4 4 0 100-8 4 4 0 000 8zm-7 9a7 7 0 0114 0" />
|
||||||
|
</svg>
|
||||||
|
<span className="text-sm">Setup Account</span>
|
||||||
|
</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
|
<div className="p-2 border-t border-[var(--border-subtle)]">
|
||||||
|
<button
|
||||||
|
onClick={onLogout}
|
||||||
|
className="w-full flex items-center gap-3 px-3 py-2 rounded-sm transition-colors hover:bg-[var(--background-tertiary)] text-[var(--foreground-dim)]"
|
||||||
|
>
|
||||||
|
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<path strokeLinecap="square" strokeLinejoin="miter" strokeWidth={2} d="M15 12H3m0 0l4-4m-4 4l4 4m5-10h6v12h-6" />
|
||||||
|
</svg>
|
||||||
|
<span className="text-sm">Sign Out</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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<HTMLFormElement>) => {
|
||||||
|
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 (
|
||||||
|
<AuthShell title="Forgot Password?" description="Use the local recovery token from .env.local to reset the operator password.">
|
||||||
|
<form onSubmit={submit} className="space-y-5">
|
||||||
|
<label className="block space-y-2">
|
||||||
|
<span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Recovery Token</span>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={recoveryToken}
|
||||||
|
onChange={(event) => setRecoveryToken(event.target.value)}
|
||||||
|
autoFocus
|
||||||
|
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--nvidia-green)]"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="block space-y-2">
|
||||||
|
<span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">New Password</span>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(event) => setPassword(event.target.value)}
|
||||||
|
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--nvidia-green)]"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="block space-y-2">
|
||||||
|
<span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Confirm Password</span>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(event) => setConfirmPassword(event.target.value)}
|
||||||
|
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--nvidia-green)]"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{message && (
|
||||||
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">
|
||||||
|
{message}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={busy}
|
||||||
|
className="w-full rounded-sm border border-[var(--nvidia-green)] bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{busy ? "Resetting..." : "Reset Password"}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<a href="/login" className="block text-center text-xs text-[var(--foreground-dim)] hover:text-[var(--nvidia-green)]">Back to Sign In</a>
|
||||||
|
</form>
|
||||||
|
</AuthShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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<SessionPayload>
|
||||||
|
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,
|
||||||
|
}
|
||||||
@@ -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 }
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<string, string>()
|
||||||
|
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<HTMLFormElement>) => {
|
||||||
|
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 (
|
||||||
|
<AuthShell title="OpenShell Control" description="Operator access is required for sandbox control.">
|
||||||
|
<form onSubmit={submit} className="space-y-6">
|
||||||
|
<label className="block space-y-2">
|
||||||
|
<span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Password</span>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(event) => setPassword(event.target.value)}
|
||||||
|
autoFocus
|
||||||
|
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--nvidia-green)]"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{message && (
|
||||||
|
<div className="rounded-sm border border-[var(--status-stopped)] bg-red-950/20 p-3 text-xs text-[var(--status-stopped)]">
|
||||||
|
{message}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={busy}
|
||||||
|
className="w-full rounded-sm border border-[var(--nvidia-green)] bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{busy ? "Signing In..." : "Sign In"}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between text-xs">
|
||||||
|
<a href="/setup-account" className="text-[var(--foreground-dim)] hover:text-[var(--nvidia-green)]">Setup Account</a>
|
||||||
|
<a href="/forgot-password" className="text-[var(--foreground-dim)] hover:text-[var(--nvidia-green)]">Forgot Password?</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</AuthShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -73,6 +73,7 @@ function OperatorTerminalInner() {
|
|||||||
const [terminalState, setTerminalState] = useState<'idle' | 'connecting' | 'connected' | 'error'>('idle')
|
const [terminalState, setTerminalState] = useState<'idle' | 'connecting' | 'connected' | 'error'>('idle')
|
||||||
const [terminalStatus, setTerminalStatus] = useState<string>('Terminal not connected yet.')
|
const [terminalStatus, setTerminalStatus] = useState<string>('Terminal not connected yet.')
|
||||||
const [liveSession, setLiveSession] = useState<LiveTerminalSession | null>(null)
|
const [liveSession, setLiveSession] = useState<LiveTerminalSession | null>(null)
|
||||||
|
const [showRecovery, setShowRecovery] = useState(false)
|
||||||
|
|
||||||
const terminalContainerRef = useRef<HTMLDivElement | null>(null)
|
const terminalContainerRef = useRef<HTMLDivElement | null>(null)
|
||||||
const terminalRef = useRef<XTermInstance | null>(null)
|
const terminalRef = useRef<XTermInstance | null>(null)
|
||||||
@@ -267,43 +268,47 @@ function OperatorTerminalInner() {
|
|||||||
const shellHint = data?.attach?.shellHint || DEFAULT_SHELL_HINT
|
const shellHint = data?.attach?.shellHint || DEFAULT_SHELL_HINT
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="min-h-screen bg-[var(--background)] text-[var(--foreground)] p-8">
|
<main className="min-h-screen bg-[var(--background)] text-[var(--foreground)] p-6">
|
||||||
<div className="mx-auto max-w-6xl space-y-6">
|
<div className="mx-auto max-w-7xl space-y-5">
|
||||||
<div className="flex items-start justify-between gap-4 flex-wrap">
|
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||||
<div>
|
<div>
|
||||||
<p className="text-[10px] uppercase tracking-[0.25em] text-[var(--foreground-dim)] font-mono">Operator path</p>
|
<p className="text-[10px] uppercase tracking-[0.25em] text-[var(--foreground-dim)] font-mono">OpenShell Control</p>
|
||||||
<h1 className="text-2xl font-semibold uppercase tracking-wider mt-2">Operator Terminal</h1>
|
<h1 className="text-xl font-semibold uppercase tracking-wider mt-2">Operator Terminal</h1>
|
||||||
<p className="text-sm text-[var(--foreground-dim)] mt-3 max-w-3xl">{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.'}</p>
|
|
||||||
<p className="text-[11px] text-[var(--foreground-dim)] font-mono mt-2">OpenShell operator terminal</p>
|
|
||||||
</div>
|
</div>
|
||||||
<Link href="/" className="px-4 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Back to Dashboard</Link>
|
<Link href="/" className="px-4 py-2 rounded-sm bg-[var(--background-tertiary)] text-[var(--foreground)] text-xs font-mono uppercase tracking-wider hover:bg-[var(--background-panel)]">Back to Dashboard</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<section className={`panel p-6 border-2 ${readiness.tone}`}>
|
<section className={`panel px-4 py-3 border ${readiness.tone}`}>
|
||||||
<div className="flex items-center justify-between gap-4 flex-wrap">
|
<div className="flex items-center justify-between gap-4 flex-wrap">
|
||||||
<div><p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Sandbox</p><h2 className="text-lg font-semibold mt-1">{sandboxId || 'HOST'}</h2></div>
|
<div className="flex items-center gap-3 min-w-0">
|
||||||
<div><p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Dashboard Session</p><h2 className="text-lg font-semibold mt-1">{dashboardSessionId.slice(0, 8)}</h2></div>
|
<span className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Sandbox</span>
|
||||||
<div className="text-right"><p className="text-[10px] uppercase tracking-[0.2em] font-mono opacity-80">Status</p><p className="text-sm font-mono mt-1">{readiness.label}</p>{lastCheckedAt && <p className="text-[10px] mt-1 opacity-80">Last checked {lastCheckedAt}</p>}</div>
|
<span className="text-sm font-mono text-[var(--foreground)] truncate">{sandboxId || 'host'}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3 min-w-0">
|
||||||
|
<span className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Status</span>
|
||||||
|
<span className="text-xs font-mono truncate">{readiness.label}</span>
|
||||||
|
{lastCheckedAt && <span className="text-[10px] text-[var(--foreground-dim)]">checked {lastCheckedAt}</span>}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm mt-4 text-[var(--foreground)]">{readiness.detail}</p>
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="panel p-6 space-y-4">
|
<section className="panel p-6 space-y-4">
|
||||||
<div className="flex items-center justify-between gap-3 flex-wrap">
|
<div className="flex items-center justify-between gap-3 flex-wrap">
|
||||||
<div><h3 className="text-sm font-semibold uppercase tracking-wider">Live Dashboard Terminal</h3><p className="text-xs text-[var(--foreground-dim)] mt-2">Browser terminal backed by the dashboard terminal server.</p></div>
|
<div><h3 className="text-sm font-semibold uppercase tracking-wider">Live Terminal</h3></div>
|
||||||
<div className="text-[11px] text-[var(--foreground-dim)] font-mono">{terminalStatus}</div>
|
<div className="text-[11px] text-[var(--foreground-dim)] font-mono">{terminalStatus}</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-black p-3"><div ref={terminalContainerRef} className="h-[520px] w-full" /></div>
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-black p-3"><div ref={terminalContainerRef} className="h-[68vh] min-h-[460px] w-full" /></div>
|
||||||
<div className="flex items-center gap-3 flex-wrap">
|
<div className="flex items-center gap-3 flex-wrap">
|
||||||
<button onClick={ensureLiveSession} disabled={terminalState === 'connecting'} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">{terminalState === 'connecting' ? 'Connecting…' : 'Reconnect Live Terminal'}</button>
|
<button onClick={ensureLiveSession} disabled={terminalState === 'connecting'} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">{terminalState === 'connecting' ? 'Connecting…' : 'Reconnect Live Terminal'}</button>
|
||||||
<button onClick={refreshReadiness} disabled={!sandboxId} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">Refresh Readiness</button>
|
<button onClick={refreshReadiness} disabled={!sandboxId} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)] disabled:opacity-50 disabled:cursor-not-allowed">Refresh Readiness</button>
|
||||||
|
<button onClick={() => setShowRecovery((current) => !current)} className="px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]">{showRecovery ? 'Hide Recovery' : 'Recovery Commands'}</button>
|
||||||
<span className="text-[11px] text-[var(--foreground-dim)] font-mono">{liveSession?.sessionId ? `session ${liveSession.sessionId.slice(0, 8)}` : 'no session'}</span>
|
<span className="text-[11px] text-[var(--foreground-dim)] font-mono">{liveSession?.sessionId ? `session ${liveSession.sessionId.slice(0, 8)}` : 'no session'}</span>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="grid grid-cols-1 xl:grid-cols-[1.1fr_0.9fr] gap-6">
|
{showRecovery && (
|
||||||
<div className="panel p-6 space-y-5">
|
<section className="panel p-6 space-y-5">
|
||||||
<div><h3 className="text-sm font-semibold uppercase tracking-wider">Direct Attach Fallbacks</h3><p className="text-xs text-[var(--foreground-dim)] mt-2">If the live dashboard terminal is degraded, these remain the authoritative escape hatches.</p></div>
|
<div><h3 className="text-sm font-semibold uppercase tracking-wider">Recovery Commands</h3><p className="text-xs text-[var(--foreground-dim)] mt-2">{readiness.detail}</p></div>
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4"><p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Preferred attach command</p><code className="block mt-2 text-sm font-mono text-[var(--nvidia-green)] break-all">{aliasCommand}</code><button onClick={() => copyCommand(aliasCommand)} className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]">Copy Alias Command</button></div>
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4"><p className="text-[10px] uppercase tracking-[0.2em] text-[var(--foreground-dim)] font-mono">Preferred attach command</p><code className="block mt-2 text-sm font-mono text-[var(--nvidia-green)] break-all">{aliasCommand}</code><button onClick={() => copyCommand(aliasCommand)} className="mt-3 px-3 py-2 rounded-sm border border-[var(--border-subtle)] text-xs font-mono uppercase tracking-wider hover:border-[var(--nvidia-green)]">Copy Alias Command</button></div>
|
||||||
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3">
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-4 space-y-3">
|
||||||
@@ -312,8 +317,8 @@ function OperatorTerminalInner() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{copyMessage && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">{copyMessage}</div>}
|
{copyMessage && <div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">{copyMessage}</div>}
|
||||||
</div>
|
</section>
|
||||||
</section>
|
)}
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
)
|
)
|
||||||
|
|||||||
+13
-2
@@ -7,6 +7,7 @@ import InferenceEndpointPanel from './components/InferenceEndpointPanel'
|
|||||||
import { useSandboxInventory } from './hooks/useSandboxInventory'
|
import { useSandboxInventory } from './hooks/useSandboxInventory'
|
||||||
import {
|
import {
|
||||||
createHydrationSafeDashboardSessionState,
|
createHydrationSafeDashboardSessionState,
|
||||||
|
buildOperatorTerminalRoute,
|
||||||
loadDashboardSessionState,
|
loadDashboardSessionState,
|
||||||
persistDashboardSessionState,
|
persistDashboardSessionState,
|
||||||
updateDashboardSessionSelection,
|
updateDashboardSessionSelection,
|
||||||
@@ -187,6 +188,14 @@ export default function Dashboard() {
|
|||||||
setIsCreateMode(false)
|
setIsCreateMode(false)
|
||||||
setLifecycleMessage(null)
|
setLifecycleMessage(null)
|
||||||
}}
|
}}
|
||||||
|
onTerminalClick={() => {
|
||||||
|
const nextUrl = buildOperatorTerminalRoute({
|
||||||
|
sandboxId: selectedSandbox?.id,
|
||||||
|
dashboardSessionId: dashboardSession.dashboardSessionId,
|
||||||
|
})
|
||||||
|
window.open(nextUrl, '_blank', 'noopener,noreferrer')
|
||||||
|
}}
|
||||||
|
terminalDisabled={!selectedSandbox}
|
||||||
onSettingsClick={() => {
|
onSettingsClick={() => {
|
||||||
setActiveView('settings')
|
setActiveView('settings')
|
||||||
setIsCreateMode(false)
|
setIsCreateMode(false)
|
||||||
@@ -198,6 +207,10 @@ export default function Dashboard() {
|
|||||||
setIsDestroyMode(false)
|
setIsDestroyMode(false)
|
||||||
clearSelection()
|
clearSelection()
|
||||||
}}
|
}}
|
||||||
|
onLogout={async () => {
|
||||||
|
await fetch('/api/auth/logout', { method: 'POST' }).catch(() => null)
|
||||||
|
window.location.href = '/login'
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<main className="ml-64 transition-all duration-300">
|
<main className="ml-64 transition-all duration-300">
|
||||||
@@ -281,7 +294,6 @@ export default function Dashboard() {
|
|||||||
<SandboxList
|
<SandboxList
|
||||||
sandboxes={sandboxes}
|
sandboxes={sandboxes}
|
||||||
nemoclaw={nemoclaw}
|
nemoclaw={nemoclaw}
|
||||||
dashboardSessionId={dashboardSession.dashboardSessionId}
|
|
||||||
selectedSandboxId={dashboardSession.selectedSandboxId}
|
selectedSandboxId={dashboardSession.selectedSandboxId}
|
||||||
selectedSandbox={selectedSandbox}
|
selectedSandbox={selectedSandbox}
|
||||||
onSandboxSelect={handleSandboxSelect}
|
onSandboxSelect={handleSandboxSelect}
|
||||||
@@ -340,7 +352,6 @@ export default function Dashboard() {
|
|||||||
<SandboxList
|
<SandboxList
|
||||||
sandboxes={sandboxes}
|
sandboxes={sandboxes}
|
||||||
nemoclaw={nemoclaw}
|
nemoclaw={nemoclaw}
|
||||||
dashboardSessionId={dashboardSession.dashboardSessionId}
|
|
||||||
selectedSandboxId={dashboardSession.selectedSandboxId}
|
selectedSandboxId={dashboardSession.selectedSandboxId}
|
||||||
selectedSandbox={selectedSandbox}
|
selectedSandbox={selectedSandbox}
|
||||||
onSandboxSelect={handleSandboxSelect}
|
onSandboxSelect={handleSandboxSelect}
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
"use client"
|
||||||
|
|
||||||
|
import { FormEvent, useState } from "react"
|
||||||
|
import AuthShell from "../components/AuthShell"
|
||||||
|
|
||||||
|
export default function SetupAccountPage() {
|
||||||
|
const [currentPassword, setCurrentPassword] = useState("")
|
||||||
|
const [password, setPassword] = useState("")
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState("")
|
||||||
|
const [message, setMessage] = useState("")
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
|
const submit = async (event: FormEvent<HTMLFormElement>) => {
|
||||||
|
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 (
|
||||||
|
<AuthShell title="Setup Your Account" description="Set or rotate the local operator password for this control UI.">
|
||||||
|
<form onSubmit={submit} className="space-y-5">
|
||||||
|
<label className="block space-y-2">
|
||||||
|
<span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Current Password</span>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={currentPassword}
|
||||||
|
onChange={(event) => setCurrentPassword(event.target.value)}
|
||||||
|
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--nvidia-green)]"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="block space-y-2">
|
||||||
|
<span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">New Password</span>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(event) => setPassword(event.target.value)}
|
||||||
|
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--nvidia-green)]"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="block space-y-2">
|
||||||
|
<span className="text-[10px] uppercase tracking-wider text-[var(--foreground-dim)]">Confirm Password</span>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(event) => setConfirmPassword(event.target.value)}
|
||||||
|
className="w-full rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] px-3 py-2 text-sm text-[var(--foreground)] outline-none focus:border-[var(--nvidia-green)]"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{message && (
|
||||||
|
<div className="rounded-sm border border-[var(--border-subtle)] bg-[var(--background-tertiary)] p-3 text-xs text-[var(--foreground-dim)]">
|
||||||
|
{message}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={busy}
|
||||||
|
className="w-full rounded-sm border border-[var(--nvidia-green)] bg-[var(--nvidia-green)] px-4 py-2 text-xs font-mono uppercase tracking-wider text-black disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{busy ? "Saving..." : "Save Account"}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<a href="/login" className="block text-center text-xs text-[var(--foreground-dim)] hover:text-[var(--nvidia-green)]">Back to Sign In</a>
|
||||||
|
</form>
|
||||||
|
</AuthShell>
|
||||||
|
)
|
||||||
|
}
|
||||||
+156
-73
@@ -1,105 +1,188 @@
|
|||||||
#!/bin/bash
|
#!/usr/bin/env bash
|
||||||
# NemoClaw Dashboard Installer
|
# OpenShell Control installer
|
||||||
# Installs and configures the OpenShell/NemoClaw control dashboard
|
# Development installer for the local OpenShell sandbox control dashboard.
|
||||||
|
|
||||||
set -e
|
set -euo pipefail
|
||||||
|
|
||||||
GREEN='\033[0;32m'
|
GREEN='\033[0;32m'
|
||||||
YELLOW='\033[1;33m'
|
YELLOW='\033[1;33m'
|
||||||
RED='\033[0;31m'
|
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
|
DO_BUILD=1
|
||||||
check_command() {
|
DO_START=0
|
||||||
if ! command -v $1 &> /dev/null; then
|
|
||||||
echo -e "${RED}Error: $1 is required but not installed.${NC}"
|
usage() {
|
||||||
exit 1
|
cat <<EOF
|
||||||
fi
|
${APP_NAME} installer
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
./install.sh [options]
|
||||||
|
|
||||||
|
Options:
|
||||||
|
--no-build Install and configure without running npm run build
|
||||||
|
--start Start the development server after install
|
||||||
|
--help Show this help
|
||||||
|
|
||||||
|
This project is in development. The installer prepares a local dev/operator
|
||||||
|
environment; it is not a hardened production deployment.
|
||||||
|
EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
check_command node
|
while [[ $# -gt 0 ]]; do
|
||||||
check_command npm
|
case "$1" in
|
||||||
check_command docker
|
--no-build)
|
||||||
|
DO_BUILD=0
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
--start)
|
||||||
|
DO_START=1
|
||||||
|
shift
|
||||||
|
;;
|
||||||
|
--help|-h)
|
||||||
|
usage
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo -e "${RED}Unknown option: $1${NC}"
|
||||||
|
usage
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
# Check if running on Mac or Linux
|
log() {
|
||||||
if [[ "$OSTYPE" == "darwin"* ]]; then
|
echo -e "${GREEN}==>${NC} $*"
|
||||||
echo -e "${YELLOW}Detected macOS${NC}"
|
}
|
||||||
DOCKER_CMD="/Applications/Docker.app/Contents/Resources/bin/docker"
|
|
||||||
OPEN_SHELL_NS="agent-sandbox-system"
|
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
|
else
|
||||||
echo -e "${YELLOW}Detected Linux${NC}"
|
warn "OpenShell CLI was not found on PATH or at ~/.local/bin/openshell."
|
||||||
DOCKER_CMD="docker"
|
warn "Sandbox create/delete, policy grants, terminal, and dashboard proxy features require it."
|
||||||
OPEN_SHELL_NS="agent-sandbox-system"
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Check if Docker is running
|
if docker ps --format '{{.Names}}' | grep -Eq '^openshell-cluster-'; then
|
||||||
echo -e "${YELLOW}Checking Docker...${NC}"
|
log "OpenShell gateway container detected:"
|
||||||
if ! $DOCKER_CMD ps &> /dev/null; then
|
docker ps --format ' {{.Names}}\t{{.Image}}\t{{.Ports}}' | grep -E 'openshell-cluster-' || true
|
||||||
echo -e "${RED}Error: Docker is not running.${NC}"
|
else
|
||||||
echo "Please start Docker Desktop and try again."
|
warn "No openshell-cluster-* Docker container is currently running."
|
||||||
exit 1
|
warn "Install can continue, but the UI will show limited inventory until OpenShell is started."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Check if OpenShell container is running
|
log "Installing npm dependencies"
|
||||||
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}"
|
|
||||||
npm install
|
npm install
|
||||||
|
|
||||||
# Build the dashboard
|
if [[ ! -f "$ENV_FILE" ]]; then
|
||||||
echo -e "${GREEN}Building dashboard...${NC}"
|
log "Creating $ENV_FILE"
|
||||||
npm run build
|
cat > "$ENV_FILE" <<EOF
|
||||||
|
# OpenShell Control local configuration
|
||||||
# Configure environment
|
|
||||||
if [ ! -f .env.local ]; then
|
|
||||||
echo -e "${YELLOW}Creating .env.local...${NC}"
|
|
||||||
cat > .env.local <<EOF
|
|
||||||
# NemoClaw Dashboard Configuration
|
|
||||||
# OpenShell/Kubernetes namespace to monitor
|
|
||||||
NEXT_PUBLIC_KUBERNETES_NAMESPACE=agent-sandbox-system
|
|
||||||
|
|
||||||
# Docker container name running OpenShell
|
|
||||||
OPEN_SHELL_CONTAINER=openshell-cluster-openshell
|
|
||||||
|
|
||||||
# Dashboard port
|
|
||||||
NEXT_PUBLIC_DASHBOARD_PORT=3000
|
NEXT_PUBLIC_DASHBOARD_PORT=3000
|
||||||
|
|
||||||
# API endpoints
|
|
||||||
NEXT_PUBLIC_API_BASE=/api
|
NEXT_PUBLIC_API_BASE=/api
|
||||||
|
|
||||||
# Enable Create/Destroy operations
|
|
||||||
NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS=true
|
NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS=true
|
||||||
|
OPEN_SHELL_CONTAINER=${OPEN_SHELL_CONTAINER_DEFAULT}
|
||||||
|
OPENSHELL_GATEWAY=nemoclaw
|
||||||
EOF
|
EOF
|
||||||
echo -e "${GREEN}Created .env.local - review and customize if needed${NC}"
|
else
|
||||||
|
log "Keeping existing $ENV_FILE"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Configure SSH for GitHub if needed
|
upsert_env "NEXT_PUBLIC_DASHBOARD_PORT" "3000"
|
||||||
if [ -f ~/.ssh/github ]; then
|
upsert_env "NEXT_PUBLIC_API_BASE" "/api"
|
||||||
echo -e "${GREEN}SSH key found - ready for GitHub operations${NC}"
|
upsert_env "NEXT_PUBLIC_ENABLE_SANDBOX_OPERATIONS" "true"
|
||||||
else
|
upsert_env "OPEN_SHELL_CONTAINER" "$OPEN_SHELL_CONTAINER_DEFAULT"
|
||||||
echo -e "${YELLOW}No GitHub SSH key found. Add one if you want to push to GitHub.${NC}"
|
upsert_env "OPENSHELL_GATEWAY" "nemoclaw"
|
||||||
|
upsert_env "OPENSHELL_CONTROL_PASSWORD" "$(random_token 18)"
|
||||||
|
upsert_env "OPENSHELL_CONTROL_AUTH_SECRET" "$(random_token 32)"
|
||||||
|
upsert_env "OPENSHELL_CONTROL_RECOVERY_TOKEN" "$(random_token 18)"
|
||||||
|
|
||||||
|
chmod 600 "$ENV_FILE" || true
|
||||||
|
|
||||||
|
if [[ "$DO_BUILD" -eq 1 ]]; then
|
||||||
|
log "Running production build check"
|
||||||
|
npm run build
|
||||||
|
rm -rf .next
|
||||||
|
log "Removed production .next cache so npm run dev starts cleanly"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo -e "${GREEN}=== Installation Complete ===${NC}"
|
echo -e "${GREEN}=== Installation Complete ===${NC}"
|
||||||
echo ""
|
echo ""
|
||||||
echo "To start the dashboard:"
|
echo "Local config: $ENV_FILE"
|
||||||
|
echo "Login password: read OPENSHELL_CONTROL_PASSWORD from $ENV_FILE"
|
||||||
|
echo "Recovery token: read OPENSHELL_CONTROL_RECOVERY_TOKEN from $ENV_FILE"
|
||||||
|
echo ""
|
||||||
|
echo "Start the development server:"
|
||||||
echo " npm run dev"
|
echo " npm run dev"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Then open: http://localhost:3000"
|
echo "Open:"
|
||||||
|
echo " http://localhost:3000"
|
||||||
echo ""
|
echo ""
|
||||||
echo "The dashboard will connect to your running OpenShell cluster and show:"
|
echo "Ports used by default:"
|
||||||
echo " - Active sandboxes from $OPEN_SHELL_NS namespace"
|
echo " 3000 dashboard HTTP"
|
||||||
echo " - Real-time telemetry (CPU, memory, disk)"
|
echo " 3001 OpenClaw dashboard websocket sidecar"
|
||||||
echo " - Create/Destroy controls (with confirmation)"
|
echo " 3011 operator terminal upstream"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Make sure your OpenShell-Mark fork is running before starting the dashboard!"
|
|
||||||
|
if [[ "$DO_START" -eq 1 ]]; then
|
||||||
|
log "Starting development server"
|
||||||
|
exec npm run dev
|
||||||
|
fi
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server"
|
||||||
|
import { getAuthSettings, verifySessionCookieValue } from "./app/lib/controlAuth"
|
||||||
|
|
||||||
|
const PUBLIC_PATHS = [
|
||||||
|
"/login",
|
||||||
|
"/api/auth/login",
|
||||||
|
"/api/auth/logout",
|
||||||
|
"/setup-account",
|
||||||
|
"/forgot-password",
|
||||||
|
"/api/auth/setup",
|
||||||
|
"/api/auth/recover",
|
||||||
|
"/favicon.ico",
|
||||||
|
"/favicon.svg",
|
||||||
|
"/favicon-32.png",
|
||||||
|
]
|
||||||
|
|
||||||
|
function isPublicPath(pathname: string) {
|
||||||
|
return PUBLIC_PATHS.some((path) => 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).*)"],
|
||||||
|
}
|
||||||
+85
@@ -1,10 +1,25 @@
|
|||||||
import http from 'node:http'
|
import http from 'node:http'
|
||||||
import crypto from 'node:crypto'
|
import crypto from 'node:crypto'
|
||||||
|
import { existsSync, readFileSync } from 'node:fs'
|
||||||
import net from 'node:net'
|
import net from 'node:net'
|
||||||
import tls from 'node:tls'
|
import tls from 'node:tls'
|
||||||
import next from 'next'
|
import next from 'next'
|
||||||
import { WebSocketServer, WebSocket } from 'ws'
|
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 dev = process.env.NODE_ENV !== 'production'
|
||||||
const hostname = process.env.HOSTNAME || process.env.HOST || '0.0.0.0'
|
const hostname = process.env.HOSTNAME || process.env.HOST || '0.0.0.0'
|
||||||
const port = Number(process.env.PORT || 3000)
|
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 defaultInstanceId = 'default'
|
||||||
const sandboxDashboardPortBase = Number.parseInt(process.env.OPENCLAW_SANDBOX_DASHBOARD_PORT_BASE || '19000', 10)
|
const sandboxDashboardPortBase = Number.parseInt(process.env.OPENCLAW_SANDBOX_DASHBOARD_PORT_BASE || '19000', 10)
|
||||||
const sandboxDashboardPortRange = 2000
|
const sandboxDashboardPortRange = 2000
|
||||||
|
const authCookieName = 'openshell_control_session'
|
||||||
|
|
||||||
function now() {
|
function now() {
|
||||||
return new Date().toISOString()
|
return new Date().toISOString()
|
||||||
@@ -32,6 +48,63 @@ function logBridge(event, fields = {}) {
|
|||||||
console.log(`[terminal-bridge] ts=${now()} event=${event}${payload ? ` ${payload}` : ''}`)
|
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) {
|
function buildTerminalUpstreamUrl(req) {
|
||||||
const incoming = new URL(req.url || '/', `http://${req.headers.host || `${hostname}:${port}`}`)
|
const incoming = new URL(req.url || '/', `http://${req.headers.host || `${hostname}:${port}`}`)
|
||||||
const upstream = new URL('/ws', `${terminalWsProtocol}//${terminalServerUrl.host}`)
|
const upstream = new URL('/ws', `${terminalWsProtocol}//${terminalServerUrl.host}`)
|
||||||
@@ -455,6 +528,10 @@ clientWss.on('connection', (client, req) => {
|
|||||||
|
|
||||||
server.on('upgrade', (req, socket, head) => {
|
server.on('upgrade', (req, socket, head) => {
|
||||||
if ((req.url || '').startsWith(terminalProxyPath)) {
|
if ((req.url || '').startsWith(terminalProxyPath)) {
|
||||||
|
if (!isAuthenticatedUpgrade(req)) {
|
||||||
|
rejectUnauthorizedUpgrade(req, socket, req.url || '/')
|
||||||
|
return
|
||||||
|
}
|
||||||
logBridge('upgrade-accepted', {
|
logBridge('upgrade-accepted', {
|
||||||
path: req.url || '/',
|
path: req.url || '/',
|
||||||
remoteAddress: req.socket.remoteAddress || 'unknown',
|
remoteAddress: req.socket.remoteAddress || 'unknown',
|
||||||
@@ -469,6 +546,10 @@ server.on('upgrade', (req, socket, head) => {
|
|||||||
(req.url || '').startsWith(legacyDashboardProxyPrefix) ||
|
(req.url || '').startsWith(legacyDashboardProxyPrefix) ||
|
||||||
(req.url || '').startsWith(instancesProxyPrefix)
|
(req.url || '').startsWith(instancesProxyPrefix)
|
||||||
) {
|
) {
|
||||||
|
if (!isAuthenticatedUpgrade(req)) {
|
||||||
|
rejectUnauthorizedUpgrade(req, socket, req.url || '/')
|
||||||
|
return
|
||||||
|
}
|
||||||
const { upstreamWsUrl, instanceId, controlUiOrigin } = resolveDashboardUpstream(req)
|
const { upstreamWsUrl, instanceId, controlUiOrigin } = resolveDashboardUpstream(req)
|
||||||
logBridge('dashboard-upgrade-accepted', {
|
logBridge('dashboard-upgrade-accepted', {
|
||||||
path: req.url || '/',
|
path: req.url || '/',
|
||||||
@@ -496,6 +577,10 @@ dashboardWsProxyServer.on('upgrade', (req, socket, head) => {
|
|||||||
(req.url || '').startsWith(legacyDashboardProxyPrefix) ||
|
(req.url || '').startsWith(legacyDashboardProxyPrefix) ||
|
||||||
(req.url || '').startsWith(instancesProxyPrefix)
|
(req.url || '').startsWith(instancesProxyPrefix)
|
||||||
) {
|
) {
|
||||||
|
if (!isAuthenticatedUpgrade(req)) {
|
||||||
|
rejectUnauthorizedUpgrade(req, socket, req.url || '/')
|
||||||
|
return
|
||||||
|
}
|
||||||
const { upstreamWsUrl, instanceId, controlUiOrigin } = resolveDashboardUpstream(req)
|
const { upstreamWsUrl, instanceId, controlUiOrigin } = resolveDashboardUpstream(req)
|
||||||
logBridge('dashboard-sidecar-upgrade-accepted', {
|
logBridge('dashboard-sidecar-upgrade-accepted', {
|
||||||
path: req.url || '/',
|
path: req.url || '/',
|
||||||
|
|||||||
Reference in New Issue
Block a user