Skip to content

An open-source, faster Devin alternative

TypeScript

Add single-tenant mode for self-hosted development (#561)

Mohamed Habib72f0ceefc33d
diff --git a/Makefile b/Makefile
index 5fc7ea15..9ec16e17 100644
--- a/Makefile
+++ b/Makefile
@@ -70,6 +70,7 @@ run-pg: build-server
OPENSANDBOX_MODE=combined \
OPENSANDBOX_API_KEY=test-key \
OPENSANDBOX_JWT_SECRET=dev-secret-change-me \
+ OPENSANDBOX_DASHBOARD_AUTH_MODE=single-tenant \
OPENSANDBOX_DATABASE_URL="postgres://opensandbox:opensandbox@localhost:5432/opensandbox?sslmode=disable" \
OPENSANDBOX_DATA_DIR=/tmp/opensandbox-data \
OPENSANDBOX_HTTP_ADDR=http://localhost:8080 \
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 66e86060..7e123bec 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -151,8 +151,43 @@ func main() {
opts.SandboxDBs = sandboxDBMgr
log.Printf("opensandbox: SQLite data directory: %s", cfg.DataDir)
- // Configure WorkOS if credentials are set
- if cfg.WorkOSAPIKey != "" && cfg.WorkOSClientID != "" {
+ // Dashboard authentication. Existing WorkOS deployments keep working when
+ // the explicit mode is unset; single-tenant mode is an opt-in trusted
+ // development identity backed by PostgreSQL.
+ dashboardAuthMode := cfg.DashboardAuthMode
+ if dashboardAuthMode == "" && cfg.WorkOSAPIKey != "" && cfg.WorkOSClientID != "" {
+ dashboardAuthMode = "workos"
+ }
+ opts.DashboardAuthMode = dashboardAuthMode
+
+ switch dashboardAuthMode {
+ case "single-tenant":
+ if opts.Store == nil {
+ log.Fatal("opensandbox: single-tenant dashboard auth requires OPENSANDBOX_DATABASE_URL")
+ }
+ org, user, err := opts.Store.EnsureSingleTenantPrincipal(
+ ctx,
+ cfg.DashboardTenantName,
+ cfg.DashboardTenantSlug,
+ cfg.DashboardUserEmail,
+ cfg.DashboardUserName,
+ )
+ if err != nil {
+ log.Fatalf("opensandbox: bootstrap single-tenant dashboard identity: %v", err)
+ }
+ opts.SingleTenantPrincipal = &auth.SingleTenantPrincipal{
+ UserID: user.ID,
+ OrgID: org.ID,
+ Email: user.Email,
+ }
+ log.Printf(
+ "opensandbox: WARNING: single-tenant dashboard auth enabled for %s; every dashboard request is trusted as this local admin",
+ user.Email,
+ )
+ case "workos":
+ if cfg.WorkOSAPIKey == "" || cfg.WorkOSClientID == "" {
+ log.Fatal("opensandbox: dashboard auth mode workos requires WORKOS_API_KEY and WORKOS_CLIENT_ID")
+ }
opts.WorkOSConfig = &auth.WorkOSConfig{
APIKey: cfg.WorkOSAPIKey,
ClientID: cfg.WorkOSClientID,
diff --git a/deploy/gcp/deploy-qemu-dev.sh b/deploy/gcp/deploy-qemu-dev.sh
index 8a9a98a5..d33f56d4 100755
--- a/deploy/gcp/deploy-qemu-dev.sh
+++ b/deploy/gcp/deploy-qemu-dev.sh
@@ -184,7 +184,8 @@ SETUP_SSD
rsync -az --progress \
-e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i $SSH_KEY" \
--exclude '.git' --exclude 'bin/' --exclude 'node_modules/' \
- --exclude '.claude/' --exclude '*.ext4' \
+ --exclude '.claude/' --exclude '.gocache/' --exclude '.gomodcache/' \
+ --exclude '.wrangler/' --exclude '*.ext4' \
"$PROJECT_ROOT/" "${SSH_USER}@${public_ip}:~/opensandbox/"
log "Running QEMU host setup (deploy/azure/setup-azure-host.sh)..."
@@ -222,7 +223,8 @@ cmd_deploy() {
rsync -az --progress --delete \
-e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i $SSH_KEY" \
--exclude '.git' --exclude 'bin/' --exclude 'node_modules/' \
- --exclude '.claude/' --exclude '*.ext4' \
+ --exclude '.claude/' --exclude '.gocache/' --exclude '.gomodcache/' \
+ --exclude '.wrangler/' --exclude '*.ext4' \
"$PROJECT_ROOT/" "${SSH_USER}@${public_ip}:~/opensandbox/"
log "Building binaries on instance..."
@@ -239,6 +241,13 @@ sudo systemctl stop opensandbox-worker 2>/dev/null || true
sudo systemctl stop opensandbox-server 2>/dev/null || true
sudo cp bin/opensandbox-server bin/opensandbox-worker bin/osb-agent /usr/local/bin/
sudo chmod +x /usr/local/bin/opensandbox-server /usr/local/bin/opensandbox-worker /usr/local/bin/osb-agent
+if [ -f web/dist/index.html ]; then
+ sudo mkdir -p /usr/local/bin/web/dist
+ sudo rsync -a --delete web/dist/ /usr/local/bin/web/dist/
+ echo "Dashboard bundle installed."
+else
+ echo "WARNING: web/dist/index.html is missing; build the dashboard locally before deploy."
+fi
echo "Binaries installed."
BUILD
@@ -296,6 +305,18 @@ ROOTFS
local workos_api_key="${WORKOS_API_KEY:-}"
local workos_client_id="${WORKOS_CLIENT_ID:-}"
local workos_redirect_uri="${WORKOS_REDIRECT_URI:-}"
+ local dashboard_auth_mode="${OPENSANDBOX_DASHBOARD_AUTH_MODE:-}"
+ if [[ -z "$dashboard_auth_mode" ]]; then
+ if [[ -n "$workos_api_key" && -n "$workos_client_id" ]]; then
+ dashboard_auth_mode="workos"
+ else
+ dashboard_auth_mode="single-tenant"
+ fi
+ fi
+ local dashboard_user_email="${OPENSANDBOX_DASHBOARD_USER_EMAIL:[email protected]}"
+ local dashboard_user_name="${OPENSANDBOX_DASHBOARD_USER_NAME:-Local Admin}"
+ local dashboard_tenant_name="${OPENSANDBOX_DASHBOARD_TENANT_NAME:-Dev Org}"
+ local dashboard_tenant_slug="${OPENSANDBOX_DASHBOARD_TENANT_SLUG:-dev}"
local env_tmpdir
env_tmpdir=$(mktemp -d)
@@ -341,6 +362,11 @@ OPENSANDBOX_S3_REGION=${s3_region}
OPENSANDBOX_S3_ACCESS_KEY_ID=${s3_ak}
OPENSANDBOX_S3_SECRET_ACCESS_KEY=${s3_sk}
OPENSANDBOX_MIN_WORKERS=1
+OPENSANDBOX_DASHBOARD_AUTH_MODE=${dashboard_auth_mode}
+OPENSANDBOX_DASHBOARD_USER_EMAIL=${dashboard_user_email}
+OPENSANDBOX_DASHBOARD_USER_NAME=${dashboard_user_name}
+OPENSANDBOX_DASHBOARD_TENANT_NAME=${dashboard_tenant_name}
+OPENSANDBOX_DASHBOARD_TENANT_SLUG=${dashboard_tenant_slug}
# Webhooks (all-Svix-at-edge): forward lifecycle events to the edge events-ingest
# Worker and reach the edge for inline-on-create registration. Set these to the
# igor-dev edge stack to exercise webhooks end-to-end (sandbox-webhooks-rearchitecture.md §8).
@@ -417,9 +443,11 @@ psql -h localhost -U opensandbox -d opensandbox -c "
ON CONFLICT DO NOTHING;
" 2>/dev/null || echo "DB seed: orgs insert failed (may already exist)"
psql -h localhost -U opensandbox -d opensandbox -c "
- INSERT INTO api_keys (id, org_id, key_hash, key_prefix, name)
- VALUES ('00000000-0000-0000-0000-000000000002', '00000000-0000-0000-0000-000000000001', '\${KEY_HASH}', '$(echo -n "${API_KEY}" | cut -c1-8)', 'dev-key')
- ON CONFLICT DO NOTHING;
+ INSERT INTO api_keys (org_id, key_hash, key_prefix, name)
+ SELECT id, '\${KEY_HASH}', '$(echo -n "${API_KEY}" | cut -c1-8)', 'dev-key'
+ FROM orgs
+ WHERE slug = 'dev'
+ ON CONFLICT (key_hash) DO NOTHING;
" 2>/dev/null || echo "DB seed: api_keys insert failed (may already exist)"
echo "DB seeded (org + API key)"
SEED
diff --git a/docs/docs.json b/docs/docs.json
index 0cd7fb39..ce39db51 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -330,6 +330,13 @@
"pages": [
"troubleshooting"
]
+ },
+ {
+ "group": "Self-hosting",
+ "pages": [
+ "self-hosting/overview",
+ "self-hosting/gcp-development"
+ ]
}
]
},
diff --git a/docs/self-hosting/gcp-development.mdx b/docs/self-hosting/gcp-development.mdx
new file mode 100644
index 00000000..50e8adf9
--- /dev/null
+++ b/docs/self-hosting/gcp-development.mdx
@@ -0,0 +1,420 @@
+---
+title: "GCP development cell"
+description: "Run a complete OpenComputer development environment on a nested-KVM Compute Engine VM."
+---
+
+This guide deploys a complete OpenComputer development cell to one Google
+Compute Engine VM. The VM runs the control plane, worker, PostgreSQL, Redis, and
+QEMU/KVM sandboxes together.
+
+<Warning>
+This topology is for development and performance testing. It has one host, no
+high availability, an HTTP API, and ephemeral Local SSD storage. For the
+production shape, start with the [self-hosting architecture](/self-hosting/overview).
+</Warning>
+
+## What gets created
+
+```text
+Developer machine
+ |
+ | SSH and HTTP, restricted by a GCP firewall rule
+ v
++------------------------------------------------------+
+| Compute Engine VM |
+| |
+| opensandbox-server :8080 |
+| opensandbox-worker |
+| PostgreSQL + Redis |
+| QEMU/KVM sandbox VMs |
+| |
+| 50 GB persistent boot disk |
+| 375 GiB Local NVMe SSD mounted at /data |
++------------------------------------------------------+
+```
+
+The default configuration uses:
+
+| Resource | Default |
+| --- | --- |
+| Machine type | `n2-standard-8` |
+| CPU and memory | 8 vCPU, 32 GiB |
+| Operating system | Ubuntu 24.04 LTS |
+| Boot disk | 50 GB `pd-ssd` |
+| Sandbox data disk | One 375 GiB Local SSD over NVMe |
+| Sandbox runtime | QEMU with nested KVM |
+| Sandbox default | 2 vCPU with dynamically managed memory |
+| API port | `8080` |
+
+Google documents the supported machine families and expected overhead in its
+[nested virtualization overview](https://cloud.google.com/compute/docs/instances/nested-virtualization/overview).
+Do not substitute an E2, AMD, or Arm machine for this guide.
+
+## Prerequisites
+
+You need:
+
+- A GCP project with billing enabled.
+- Permission to enable APIs and create Compute Engine instances and firewall
+ rules.
+- The current [Google Cloud CLI](https://cloud.google.com/sdk/docs/install-sdk).
+- `git`, `curl`, `jq`, `ssh`, `rsync`, and `openssl` on your development
+ machine.
+- A clone of the OpenComputer repository.
+
+Authenticate and enable Compute Engine:
+
+```bash
+export GCP_PROJECT="<your-project-id>"
+export GCP_ZONE="us-east4-c"
+
+gcloud auth login
+gcloud config set project "$GCP_PROJECT"
+gcloud services enable compute.googleapis.com
+```
+
+Run the remaining commands from the OpenComputer repository root.
+
+## Configure the deployment
+
+Choose a machine and instance name, then generate a development API key:
+
+```bash
+export MACHINE_TYPE="n2-standard-8"
+export INSTANCE_NAME="opensandbox-qemu-dev"
+export API_KEY="$(openssl rand -hex 32)"
+
+printf 'Save this development API key now: %s\n' "$API_KEY"
+```
+
+Keep the API key in a password manager or a local secret file outside the
+repository. The deploy script stores only its hash in PostgreSQL.
+
+### Restrict ingress before creating the VM
+
+The deployment script looks for a firewall rule named
+`opensandbox-dev-allow`. Create that rule first so the development API and SSH
+are not exposed to the internet.
+
+Replace the CIDR below with your current public IP:
+
+```bash
+export ADMIN_CIDR="<your-public-ip>/32"
+
+gcloud compute firewall-rules create opensandbox-dev-allow \
+ --direction=INGRESS \
+ --action=ALLOW \
+ --rules=tcp:22,tcp:8080 \
+ --source-ranges="$ADMIN_CIDR" \
+ --target-tags=opensandbox-dev \
+ --description="OpenComputer development cell: SSH and API"
+```
+
+If the rule already exists, inspect and tighten it:
+
+```bash
+gcloud compute firewall-rules update opensandbox-dev-allow \
+ --rules=tcp:22,tcp:8080 \
+ --source-ranges="$ADMIN_CIDR"
+```
+
+<Warning>
+The cell serves plain HTTP. Keep port `8080` restricted to trusted source
+addresses. Do not expose worker port `8081`, PostgreSQL, Redis, or worker RPC.
+</Warning>
+
+## Create the host
+
+Create the VM, enable nested virtualization, format the Local SSD as
+reflink-enabled XFS, and install the host dependencies:
+
+```bash
+./deploy/gcp/deploy-qemu-dev.sh create
+```
+
+The first run:
+
+1. Creates an SSH key if the configured key does not exist.
+2. Creates an Ubuntu N2 instance with nested virtualization enabled.
+3. Attaches one Local NVMe SSD.
+4. Mounts the SSD at `/data`.
+5. Installs QEMU/KVM, Docker, Go, PostgreSQL, Redis, and the systemd units.
+
+Confirm KVM before deploying:
+
+```bash
+./deploy/gcp/deploy-qemu-dev.sh ssh -- \
+ sh -lc 'test -c /dev/kvm && echo "KVM ready" || echo "KVM missing"'
+```
+
+Expected output:
+
+```text
+KVM ready
+```
+
+## Deploy OpenComputer
+
+Build the server, worker, and in-VM agent; build the rootfs images; install the
+environment files; start the services; and seed the development API key:
+
+```bash
+./deploy/gcp/deploy-qemu-dev.sh deploy
+```
+
+The first rootfs build takes several minutes. It emits:
+
+- `default.ext4`: the legacy 4 GiB split-disk base.
+- `default-merged.ext4`: the unified 20 GiB base used by new sandboxes.
+
+The unified layout keeps `/`, `/home/sandbox`, and `/workspace` on one virtual
+disk. The underlying image is sparse, so its logical 20 GiB size does not
+consume 20 GiB of Local SSD space immediately.
+
+### Wait for worker registration
+
+The HTTP health endpoint can become ready before the worker has created its
+golden snapshot and registered with the control plane. On a fresh host, allow
+approximately one minute after deployment.
+
+Inspect the server log:
+
+```bash
+./deploy/gcp/deploy-qemu-dev.sh ssh -- \
+ sudo journalctl -u opensandbox-server -n 100 --no-pager
+```
+
+Continue after you see a message similar to:
+
+```text
+new worker registered: w-qemu-dev-1
+```
+
+If sandbox creation returns `503 no workers available`, wait for registration
+and retry.
+
+## Validate the cell
+
+Get the public IP and configure your shell:
+
+```bash
+export PUBLIC_IP="$(
+ gcloud compute instances describe "$INSTANCE_NAME" \
+ --zone="$GCP_ZONE" \
+ --format='value(networkInterfaces[0].accessConfigs[0].natIP)'
+)"
+export OPENCOMPUTER_URL="http://${PUBLIC_IP}:8080"
+export OPENCOMPUTER_API_KEY="$API_KEY"
+```
+
+Check control-plane health:
+
+```bash
+curl -fsS "$OPENCOMPUTER_URL/health"
+```
+
+Create a sandbox:
+
+```bash
+export SANDBOX_ID="$(
+ curl -fsS -X POST "$OPENCOMPUTER_URL/api/sandboxes" \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: $OPENCOMPUTER_API_KEY" \
+ -d '{"templateID":"default"}' |
+ jq -r .sandboxID
+)"
+
+printf 'Sandbox: %s\n' "$SANDBOX_ID"
+```
+
+Run a command inside the VM and verify the unified disk:
+
+```bash
+curl -fsS -X POST \
+ "$OPENCOMPUTER_URL/api/sandboxes/$SANDBOX_ID/exec/run" \
+ -H "Content-Type: application/json" \
+ -H "X-API-Key: $OPENCOMPUTER_API_KEY" \
+ -d '{
+ "cmd": "sh",
+ "args": [
+ "-lc",
+ "uname -a; nproc; free -h; df -h / /home/sandbox /workspace; lsblk"
+ ],
+ "timeout": 30
+ }' |
+jq
+```
+
+For the default unified rootfs, `lsblk` should show one approximately 20 GiB
+`vda`, and all three paths should resolve to the same root filesystem.
+
+## Use the dashboard during development
+
+The development deployment enables the explicit `single-tenant` dashboard
+mode. On startup, the control plane creates or reuses one local organization
+and administrator in PostgreSQL and keeps that development organization on the
+Pro plan so hosted free-tier size gates do not restrict local testing. The
+dashboard therefore shows the live cell's sandboxes without requiring an
+external identity provider.
+
+<Warning>
+Single-tenant mode supplies a persistent local identity but does not
+authenticate individual browser users. Reach the development UI through SSH
+port forwarding and do not expose the Vite port publicly.
+</Warning>
+
+### Start the development UI
+
+The deploy command syncs the dashboard source to the VM. In one terminal, run
+Vite there through the existing Docker installation:
+
+```bash
+gcloud compute ssh "$INSTANCE_NAME" \
+ --project="$GCP_PROJECT" \
+ --zone="$GCP_ZONE" \
+ --command='
+ sudo docker run --rm --network host \
+ -v "$HOME/opensandbox/web:/app" \
+ -w /app \
+ node:22-bookworm-slim \
+ sh -lc "npm ci && npm run dev -- --host 127.0.0.1"
+ '
+```
+
+Vite's development proxy reaches the control plane at `localhost:8080` on the
+VM, so UI requests use the single-tenant identity and operate on the live
+development cell.
+
+### Forward it to your machine
+
+Keep Vite running. In a second local terminal, forward the VM's loopback-only
+UI port to port `3000` on your machine:
+
+```bash
+gcloud compute ssh "$INSTANCE_NAME" \
+ --project="$GCP_PROJECT" \
+ --zone="$GCP_ZONE" \
+ -- -N \
+ -L 127.0.0.1:3000:127.0.0.1:3000 \
+ -o ExitOnForwardFailure=yes \
+ -o ServerAliveInterval=30
+```
+
+Open [http://127.0.0.1:3000](http://127.0.0.1:3000).
+
+Every dashboard action is attributed to the development administrator. You can
+customize that identity before deploying:
+
+```bash
+export OPENSANDBOX_DASHBOARD_AUTH_MODE="single-tenant"
+export OPENSANDBOX_DASHBOARD_USER_EMAIL="[email protected]"
+export OPENSANDBOX_DASHBOARD_USER_NAME="Development Admin"
+export OPENSANDBOX_DASHBOARD_TENANT_NAME="Development"
+export OPENSANDBOX_DASHBOARD_TENANT_SLUG="development"
+
+./deploy/gcp/deploy-qemu-dev.sh deploy
+```
+
+## Operations
+
+Check status:
+
+```bash
+./deploy/gcp/deploy-qemu-dev.sh status
+```
+
+Follow logs:
+
+```bash
+./deploy/gcp/deploy-qemu-dev.sh ssh -- \
+ sudo journalctl -u opensandbox-worker -f
+```
+
+Redeploy the current checkout:
+
+```bash
+./deploy/gcp/deploy-qemu-dev.sh deploy
+```
+
+The deploy command synchronizes the current local checkout to the VM and
+restarts the services.
+
+### Rebuild the rootfs
+
+Normal deploys reuse existing rootfs images. When you intentionally need to
+test a rootfs change, remove both cached bases and deploy again:
+
+```bash
+./deploy/gcp/deploy-qemu-dev.sh ssh -- \
+ sudo rm -f \
+ /data/firecracker/images/default.ext4 \
+ /data/firecracker/images/default-merged.ext4
+
+./deploy/gcp/deploy-qemu-dev.sh deploy
+```
+
+This affects only future sandboxes. Delete or recreate existing development
+sandboxes separately if you need them to use the new base.
+
+## Storage and shutdown
+
+The 50 GB boot disk is a persistent block disk. The 375 GiB Local SSD mounted
+at `/data` holds active sandbox disks and rootfs images.
+
+Google documents that Local SSD data is discarded by default when an instance
+is stopped and recommends durable block storage for data that must survive
+host replacement. See [About Local SSD disks](https://cloud.google.com/compute/docs/disks/local-ssd).
+
+<Warning>
+Treat `stop`, instance deletion, and host replacement as destructive for
+everything under `/data`. Configure object storage before testing durable
+checkpoints or hibernation, and never keep the only copy of important data on
+the Local SSD.
+</Warning>
+
+Delete the development VM when you are finished:
+
+```bash
+./deploy/gcp/deploy-qemu-dev.sh destroy
+```
+
+The script asks for confirmation before deleting the instance.
+
+## Troubleshooting
+
+### `no workers available`
+
+The server became healthy before worker registration completed. Wait for the
+worker registration log, then retry sandbox creation.
+
+### `/dev/kvm` is missing
+
+Confirm that the VM is using a supported Intel machine type, nested
+virtualization was enabled at instance creation, and your organization policy
+allows nested virtualization.
+
+```bash
+gcloud compute instances describe "$INSTANCE_NAME" \
+ --zone="$GCP_ZONE" \
+ --format='yaml(machineType,advancedMachineFeatures)'
+```
+
+### The control-plane root redirects to `localhost:3000`
+
+No built dashboard bundle is installed. Run Vite using one of the dashboard
+modes above, or build `web/dist` before packaging the control plane.
+
+### API requests return `401`
+
+Use the same API key that was passed to `deploy`:
+
+```bash
+curl -fsS "$OPENCOMPUTER_URL/api/sandboxes" \
+ -H "X-API-Key: $OPENCOMPUTER_API_KEY"
+```
+
+### The public IP changed
+
+Run `status` to refresh the deployment state, update
+`OPENCOMPUTER_URL`, and confirm that the firewall still allows your current
+source address.
diff --git a/docs/self-hosting/overview.mdx b/docs/self-hosting/overview.mdx
new file mode 100644
index 00000000..e64f5353
--- /dev/null
+++ b/docs/self-hosting/overview.mdx
@@ -0,0 +1,215 @@
+---
+title: "Self-hosting"
+description: "Understand the OpenComputer architecture and choose a development or scalable deployment shape."
+---
+
+OpenComputer can run inside your own cloud account. A self-hosted deployment
+combines an API control plane with Linux hosts that use QEMU/KVM to run isolated
+sandbox VMs.
+
+Self-hosting is an operator workflow. You are responsible for provisioning the
+cloud resources, securing the API, operating the data stores, and upgrading the
+OpenComputer services.
+
+<CardGroup cols={2}>
+ <Card title="GCP development cell" icon="google" href="/self-hosting/gcp-development">
+ Run a complete single-cell development environment on one nested-KVM Compute Engine VM.
+ </Card>
+ <Card title="Configuration reference" icon="sliders" href="https://github.com/diggerhq/opencomputer/blob/main/deploy/server.env.example">
+ Review the control-plane environment-variable shape.
+ </Card>
+</CardGroup>
+
+## Architecture
+
+OpenComputer has three runtime tiers:
+
+```text
+Client, SDK, CLI, or dashboard
+ |
+ | HTTP
+ v
++---------------+----------------+
+| Control plane |
+| |
+| API and authentication |
+| Sandbox lifecycle and routing |
+| Worker coordination |
++---------------+----------------+
+ |
+ | worker RPC
+ v
++---------------+----------------+
+| Data plane worker |
+| |
+| QEMU/KVM VM lifecycle |
+| Networking and storage |
+| Checkpoint and hibernation |
++---------------+----------------+
+ |
+ | virtio serial / vsock
+ v
++---------------+----------------+
+| Sandbox VM |
+| |
+| Full Linux filesystem |
+| OpenComputer in-VM agent |
+| User commands and processes |
++--------------------------------+
+```
+
+### Control plane
+
+The control plane exposes the OpenComputer HTTP API. It authenticates requests,
+tracks sandbox state, chooses a worker, and routes operations to the worker that
+owns each sandbox.
+
+The control-plane binary is named `opensandbox-server`. The historical
+`opensandbox` name also appears in environment variables as the
+`OPENSANDBOX_*` prefix.
+
+### Data plane
+
+Data-plane workers run on Linux machines with KVM. Each worker starts QEMU
+microVMs, configures their networking and disks, and maintains the connection
+to the agent inside each VM.
+
+The worker binary is named `opensandbox-worker`. A worker registers itself with
+the control plane through Redis and advertises its capacity and RPC address.
+
+### In-VM agent
+
+Every sandbox image contains `osb-agent`. It receives command, file, terminal,
+and process operations from the worker over a VM-local transport. User
+workloads do not need direct access to the worker host.
+
+## Request lifecycle
+
+When a client creates a sandbox:
+
+1. The control plane authenticates the request and selects a worker with
+ capacity.
+2. The worker creates a copy-on-write disk from the selected rootfs image.
+3. QEMU starts the sandbox with KVM acceleration.
+4. The worker waits for `osb-agent`, applies sandbox networking and environment
+ configuration, and reports the sandbox as running.
+5. Subsequent API calls are routed to the owning worker and then to the
+ in-VM agent.
+
+OpenComputer can keep paused VMs in a warm pool. Claiming a prepared VM avoids
+most cold-start work while preserving VM isolation.
+
+## Deployment shapes
+
+### Single-cell development
+
+A development cell can run every component on one VM:
+
+```text
++--------------------------------------------------+
+| One development VM |
+| |
+| opensandbox-server :8080 |
+| opensandbox-worker |
+| PostgreSQL + Redis |
+| QEMU/KVM sandbox VMs |
+| local rootfs images and sandbox disks |
++--------------------------------------------------+
+```
+
+This is the fastest way to test real VM behavior. It is not highly available,
+and local storage can be ephemeral. Use the
+[GCP development guide](/self-hosting/gcp-development) for this topology.
+
+### Scalable hosting
+
+A scalable deployment separates the control plane from a pool of worker
+machines:
+
+```text
+ +----------------------+
+ | HTTPS load balancer |
+ +----------+-----------+
+ |
+ +----------v-----------+
+ | Control plane |
+ | one or more replicas |
+ +----+-------------+---+
+ | |
+ +---------v--+ +--v-----------+
+ | PostgreSQL | | Redis |
+ +------------+ +--------------+
+ |
+ +---------v-------------------------+
+ | Worker pool |
+ | KVM host | KVM host | KVM host |
+ +------------------+----------------+
+ |
+ +--------v---------+
+ | Object storage |
+ | durable VM data |
+ +------------------+
+```
+
+A production-shaped deployment should include:
+
+- Multiple control-plane replicas behind HTTPS.
+- A worker pool spread across failure domains.
+- Durable PostgreSQL and Redis services.
+- S3-compatible object storage for checkpoints, hibernation archives, and
+ durable image artifacts.
+- A secrets manager for database credentials, signing keys, storage
+ credentials, and third-party integrations.
+- Monitoring, centralized logs, backups, and tested recovery procedures.
+- Private worker networking. Only the control-plane or edge endpoint should be
+ public.
+
+The control plane can launch cloud workers using the supported provider
+integrations, or workers can be provisioned independently and configured to
+register with the cell.
+
+## State and storage
+
+Different data has different durability requirements:
+
+| Data | Recommended storage |
+| --- | --- |
+| Organizations, API keys, sandbox records | PostgreSQL |
+| Worker registry and coordination | Redis |
+| Checkpoints and hibernation archives | S3-compatible object storage |
+| Golden rootfs images | Worker image or durable object storage |
+| Active sandbox disks | Fast local NVMe or provisioned block storage |
+
+Fast local disks are a good fit for active copy-on-write sandbox disks, but they
+must not be the only copy of data that needs to survive a worker replacement.
+
+## Networking and security
+
+At minimum:
+
+- Terminate public traffic with HTTPS.
+- Keep worker RPC, Redis, PostgreSQL, and worker HTTP ports on private networks.
+- Use a randomly generated API key for development and a managed
+ authentication flow for shared environments.
+- Store secrets outside source control.
+- Restrict administrative SSH access to known source addresses or an identity
+ aware access layer.
+- Treat preview URLs and sandbox egress as security boundaries, not ordinary
+ application routes.
+
+The single-cell development guides intentionally trade availability and
+durability for simplicity. Do not expose one directly to untrusted traffic.
+
+## Moving from development to scalable hosting
+
+Use the single-cell environment to validate:
+
+- KVM and sandbox boot.
+- The unified rootfs and in-VM agent.
+- Command, file, and terminal APIs.
+- Checkpoint and wake behavior after object storage is configured.
+- Your client and SDK integration.
+
+Before serving production traffic, move PostgreSQL, Redis, and durable artifacts
+off the worker host; place the API behind HTTPS; provision replaceable workers;
+and test worker loss while sandboxes are running.
diff --git a/internal/api/dashboard.go b/internal/api/dashboard.go
index b41f5592..f064c7dd 100644
--- a/internal/api/dashboard.go
+++ b/internal/api/dashboard.go
@@ -30,13 +30,28 @@ func (s *Server) dashboardMe(c echo.Context) error {
orgID, _ := auth.GetOrgID(c)
resp := map[string]interface{}{
- "id": userID,
- "email": email,
- "orgId": orgID,
- }
-
- // Include the user's org list if WorkOS is configured
- if s.store != nil && s.workos != nil && s.workos.OrgMgr() != nil {
+ "id": userID,
+ "email": email,
+ "orgId": orgID,
+ "authMode": s.dashboardAuthMode,
+ "capabilities": map[string]bool{
+ "signOut": s.dashboardAuthMode == "workos",
+ "manageMembers": s.dashboardAuthMode == "workos",
+ "switchOrganizations": s.dashboardAuthMode == "workos",
+ },
+ }
+
+ if s.dashboardAuthMode == "single-tenant" && s.store != nil {
+ if org, err := s.store.GetOrg(c.Request().Context(), orgID); err == nil {
+ resp["orgs"] = []map[string]interface{}{{
+ "id": org.ID,
+ "name": org.Name,
+ "isPersonal": org.IsPersonal,
+ "isActive": true,
+ }}
+ }
+ } else if s.store != nil && s.workos != nil && s.workos.OrgMgr() != nil {
+ // WorkOS remains the membership authority for hosted deployments.
if emailStr, ok := email.(string); ok {
user, err := s.store.GetUserByEmail(c.Request().Context(), emailStr)
if err == nil && user.WorkOSUserID != nil {
diff --git a/internal/api/dashboard_auth_test.go b/internal/api/dashboard_auth_test.go
new file mode 100644
index 00000000..74035b29
--- /dev/null
+++ b/internal/api/dashboard_auth_test.go
@@ -0,0 +1,81 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/auth"
+)
+
+func TestSingleTenantDashboardMe(t *testing.T) {
+ principal := &auth.SingleTenantPrincipal{
+ UserID: uuid.New(),
+ OrgID: uuid.New(),
+ Email: "[email protected]",
+ }
+ server := NewServer(nil, nil, "", &ServerOpts{
+ DashboardAuthMode: "single-tenant",
+ SingleTenantPrincipal: principal,
+ })
+
+ rec := httptest.NewRecorder()
+ server.Echo().ServeHTTP(
+ rec,
+ httptest.NewRequest(http.MethodGet, "/api/dashboard/me", nil),
+ )
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d: %s", rec.Code, http.StatusOK, rec.Body.String())
+ }
+ var got struct {
+ ID uuid.UUID `json:"id"`
+ Email string `json:"email"`
+ OrgID uuid.UUID `json:"orgId"`
+ AuthMode string `json:"authMode"`
+ Capabilities struct {
+ SignOut bool `json:"signOut"`
+ ManageMembers bool `json:"manageMembers"`
+ } `json:"capabilities"`
+ }
+ if err := json.NewDecoder(rec.Body).Decode(&got); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if got.ID != principal.UserID || got.OrgID != principal.OrgID || got.Email != principal.Email {
+ t.Fatalf("identity = %#v, want %#v", got, principal)
+ }
+ if got.AuthMode != "single-tenant" {
+ t.Fatalf("authMode = %q", got.AuthMode)
+ }
+ if got.Capabilities.SignOut || got.Capabilities.ManageMembers {
+ t.Fatalf("single-tenant capabilities unexpectedly enable identity-provider actions: %#v", got.Capabilities)
+ }
+ if !hasRoute(server, http.MethodPost, "/api/dashboard/sandboxes") {
+ t.Fatal("single-tenant dashboard does not expose direct sandbox creation")
+ }
+}
+
+func TestWorkOSDashboardDoesNotExposeDirectSandboxCreate(t *testing.T) {
+ server := NewServer(nil, nil, "", &ServerOpts{
+ DashboardAuthMode: "workos",
+ WorkOSConfig: &auth.WorkOSConfig{
+ APIKey: "sk_test_local",
+ ClientID: "client_test_local",
+ },
+ })
+
+ if hasRoute(server, http.MethodPost, "/api/dashboard/sandboxes") {
+ t.Fatal("WorkOS dashboard unexpectedly exposes direct sandbox creation")
+ }
+}
+
+func hasRoute(server *Server, method, path string) bool {
+ for _, route := range server.Echo().Routes() {
+ if route.Method == method && route.Path == path {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/api/dashboard_org.go b/internal/api/dashboard_org.go
index 4bcfa79b..f628390f 100644
--- a/internal/api/dashboard_org.go
+++ b/internal/api/dashboard_org.go
@@ -8,9 +8,10 @@ import (
"github.com/opensandbox/opensandbox/internal/auth"
)
-// dashboardListOrgMembers returns the members of the current org via WorkOS.
+// dashboardListOrgMembers returns local members for a single-tenant org and
+// uses WorkOS as the membership authority when the org is linked to it.
func (s *Server) dashboardListOrgMembers(c echo.Context) error {
- if s.store == nil || s.workos == nil || s.workos.OrgMgr() == nil {
+ if s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{
"error": "not configured",
})
@@ -26,8 +27,8 @@ func (s *Server) dashboardListOrgMembers(c echo.Context) error {
return c.JSON(http.StatusNotFound, map[string]string{"error": "org not found"})
}
- if org.WorkOSOrgID == nil {
- // Org not linked to WorkOS yet — return local users only
+ if org.WorkOSOrgID == nil || s.workos == nil || s.workos.OrgMgr() == nil {
+ // A local single-tenant org has no external membership provider.
users, err := s.store.ListUsersByOrgID(c.Request().Context(), orgID)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
@@ -233,9 +234,9 @@ func (s *Server) dashboardRevokeInvitation(c echo.Context) error {
return c.JSON(http.StatusOK, map[string]string{"status": "revoked"})
}
-// dashboardListOrgs returns all orgs the user belongs to (via WorkOS memberships).
+// dashboardListOrgs returns the local tenant or the user's WorkOS memberships.
func (s *Server) dashboardListOrgs(c echo.Context) error {
- if s.store == nil || s.workos == nil || s.workos.OrgMgr() == nil {
+ if s.store == nil {
return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})
}
@@ -249,8 +250,8 @@ func (s *Server) dashboardListOrgs(c echo.Context) error {
return c.JSON(http.StatusNotFound, map[string]string{"error": "user not found"})
}
- if user.WorkOSUserID == nil {
- // No WorkOS link — return only the current org
+ if user.WorkOSUserID == nil || s.workos == nil || s.workos.OrgMgr() == nil {
+ // No external identity link — return only the local tenant.
org, err := s.store.GetOrg(c.Request().Context(), user.OrgID)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
@@ -383,4 +384,3 @@ func (s *Server) dashboardGetCredits(c echo.Context) error {
"isPersonal": org.IsPersonal,
})
}
-
diff --git a/internal/api/router.go b/internal/api/router.go
index ec1725c1..6ccdd2a8 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -29,9 +29,9 @@ import (
"github.com/opensandbox/opensandbox/internal/observability"
"github.com/opensandbox/opensandbox/internal/obslog"
"github.com/opensandbox/opensandbox/internal/proxy"
- "github.com/opensandbox/opensandbox/internal/wsgateway"
"github.com/opensandbox/opensandbox/internal/sandbox"
"github.com/opensandbox/opensandbox/internal/storage"
+ "github.com/opensandbox/opensandbox/internal/wsgateway"
)
var errSandboxNotAvailable = map[string]string{
@@ -40,37 +40,38 @@ var errSandboxNotAvailable = map[string]string{
// Server holds the API server dependencies.
type Server struct {
- echo *echo.Echo
- manager sandbox.Manager
- router *sandbox.SandboxRouter // routes all sandbox interactions (state machine, auto-wake, rolling timeout)
- ptyManager *sandbox.PTYManager
- store *db.Store // nil in combined/dev mode without PG
- jwtIssuer *auth.JWTIssuer // nil if JWT not configured
- capTokenIssuer *auth.JWTIssuer // verifies edge→CP capability tokens; nil if SESSION_JWT_SECRET unset
- requireCapToken bool // derived from PRO_BILLING_AUTHORITY=edge: reject direct API-key creates that bypass edge billing (split mode only)
- cfAdminSecret string // HMAC shared with CreditAccount DO for /admin/halt-org and /admin/resume-org; empty disables auth (dev only)
- cfEventSecret string // HMAC shared with the api-edge Worker for /internal/secret-refresh and other edge-→cell push paths
- cellID string // this control plane's cell_id (for the cap-token cell check)
- platformOrgID uuid.UUID // owner of the shared catalog snapshots; anchors the public-snapshot fallback + gates publish (uuid.Nil = fallback disabled)
- mode string // "server", "worker", "combined"
- workerID string // this worker's ID
- region string // this worker's region
- httpAddr string // public HTTP address for direct access
- execSessionManager *sandbox.ExecSessionManager // nil if not configured
- sandboxDBs *sandbox.SandboxDBManager // per-sandbox SQLite manager
- workos *auth.WorkOSMiddleware // nil if WorkOS not configured
- workerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
- checkpointStore *storage.CheckpointStore // nil if hibernation not configured
- sandboxDomain string // base domain for sandbox subdomains
- cfClient *cloudflare.Client // nil if Cloudflare not configured
- pendingCreates sync.Map // map[sandboxID]*pendingCreate — async sandbox creation tracking
- mountSvc *mounts.Service // shared with worker.HTTPServer; nil disables the mounts API
- sandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
- wsGateway *wsgateway.Gateway // nil disables the broker; WS data-plane routes fall back to sandboxAPIProxy
- stripeClient *billing.StripeClient // nil if Stripe not configured
- redisClient *redis.Client // nil if Redis not configured (for health checks)
- adminEvents *AdminEventBus // real-time event bus for admin dashboard
- ready int32 // atomic: 1 = ready, 0 = not ready
+ echo *echo.Echo
+ manager sandbox.Manager
+ router *sandbox.SandboxRouter // routes all sandbox interactions (state machine, auto-wake, rolling timeout)
+ ptyManager *sandbox.PTYManager
+ store *db.Store // nil in combined/dev mode without PG
+ jwtIssuer *auth.JWTIssuer // nil if JWT not configured
+ capTokenIssuer *auth.JWTIssuer // verifies edge→CP capability tokens; nil if SESSION_JWT_SECRET unset
+ requireCapToken bool // derived from PRO_BILLING_AUTHORITY=edge: reject direct API-key creates that bypass edge billing (split mode only)
+ cfAdminSecret string // HMAC shared with CreditAccount DO for /admin/halt-org and /admin/resume-org; empty disables auth (dev only)
+ cfEventSecret string // HMAC shared with the api-edge Worker for /internal/secret-refresh and other edge-→cell push paths
+ cellID string // this control plane's cell_id (for the cap-token cell check)
+ platformOrgID uuid.UUID // owner of the shared catalog snapshots; anchors the public-snapshot fallback + gates publish (uuid.Nil = fallback disabled)
+ mode string // "server", "worker", "combined"
+ workerID string // this worker's ID
+ region string // this worker's region
+ httpAddr string // public HTTP address for direct access
+ execSessionManager *sandbox.ExecSessionManager // nil if not configured
+ sandboxDBs *sandbox.SandboxDBManager // per-sandbox SQLite manager
+ workos *auth.WorkOSMiddleware // nil if WorkOS not configured
+ dashboardAuthMode string // "workos" or "single-tenant"; empty disables dashboard APIs
+ workerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
+ checkpointStore *storage.CheckpointStore // nil if hibernation not configured
+ sandboxDomain string // base domain for sandbox subdomains
+ cfClient *cloudflare.Client // nil if Cloudflare not configured
+ pendingCreates sync.Map // map[sandboxID]*pendingCreate — async sandbox creation tracking
+ mountSvc *mounts.Service // shared with worker.HTTPServer; nil disables the mounts API
+ sandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
+ wsGateway *wsgateway.Gateway // nil disables the broker; WS data-plane routes fall back to sandboxAPIProxy
+ stripeClient *billing.StripeClient // nil if Stripe not configured
+ redisClient *redis.Client // nil if Redis not configured (for health checks)
+ adminEvents *AdminEventBus // real-time event bus for admin dashboard
+ ready int32 // atomic: 1 = ready, 0 = not ready
// Axiom log query (sandbox session logs read API).
// Empty token = endpoint returns 503.
@@ -132,36 +133,38 @@ func (s *Server) SetAxiomQueryConfig(queryToken, dataset string) {
// pendingCreate tracks an async sandbox creation.
type pendingCreate struct {
ready chan struct{} // closed when creation completes
- err error // set before closing ready
+ err error // set before closing ready
}
// ServerOpts holds optional dependencies for the API server.
type ServerOpts struct {
- Store *db.Store
- JWTIssuer *auth.JWTIssuer
- SessionJWTSecret string // shared edge↔CP HMAC secret; enables /internal/sandboxes/create
- RequireCapToken bool // set from PRO_BILLING_AUTHORITY=edge; rejects edge-bypassing direct API-key creates
- CFAdminSecret string // HMAC shared with CF CreditAccount DO; enables /admin/halt-org and /admin/resume-org
- CFEventSecret string // HMAC shared with the api-edge Worker; enables /internal/secret-refresh and other edge-→cell push paths
- CellID string // this control plane's cell_id
- PlatformOrgID string // owner of the shared catalog snapshots (UUID string); empty disables the public-snapshot fallback
- Mode string // "server", "worker", "combined"
- WorkerID string
- Region string
- HTTPAddr string
- ExecSessionManager *sandbox.ExecSessionManager
- SandboxDBs *sandbox.SandboxDBManager
- Router *sandbox.SandboxRouter // nil in server-only mode
- SandboxProxy *proxy.SandboxProxy // nil if subdomain routing not configured
- ControlPlaneProxy *proxy.ControlPlaneProxy // nil except in server mode (routes subdomains to workers)
- SandboxDomain string // base domain for sandbox subdomains
- WorkOSConfig *auth.WorkOSConfig // nil if WorkOS not configured
- WorkerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
- CheckpointStore *storage.CheckpointStore // nil if hibernation not configured
- CFClient *cloudflare.Client // nil if Cloudflare not configured
- SandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
- StripeClient *billing.StripeClient // nil if Stripe not configured
- RedisClient *redis.Client // nil if Redis not configured (for health checks)
+ Store *db.Store
+ JWTIssuer *auth.JWTIssuer
+ SessionJWTSecret string // shared edge↔CP HMAC secret; enables /internal/sandboxes/create
+ RequireCapToken bool // set from PRO_BILLING_AUTHORITY=edge; rejects edge-bypassing direct API-key creates
+ CFAdminSecret string // HMAC shared with CF CreditAccount DO; enables /admin/halt-org and /admin/resume-org
+ CFEventSecret string // HMAC shared with the api-edge Worker; enables /internal/secret-refresh and other edge-→cell push paths
+ CellID string // this control plane's cell_id
+ PlatformOrgID string // owner of the shared catalog snapshots (UUID string); empty disables the public-snapshot fallback
+ Mode string // "server", "worker", "combined"
+ WorkerID string
+ Region string
+ HTTPAddr string
+ ExecSessionManager *sandbox.ExecSessionManager
+ SandboxDBs *sandbox.SandboxDBManager
+ Router *sandbox.SandboxRouter // nil in server-only mode
+ SandboxProxy *proxy.SandboxProxy // nil if subdomain routing not configured
+ ControlPlaneProxy *proxy.ControlPlaneProxy // nil except in server mode (routes subdomains to workers)
+ SandboxDomain string // base domain for sandbox subdomains
+ WorkOSConfig *auth.WorkOSConfig // nil if WorkOS not configured
+ DashboardAuthMode string // "workos" or "single-tenant"
+ SingleTenantPrincipal *auth.SingleTenantPrincipal // required for single-tenant dashboard auth
+ WorkerRegistry *controlplane.RedisWorkerRegistry // nil in combined/worker mode
+ CheckpointStore *storage.CheckpointStore // nil if hibernation not configured
+ CFClient *cloudflare.Client // nil if Cloudflare not configured
+ SandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
+ StripeClient *billing.StripeClient // nil if Stripe not configured
+ RedisClient *redis.Client // nil if Redis not configured (for health checks)
}
// NewServer creates a new API server with all routes configured.
@@ -206,6 +209,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.execSessionManager = opts.ExecSessionManager
s.sandboxDBs = opts.SandboxDBs
s.router = opts.Router
+ s.dashboardAuthMode = opts.DashboardAuthMode
s.workerRegistry = opts.WorkerRegistry
s.checkpointStore = opts.CheckpointStore
s.sandboxDomain = opts.SandboxDomain
@@ -633,24 +637,50 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// Session history (requires PG)
api.GET("/sessions", s.listSessions)
- // WorkOS OAuth + Dashboard API routes (only if WorkOS is configured)
+ // Dashboard authentication. WorkOS owns its OAuth routes; single-tenant
+ // mode supplies one persistent local principal for trusted development
+ // deployments. The dashboard routes themselves are provider-independent.
var frontendURL string
- if opts != nil && opts.WorkOSConfig != nil && opts.WorkOSConfig.APIKey != "" {
- frontendURL = opts.WorkOSConfig.FrontendURL
-
- s.workos = auth.NewWorkOSMiddleware(*opts.WorkOSConfig, s.store)
- oauthHandlers := auth.NewOAuthHandlers(s.workos)
+ var dashboardAuth echo.MiddlewareFunc
+ if opts != nil {
+ workosConfigured := opts.WorkOSConfig != nil && opts.WorkOSConfig.APIKey != ""
+ authMode := opts.DashboardAuthMode
+ // Preserve existing deployments that configure WorkOS without the new
+ // explicit mode.
+ if authMode == "" && workosConfigured {
+ authMode = "workos"
+ s.dashboardAuthMode = authMode
+ }
- // Public OAuth routes
- e.GET("/auth/login", oauthHandlers.HandleLogin)
- e.GET("/auth/callback", oauthHandlers.HandleCallback)
- e.POST("/auth/logout", oauthHandlers.HandleLogout)
+ switch authMode {
+ case "workos":
+ if workosConfigured {
+ frontendURL = opts.WorkOSConfig.FrontendURL
+ s.workos = auth.NewWorkOSMiddleware(*opts.WorkOSConfig, s.store)
+ oauthHandlers := auth.NewOAuthHandlers(s.workos)
+ e.GET("/auth/login", oauthHandlers.HandleLogin)
+ e.GET("/auth/callback", oauthHandlers.HandleCallback)
+ e.POST("/auth/logout", oauthHandlers.HandleLogout)
+ dashboardAuth = s.workos.Middleware()
+ }
+ case "single-tenant":
+ if opts.SingleTenantPrincipal != nil {
+ dashboardAuth = auth.SingleTenantMiddleware(*opts.SingleTenantPrincipal)
+ }
+ }
+ }
- // Dashboard API routes (protected by WorkOS session middleware)
+ if dashboardAuth != nil {
dash := e.Group("/api/dashboard")
- dash.Use(s.workos.Middleware())
+ dash.Use(dashboardAuth)
dash.GET("/me", s.dashboardMe)
+ // Direct dashboard creates are a self-hosted single-tenant convenience.
+ // Hosted WorkOS deployments create through the Cloudflare edge, which
+ // enforces global policy before calling /internal/sandboxes/create.
+ if s.dashboardAuthMode == "single-tenant" {
+ dash.POST("/sandboxes", s.createSandbox)
+ }
dash.GET("/sessions", s.dashboardSessions)
dash.GET("/api-keys", s.dashboardListAPIKeys)
dash.POST("/api-keys", s.dashboardCreateAPIKey)
diff --git a/internal/auth/single_tenant.go b/internal/auth/single_tenant.go
new file mode 100644
index 00000000..cf196600
--- /dev/null
+++ b/internal/auth/single_tenant.go
@@ -0,0 +1,38 @@
+package auth
+
+import (
+ "net/http"
+
+ "github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+)
+
+// SingleTenantPrincipal is the persistent local identity used by explicitly
+// configured development deployments that do not have an identity provider.
+// The deployment owns one local organization; additional authentication
+// strategies can map more users into that tenant later.
+type SingleTenantPrincipal struct {
+ UserID uuid.UUID
+ OrgID uuid.UUID
+ Email string
+}
+
+// SingleTenantMiddleware authenticates every dashboard request as one local
+// principal. It must only be enabled explicitly on a trusted development
+// network; it provides identity context, not user authentication.
+func SingleTenantMiddleware(principal SingleTenantPrincipal) echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ if principal.UserID == uuid.Nil || principal.OrgID == uuid.Nil || principal.Email == "" {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{
+ "error": "single-tenant dashboard identity is not configured",
+ })
+ }
+
+ SetOrgID(c, principal.OrgID)
+ SetUserID(c, principal.UserID)
+ c.Set("user_email", principal.Email)
+ return next(c)
+ }
+ }
+}
diff --git a/internal/auth/single_tenant_test.go b/internal/auth/single_tenant_test.go
new file mode 100644
index 00000000..a5b07c4f
--- /dev/null
+++ b/internal/auth/single_tenant_test.go
@@ -0,0 +1,65 @@
+package auth
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+)
+
+func TestSingleTenantMiddlewareSetsIdentity(t *testing.T) {
+ principal := SingleTenantPrincipal{
+ UserID: uuid.New(),
+ OrgID: uuid.New(),
+ Email: "[email protected]",
+ }
+
+ e := echo.New()
+ e.GET("/me", func(c echo.Context) error {
+ orgID, ok := GetOrgID(c)
+ if !ok {
+ t.Fatal("org context was not set")
+ }
+ userID := GetUserID(c)
+ return c.JSON(http.StatusOK, map[string]interface{}{
+ "orgId": orgID,
+ "userId": userID,
+ "email": c.Get("user_email"),
+ })
+ }, SingleTenantMiddleware(principal))
+
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/me", nil))
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
+ }
+ var got struct {
+ OrgID uuid.UUID `json:"orgId"`
+ UserID *uuid.UUID `json:"userId"`
+ Email string `json:"email"`
+ }
+ if err := json.NewDecoder(rec.Body).Decode(&got); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if got.OrgID != principal.OrgID || got.UserID == nil || *got.UserID != principal.UserID || got.Email != principal.Email {
+ t.Fatalf("identity = %#v, want principal %#v", got, principal)
+ }
+}
+
+func TestSingleTenantMiddlewareRejectsIncompletePrincipal(t *testing.T) {
+ e := echo.New()
+ e.GET("/", func(c echo.Context) error {
+ return c.NoContent(http.StatusNoContent)
+ }, SingleTenantMiddleware(SingleTenantPrincipal{}))
+
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
+
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want %d", rec.Code, http.StatusServiceUnavailable)
+ }
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 46c26ac4..ac424650 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -57,6 +57,15 @@ type Config struct {
WorkOSCookieDomain string
WorkOSFrontendURL string // e.g. "http://localhost:3000" for Vite dev
+ // Dashboard authentication. Empty preserves the legacy behavior: WorkOS
+ // credentials enable WorkOS, otherwise dashboard API routes stay disabled.
+ // "single-tenant" explicitly enables the trusted development identity.
+ DashboardAuthMode string
+ DashboardUserEmail string
+ DashboardUserName string
+ DashboardTenantName string
+ DashboardTenantSlug string
+
// Redis (Upstash) for worker discovery
RedisURL string
@@ -127,25 +136,25 @@ type Config struct {
GoldenDiskLayout string
// AWS EC2 compute pool (server mode only — for auto-scaling worker machines)
- EC2AMI string // Custom AMI for worker instances
- EC2InstanceType string // single fallback type; used only when EC2InstanceTypes is empty
- EC2InstanceTypes []string // ranked list of instance types tried in order on quota/capacity errors
- EC2SubnetID string // VPC subnet for worker instances
- EC2SecurityGroupID string // Security group (allow 8080, 9090, 9091)
- EC2KeyName string // SSH key pair name (for debugging)
- EC2WorkerImage string // Docker image for containerized workers
- EC2IAMInstanceProfile string // IAM instance profile for worker instances (Secrets Manager + S3)
- EC2SSMParameterName string // SSM parameter name for dynamic AMI ID (e.g. /opensandbox/prod/worker-ami-id)
+ EC2AMI string // Custom AMI for worker instances
+ EC2InstanceType string // single fallback type; used only when EC2InstanceTypes is empty
+ EC2InstanceTypes []string // ranked list of instance types tried in order on quota/capacity errors
+ EC2SubnetID string // VPC subnet for worker instances
+ EC2SecurityGroupID string // Security group (allow 8080, 9090, 9091)
+ EC2KeyName string // SSH key pair name (for debugging)
+ EC2WorkerImage string // Docker image for containerized workers
+ EC2IAMInstanceProfile string // IAM instance profile for worker instances (Secrets Manager + S3)
+ EC2SSMParameterName string // SSM parameter name for dynamic AMI ID (e.g. /opensandbox/prod/worker-ami-id)
// Azure compute pool (server mode — for auto-scaling worker VMs)
- AzureSubscriptionID string // Azure subscription ID
- AzureResourceGroup string // Resource group for worker VMs
- AzureVMSize string // single fallback size; used only when AzureVMSizes is empty
+ AzureSubscriptionID string // Azure subscription ID
+ AzureResourceGroup string // Resource group for worker VMs
+ AzureVMSize string // single fallback size; used only when AzureVMSizes is empty
AzureVMSizes []string // ranked list of VM sizes tried in order on quota/capacity errors
- AzureImageID string // Custom image ID or URN
- AzureSubnetID string // Full resource ID of the VNet subnet
- AzureSSHPublicKey string // SSH public key for worker VMs
- AzureKeyVaultName string // Key Vault name for dynamic image ID refresh (e.g. "opensandbox-prod")
+ AzureImageID string // Custom image ID or URN
+ AzureSubnetID string // Full resource ID of the VNet subnet
+ AzureSSHPublicKey string // SSH public key for worker VMs
+ AzureKeyVaultName string // Key Vault name for dynamic image ID refresh (e.g. "opensandbox-prod")
// AzureWorkerIdentityID is the full resource ID of a UserAssigned managed
// identity to attach to every worker VM. The identity must already have
// "Key Vault Secrets Officer" on the regional KV so workers can fetch
@@ -344,7 +353,13 @@ func Load() (*Config, error) {
WorkOSCookieDomain: os.Getenv("WORKOS_COOKIE_DOMAIN"),
WorkOSFrontendURL: os.Getenv("WORKOS_FRONTEND_URL"),
- RedisURL: os.Getenv("OPENSANDBOX_REDIS_URL"),
+ DashboardAuthMode: strings.ToLower(strings.TrimSpace(os.Getenv("OPENSANDBOX_DASHBOARD_AUTH_MODE"))),
+ DashboardUserEmail: envOrDefault("OPENSANDBOX_DASHBOARD_USER_EMAIL", "[email protected]"),
+ DashboardUserName: envOrDefault("OPENSANDBOX_DASHBOARD_USER_NAME", "Local Admin"),
+ DashboardTenantName: envOrDefault("OPENSANDBOX_DASHBOARD_TENANT_NAME", "OpenComputer"),
+ DashboardTenantSlug: envOrDefault("OPENSANDBOX_DASHBOARD_TENANT_SLUG", "opencomputer"),
+
+ RedisURL: os.Getenv("OPENSANDBOX_REDIS_URL"),
AlertSlackWebhook: os.Getenv("OPENSANDBOX_ALERT_SLACK_WEBHOOK"),
RollStuckDeadline: envDuration("OPENSANDBOX_ROLL_STUCK_DEADLINE"),
@@ -373,30 +388,30 @@ func Load() (*Config, error) {
DefaultSandboxCPUs: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_CPUS", 1),
DefaultSandboxDiskMB: envOrDefaultInt("OPENSANDBOX_DEFAULT_SANDBOX_DISK_MB", 0),
- KernelPath: os.Getenv("OPENSANDBOX_KERNEL_PATH"), // default derived from DataDir
- ImagesDir: os.Getenv("OPENSANDBOX_IMAGES_DIR"), // default derived from DataDir
- QEMUBin: envOrDefault("OPENSANDBOX_QEMU_BIN", "qemu-system-x86_64"),
+ KernelPath: os.Getenv("OPENSANDBOX_KERNEL_PATH"), // default derived from DataDir
+ ImagesDir: os.Getenv("OPENSANDBOX_IMAGES_DIR"), // default derived from DataDir
+ QEMUBin: envOrDefault("OPENSANDBOX_QEMU_BIN", "qemu-system-x86_64"),
GoldenDiskLayout: envOrDefault("OPENSANDBOX_GOLDEN_DISK_LAYOUT", "merged"), // default merged; set "split" to override (see field doc)
- EC2AMI: os.Getenv("OPENSANDBOX_EC2_AMI"),
- EC2InstanceType: envOrDefault("OPENSANDBOX_EC2_INSTANCE_TYPE", "c7gd.metal"),
- EC2InstanceTypes: splitCSV(os.Getenv("OPENSANDBOX_EC2_INSTANCE_TYPES")),
- EC2SubnetID: os.Getenv("OPENSANDBOX_EC2_SUBNET_ID"),
- EC2SecurityGroupID: os.Getenv("OPENSANDBOX_EC2_SECURITY_GROUP_ID"),
- EC2KeyName: os.Getenv("OPENSANDBOX_EC2_KEY_NAME"),
- EC2WorkerImage: envOrDefault("OPENSANDBOX_EC2_WORKER_IMAGE", "opensandbox-worker:latest"),
- EC2IAMInstanceProfile: os.Getenv("OPENSANDBOX_EC2_IAM_INSTANCE_PROFILE"),
- EC2SSMParameterName: os.Getenv("OPENSANDBOX_EC2_SSM_AMI_PARAM"),
-
- AzureSubscriptionID: os.Getenv("OPENSANDBOX_AZURE_SUBSCRIPTION_ID"),
- AzureResourceGroup: os.Getenv("OPENSANDBOX_AZURE_RESOURCE_GROUP"),
- AzureVMSize: envOrDefault("OPENSANDBOX_AZURE_VM_SIZE", "Standard_D16s_v5"),
- AzureVMSizes: splitCSV(os.Getenv("OPENSANDBOX_AZURE_VM_SIZES")),
- AzureImageID: os.Getenv("OPENSANDBOX_AZURE_IMAGE_ID"),
- AzureSubnetID: os.Getenv("OPENSANDBOX_AZURE_SUBNET_ID"),
- AzureSSHPublicKey: os.Getenv("OPENSANDBOX_AZURE_SSH_PUBLIC_KEY"),
- AzureKeyVaultName: os.Getenv("OPENSANDBOX_AZURE_KEY_VAULT_NAME"),
+ EC2AMI: os.Getenv("OPENSANDBOX_EC2_AMI"),
+ EC2InstanceType: envOrDefault("OPENSANDBOX_EC2_INSTANCE_TYPE", "c7gd.metal"),
+ EC2InstanceTypes: splitCSV(os.Getenv("OPENSANDBOX_EC2_INSTANCE_TYPES")),
+ EC2SubnetID: os.Getenv("OPENSANDBOX_EC2_SUBNET_ID"),
+ EC2SecurityGroupID: os.Getenv("OPENSANDBOX_EC2_SECURITY_GROUP_ID"),
+ EC2KeyName: os.Getenv("OPENSANDBOX_EC2_KEY_NAME"),
+ EC2WorkerImage: envOrDefault("OPENSANDBOX_EC2_WORKER_IMAGE", "opensandbox-worker:latest"),
+ EC2IAMInstanceProfile: os.Getenv("OPENSANDBOX_EC2_IAM_INSTANCE_PROFILE"),
+ EC2SSMParameterName: os.Getenv("OPENSANDBOX_EC2_SSM_AMI_PARAM"),
+
+ AzureSubscriptionID: os.Getenv("OPENSANDBOX_AZURE_SUBSCRIPTION_ID"),
+ AzureResourceGroup: os.Getenv("OPENSANDBOX_AZURE_RESOURCE_GROUP"),
+ AzureVMSize: envOrDefault("OPENSANDBOX_AZURE_VM_SIZE", "Standard_D16s_v5"),
+ AzureVMSizes: splitCSV(os.Getenv("OPENSANDBOX_AZURE_VM_SIZES")),
+ AzureImageID: os.Getenv("OPENSANDBOX_AZURE_IMAGE_ID"),
+ AzureSubnetID: os.Getenv("OPENSANDBOX_AZURE_SUBNET_ID"),
+ AzureSSHPublicKey: os.Getenv("OPENSANDBOX_AZURE_SSH_PUBLIC_KEY"),
+ AzureKeyVaultName: os.Getenv("OPENSANDBOX_AZURE_KEY_VAULT_NAME"),
AzureWorkerIdentityID: os.Getenv("OPENSANDBOX_AZURE_WORKER_IDENTITY_ID"),
CFAPIToken: os.Getenv("OPENSANDBOX_CF_API_TOKEN"),
@@ -410,8 +425,8 @@ func Load() (*Config, error) {
StripeSecretKey: os.Getenv("STRIPE_SECRET_KEY"),
StripeWebhookSecret: os.Getenv("STRIPE_WEBHOOK_SECRET"),
StripeTelegramAgentPriceID: os.Getenv("STRIPE_TELEGRAM_AGENT_PRICE_ID"),
- StripeSuccessURL: envOrDefault("STRIPE_SUCCESS_URL", "http://localhost:3000/billing?success=true"),
- StripeCancelURL: envOrDefault("STRIPE_CANCEL_URL", "http://localhost:3000/billing?cancelled=true"),
+ StripeSuccessURL: envOrDefault("STRIPE_SUCCESS_URL", "http://localhost:3000/billing?success=true"),
+ StripeCancelURL: envOrDefault("STRIPE_CANCEL_URL", "http://localhost:3000/billing?cancelled=true"),
SegmentWriteKey: os.Getenv("SEGMENT_WRITE_KEY"),
@@ -428,16 +443,16 @@ func Load() (*Config, error) {
SentrySampleRate: envOrDefaultFloat("OPENSANDBOX_SENTRY_SAMPLE_RATE", 1.0),
SentryTracesSampleRate: envOrDefaultFloat("OPENSANDBOX_SENTRY_TRACES_SAMPLE_RATE", 0.0),
- CellID: os.Getenv("OPENSANDBOX_CELL_ID"),
- PlatformOrgID: os.Getenv("OPENSANDBOX_PLATFORM_ORG_ID"),
- CFEventEndpoint: os.Getenv("OPENSANDBOX_CF_EVENT_ENDPOINT"),
- CFEventSecret: os.Getenv("OPENSANDBOX_CF_EVENT_SECRET"),
- CFAdminSecret: os.Getenv("OPENSANDBOX_CF_ADMIN_SECRET"),
- SessionJWTSecret: os.Getenv("OPENSANDBOX_SESSION_JWT_SECRET"),
- HaltListURL: os.Getenv("OPENSANDBOX_HALT_LIST_URL"),
- UsageParityURL: os.Getenv("OPENSANDBOX_USAGE_PARITY_URL"),
+ CellID: os.Getenv("OPENSANDBOX_CELL_ID"),
+ PlatformOrgID: os.Getenv("OPENSANDBOX_PLATFORM_ORG_ID"),
+ CFEventEndpoint: os.Getenv("OPENSANDBOX_CF_EVENT_ENDPOINT"),
+ CFEventSecret: os.Getenv("OPENSANDBOX_CF_EVENT_SECRET"),
+ CFAdminSecret: os.Getenv("OPENSANDBOX_CF_ADMIN_SECRET"),
+ SessionJWTSecret: os.Getenv("OPENSANDBOX_SESSION_JWT_SECRET"),
+ HaltListURL: os.Getenv("OPENSANDBOX_HALT_LIST_URL"),
+ UsageParityURL: os.Getenv("OPENSANDBOX_USAGE_PARITY_URL"),
ProBillingAuthority: os.Getenv("OPENSANDBOX_PRO_BILLING_AUTHORITY"),
- CFEdgeBaseURL: os.Getenv("OPENSANDBOX_CF_EDGE_BASE_URL"),
+ CFEdgeBaseURL: os.Getenv("OPENSANDBOX_CF_EDGE_BASE_URL"),
ComputeProvider: os.Getenv("OPENSANDBOX_COMPUTE_PROVIDER"),
SecretsProvider: envOrDefault("OPENSANDBOX_SECRETS_PROVIDER", "env"),
@@ -484,6 +499,15 @@ func Load() (*Config, error) {
cfg.Port = port
}
+ switch cfg.DashboardAuthMode {
+ case "", "single-tenant", "workos":
+ default:
+ return nil, fmt.Errorf(
+ "invalid OPENSANDBOX_DASHBOARD_AUTH_MODE %q (expected single-tenant or workos)",
+ cfg.DashboardAuthMode,
+ )
+ }
+
return cfg, nil
}
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
index 284551ea..06a75543 100644
--- a/internal/config/config_test.go
+++ b/internal/config/config_test.go
@@ -109,3 +109,32 @@ func TestLoadInvalidPort(t *testing.T) {
t.Fatal("expected error for invalid port, got nil")
}
}
+
+func TestLoadSingleTenantDashboardAuth(t *testing.T) {
+ t.Setenv("OPENSANDBOX_DASHBOARD_AUTH_MODE", " Single-Tenant ")
+ t.Setenv("OPENSANDBOX_DASHBOARD_USER_EMAIL", "[email protected]")
+ t.Setenv("OPENSANDBOX_DASHBOARD_TENANT_NAME", "Dev Tenant")
+ t.Setenv("OPENSANDBOX_DASHBOARD_TENANT_SLUG", "dev-tenant")
+
+ cfg, err := Load()
+ if err != nil {
+ t.Fatalf("Load() error: %v", err)
+ }
+ if cfg.DashboardAuthMode != "single-tenant" {
+ t.Fatalf("DashboardAuthMode = %q, want single-tenant", cfg.DashboardAuthMode)
+ }
+ if cfg.DashboardUserEmail != "[email protected]" {
+ t.Fatalf("DashboardUserEmail = %q", cfg.DashboardUserEmail)
+ }
+ if cfg.DashboardTenantName != "Dev Tenant" || cfg.DashboardTenantSlug != "dev-tenant" {
+ t.Fatalf("tenant = %q/%q", cfg.DashboardTenantName, cfg.DashboardTenantSlug)
+ }
+}
+
+func TestLoadRejectsUnknownDashboardAuthMode(t *testing.T) {
+ t.Setenv("OPENSANDBOX_DASHBOARD_AUTH_MODE", "anonymous")
+
+ if _, err := Load(); err == nil {
+ t.Fatal("Load() succeeded with an unknown dashboard auth mode")
+ }
+}
diff --git a/internal/db/single_tenant_pgfixture_test.go b/internal/db/single_tenant_pgfixture_test.go
new file mode 100644
index 00000000..97b94a5d
--- /dev/null
+++ b/internal/db/single_tenant_pgfixture_test.go
@@ -0,0 +1,72 @@
+//go:build pgfixture
+
+// Integration coverage for single-tenant bootstrap. Run against a disposable
+// Postgres database with:
+//
+// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/dbname?sslmode=disable \
+// go test -tags=pgfixture ./internal/db -run SingleTenant -v
+package db
+
+import (
+ "context"
+ "testing"
+
+ "github.com/google/uuid"
+)
+
+func TestEnsureSingleTenantPrincipalEnforcesProPlan_pgfixture(t *testing.T) {
+ store := openPgStore(t)
+ ctx := context.Background()
+ suffix := uuid.New().String()
+ slug := "single-tenant-" + suffix
+ email := "admin-" + suffix + "@example.test"
+
+ org, user, err := store.EnsureSingleTenantPrincipal(
+ ctx,
+ "Single Tenant Test",
+ slug,
+ email,
+ "Local Admin",
+ )
+ if err != nil {
+ t.Fatalf("first bootstrap: %v", err)
+ }
+ if org.Plan != "pro" {
+ t.Fatalf("first bootstrap plan = %q, want pro", org.Plan)
+ }
+
+ if err := store.UpdateOrgPlan(ctx, org.ID, "free"); err != nil {
+ t.Fatalf("reset plan to free: %v", err)
+ }
+
+ reloadedOrg, reloadedUser, err := store.EnsureSingleTenantPrincipal(
+ ctx,
+ "Single Tenant Test",
+ slug,
+ email,
+ "Local Admin",
+ )
+ if err != nil {
+ t.Fatalf("second bootstrap: %v", err)
+ }
+ if reloadedOrg.ID != org.ID || reloadedUser.ID != user.ID {
+ t.Fatalf(
+ "bootstrap identity changed: org %s -> %s, user %s -> %s",
+ org.ID,
+ reloadedOrg.ID,
+ user.ID,
+ reloadedUser.ID,
+ )
+ }
+ if reloadedOrg.Plan != "pro" {
+ t.Fatalf("second bootstrap plan = %q, want pro", reloadedOrg.Plan)
+ }
+
+ persisted, err := store.GetOrg(ctx, org.ID)
+ if err != nil {
+ t.Fatalf("reload persisted org: %v", err)
+ }
+ if persisted.Plan != "pro" {
+ t.Fatalf("persisted plan = %q, want pro", persisted.Plan)
+ }
+}
diff --git a/internal/db/store.go b/internal/db/store.go
index c772a1dc..3e9782c9 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -630,6 +630,58 @@ func (s *Store) GetUserByID(ctx context.Context, userID uuid.UUID) (*User, error
return user, nil
}
+// EnsureSingleTenantPrincipal returns a stable local organization and admin
+// user for an explicitly configured single-tenant dashboard. Single-tenant
+// deployments do not use the hosted free-tier billing gate, so the local org
+// is always promoted to Pro. The operation is idempotent so development
+// deployments can run it on every control-plane start.
+func (s *Store) EnsureSingleTenantPrincipal(ctx context.Context, orgName, orgSlug, email, name string) (*Org, *User, error) {
+ org, err := s.GetOrgBySlug(ctx, orgSlug)
+ if err != nil {
+ org, err = s.CreateOrg(ctx, orgName, orgSlug)
+ if err != nil {
+ // Another control-plane replica may have created it concurrently.
+ org, err = s.GetOrgBySlug(ctx, orgSlug)
+ if err != nil {
+ return nil, nil, fmt.Errorf("ensure single-tenant org: %w", err)
+ }
+ }
+ }
+ if org.Plan != "pro" {
+ if err := s.UpdateOrgPlan(ctx, org.ID, "pro"); err != nil {
+ return nil, nil, fmt.Errorf("promote single-tenant org to pro: %w", err)
+ }
+ org.Plan = "pro"
+ }
+
+ user, err := s.GetUserByEmail(ctx, email)
+ if err != nil {
+ user, err = s.CreateUser(ctx, org.ID, email, name, "admin")
+ if err != nil {
+ // As above, tolerate a concurrent bootstrap of the same identity.
+ user, err = s.GetUserByEmail(ctx, email)
+ if err != nil {
+ return nil, nil, fmt.Errorf("ensure single-tenant user: %w", err)
+ }
+ }
+ }
+ if user.OrgID != org.ID {
+ return nil, nil, fmt.Errorf(
+ "single-tenant user %q belongs to org %s, not configured org %s",
+ email, user.OrgID, org.ID,
+ )
+ }
+
+ if org.OwnerUserID == nil {
+ if err := s.SetOrgOwner(ctx, org.ID, user.ID); err != nil {
+ return nil, nil, fmt.Errorf("set single-tenant org owner: %w", err)
+ }
+ org.OwnerUserID = &user.ID
+ }
+
+ return org, user, nil
+}
+
// --- API Key operations ---
type APIKey struct {
diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.ts
index 9fba4ac1..86abcd64 100644
--- a/web/src/api/schemas.ts
+++ b/web/src/api/schemas.ts
@@ -19,6 +19,14 @@ export const MeResponseSchema = z.object({
email: z.string(),
orgId: z.string(),
orgs: z.array(OrgInfoSchema).optional(),
+ authMode: z.string().optional(),
+ capabilities: z
+ .object({
+ signOut: z.boolean(),
+ manageMembers: z.boolean(),
+ switchOrganizations: z.boolean(),
+ })
+ .optional(),
})
export const SandboxSchema = z.object({
diff --git a/web/src/components/ProtectedRoute.tsx b/web/src/components/ProtectedRoute.tsx
index 6fe0eb1b..7c20ec37 100644
--- a/web/src/components/ProtectedRoute.tsx
+++ b/web/src/components/ProtectedRoute.tsx
@@ -6,10 +6,9 @@ import { useAuth } from '@/hooks/useAuth'
export default function ProtectedRoute() {
const { user, loading } = useAuth()
- // Not authenticated → go straight to WorkOS. /auth/login is a server route
- // (proxied by Vite) that 302s to the WorkOS hosted login, so we do a
- // full-page navigation rather than an in-app route. No intermediate
- // "Sign in" screen — the spinner below shows until the browser leaves.
+ // Not authenticated → use the server-owned login route. Hosted identity
+ // providers redirect from there; single-tenant development mode returns a
+ // local user from /me and never enters this branch.
// Carry the requested URL as `returnTo` so the login round-trip lands the
// user back where they aimed (a shared session link, a /do deferred action)
// instead of the dashboard. The edge threads it through the WorkOS `state`.
diff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsx
index 9d3e79e7..c5d5103b 100644
--- a/web/src/components/app-shell.tsx
+++ b/web/src/components/app-shell.tsx
@@ -234,14 +234,16 @@ function SidebarNav({ onNavigate }: { onNavigate?: () => void }) {
<span className="text-foreground min-w-0 flex-1 truncate text-xs">
{user?.email}
</span>
- <button
- onClick={() => void logout()}
- aria-label="Sign out"
- title="Sign out"
- className="text-muted-foreground/40 hover:text-foreground flex size-7 shrink-0 items-center justify-center transition-colors"
- >
- <LogOut className="size-4" strokeWidth={1.5} aria-hidden />
- </button>
+ {user?.capabilities?.signOut !== false ? (
+ <button
+ onClick={() => void logout()}
+ aria-label="Sign out"
+ title="Sign out"
+ className="text-muted-foreground/40 hover:text-foreground flex size-7 shrink-0 items-center justify-center transition-colors"
+ >
+ <LogOut className="size-4" strokeWidth={1.5} aria-hidden />
+ </button>
+ ) : null}
</div>
</div>
</div>
diff --git a/web/src/hooks/useAuth.ts b/web/src/hooks/useAuth.ts
index 96630353..178ba375 100644
--- a/web/src/hooks/useAuth.ts
+++ b/web/src/hooks/useAuth.ts
@@ -6,6 +6,12 @@ export interface AuthUser {
email: string
orgId: string
orgs?: OrgInfo[]
+ authMode?: string
+ capabilities?: {
+ signOut: boolean
+ manageMembers: boolean
+ switchOrganizations: boolean
+ }
}
export interface AuthContextValue {
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 8db80b32..264bc10a 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -2,6 +2,7 @@ import { useState, type ReactNode } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { notifyError } from '@/lib/errors'
import { useTransientFlag } from '@/lib/use-transient-flag'
+import { useAuth } from '@/hooks/useAuth'
import {
deleteCustomDomain,
getInvitations,
@@ -63,6 +64,7 @@ function CodeBlock({ children }: { children: ReactNode }) {
export default function Settings() {
const queryClient = useQueryClient()
+ const { user } = useAuth()
const { data: org, isLoading } = useQuery({
queryKey: ['org'],
queryFn: getOrg,
@@ -307,12 +309,16 @@ export default function Settings() {
)}
</Panel>
- <div className="lg:col-span-2">
- <TeamMembers />
- </div>
- <div className="lg:col-span-2">
- <PendingInvitations />
- </div>
+ {user?.capabilities?.manageMembers !== false ? (
+ <>
+ <div className="lg:col-span-2">
+ <TeamMembers />
+ </div>
+ <div className="lg:col-span-2">
+ <PendingInvitations />
+ </div>
+ </>
+ ) : null}
</div>
<ConfirmDialog