An open-source, faster Devin alternative
TypeScript
feat(xcell): api-edge sandbox routing + CP /internal/sandboxes/create + capability tokens + D1 cells registry
Brian Reardonf0dab44e06a8
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 207e3447..d175c529 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -1,8 +1,17 @@// api-edge Worker — global API entry point.//-// All routes are placeholders — implementation lands in subsequent commits.-// Until then this Worker rejects everything with 501 Not Implemented except-// /health (so wrangler deploy succeeds and connectivity can be verified).+// Implemented so far (cross-cell test path):+// POST /api/sandboxes — auth (D1 api_keys) → pick org.home_cell →+// mint capability token → proxy to that cell's+// CP /internal/sandboxes/create → record in+// sandboxes_index → return the CP's response+// GET /api/sandboxes — list this org's sandboxes from sandboxes_index+// GET /api/sandboxes/:id — one row + cell_endpoint+// ANY /api/sandboxes/:id/* — 307 to the owning cell's CP (dumb-client path)+// GET /health+//+// Still 501 (not on the cross-cell test path): /auth/*, /webhooks/stripe,+// /internal/halt-list. See docs/dev-cutover-runbook.md.export { CreditAccount } from "../../shared/credit_account";@@ -21,28 +30,233 @@ export interface Env {CELLS: string;}+// ── small helpers ────────────────────────────────────────────────────────++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });+}++const b64url = (buf: ArrayBuffer | Uint8Array): string => {+ const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);+ let s = "";+ for (const b of bytes) s += String.fromCharCode(b);+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");+};++async function sha256Hex(s: string): Promise<string> {+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s));+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");+}++// Mint the capability token the regional CP expects on /internal/sandboxes/create:+// HS256 JWT signed with SESSION_JWT_SECRET, iss="opensandbox-edge", carrying+// org_id + cell_id (+ optional user_id). Mirrors auth.CapabilityClaims in Go.+async function mintCapToken(+ secret: string,+ orgID: string,+ cellID: string,+ userID: string | null,+): Promise<string> {+ const now = Math.floor(Date.now() / 1000);+ const header = { alg: "HS256", typ: "JWT" };+ const payload: Record<string, unknown> = {+ sub: orgID,+ iss: "opensandbox-edge",+ iat: now,+ exp: now + 120, // short-lived — it's only the edge→CP hop+ org_id: orgID,+ cell_id: cellID,+ };+ if (userID) payload.user_id = userID;+ const enc = new TextEncoder();+ const signingInput =+ b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));+ const key = await crypto.subtle.importKey(+ "raw",+ enc.encode(secret),+ { name: "HMAC", hash: "SHA-256" },+ false,+ ["sign"],+ );+ const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signingInput));+ return signingInput + "." + b64url(sig);+}++interface Caller {+ orgID: string;+ userID: string | null;+}++// Authenticate via X-API-Key (looked up by sha256 in D1 api_keys). Session-JWT+// auth (browser flows) is a TODO; SDK/test traffic uses the API key.+async function authenticate(req: Request, env: Env): Promise<Caller | null> {+ const apiKey = req.headers.get("X-API-Key");+ if (!apiKey) return null;+ const hash = await sha256Hex(apiKey);+ const row = await env.OPENCOMPUTER_DB.prepare(+ "SELECT org_id, created_by, expires_at FROM api_keys WHERE key_hash = ?1",+ )+ .bind(hash)+ .first<{ org_id: string; created_by: string | null; expires_at: number | null }>();+ if (!row) return null;+ if (row.expires_at && row.expires_at < Math.floor(Date.now() / 1000)) return null;+ // best-effort last_used bump+ env.OPENCOMPUTER_DB.prepare("UPDATE api_keys SET last_used = ?1 WHERE key_hash = ?2")+ .bind(Math.floor(Date.now() / 1000), hash)+ .run()+ .catch(() => {});+ return { orgID: row.org_id, userID: row.created_by };+}++interface CellRow {+ cell_id: string;+ base_url: string;+ status: string;+}++async function lookupCell(env: Env, cellID: string): Promise<CellRow | null> {+ return env.OPENCOMPUTER_DB.prepare(+ "SELECT cell_id, base_url, status FROM cells WHERE cell_id = ?1",+ )+ .bind(cellID)+ .first<CellRow>();+}++// ── route handlers ───────────────────────────────────────────────────────++async function createSandbox(req: Request, env: Env): Promise<Response> {+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);++ const org = await env.OPENCOMPUTER_DB.prepare("SELECT home_cell FROM orgs WHERE id = ?1")+ .bind(caller.orgID)+ .first<{ home_cell: string }>();+ if (!org) return json({ error: "org not found" }, 401);++ const cell = await lookupCell(env, org.home_cell);+ if (!cell) return json({ error: `home cell ${org.home_cell} not registered` }, 503);+ if (cell.status !== "active") return json({ error: `cell ${cell.cell_id} is ${cell.status}` }, 503);++ const capToken = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, caller.userID);++ const bodyText = await req.text();+ let cpResp: Response;+ try {+ cpResp = await fetch(cell.base_url.replace(/\/$/, "") + "/internal/sandboxes/create", {+ method: "POST",+ headers: { authorization: "Bearer " + capToken, "content-type": "application/json" },+ body: bodyText || "{}",+ });+ } catch (e) {+ return json({ error: `cell ${cell.cell_id} unreachable: ${(e as Error).message}` }, 502);+ }++ const cpText = await cpResp.text();+ if (cpResp.status >= 200 && cpResp.status < 300) {+ let parsed: { sandboxID?: string; workerID?: string; status?: string } = {};+ try {+ parsed = JSON.parse(cpText);+ } catch {+ /* leave parsed empty — still record what we can */+ }+ if (parsed.sandboxID) {+ await env.OPENCOMPUTER_DB.prepare(+ `INSERT OR REPLACE INTO sandboxes_index+ (id, org_id, user_id, cell_id, worker_id, status, created_at, last_event_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)`,+ )+ .bind(+ parsed.sandboxID,+ caller.orgID,+ caller.userID,+ cell.cell_id,+ parsed.workerID ?? null,+ parsed.status ?? "running",+ Math.floor(Date.now() / 1000),+ )+ .run();+ }+ }+ // Pass the CP's response through verbatim (status + body).+ return new Response(cpText, {+ status: cpResp.status,+ headers: { "content-type": "application/json" },+ });+}++async function listSandboxes(req: Request, env: Env): Promise<Response> {+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, cell_id, worker_id, status, template_id, created_at, last_event_at, stopped_at+ FROM sandboxes_index WHERE org_id = ?1 ORDER BY created_at DESC LIMIT 200`,+ )+ .bind(caller.orgID)+ .all();+ return json({ sandboxes: results });+}++async function getSandbox(req: Request, env: Env, id: string): Promise<Response> {+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);+ const row = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id, org_id, cell_id, worker_id, status, template_id, created_at, last_event_at, stopped_at+ FROM sandboxes_index WHERE id = ?1`,+ )+ .bind(id)+ .first<{ org_id: string; cell_id: string } & Record<string, unknown>>();+ if (!row || row.org_id !== caller.orgID) return json({ error: "sandbox not found" }, 404);+ const cell = await lookupCell(env, row.cell_id);+ return json({ ...row, cell_endpoint: cell ? cell.base_url : null });+}++// 307 the request to the owning cell's CP — same path + query, body preserved+// by the 307 semantics. Re-auth happens at the CP (API key / sandbox JWT).+async function redirectToCell(req: Request, env: Env, id: string, url: URL): Promise<Response> {+ const row = await env.OPENCOMPUTER_DB.prepare("SELECT cell_id FROM sandboxes_index WHERE id = ?1")+ .bind(id)+ .first<{ cell_id: string }>();+ if (!row) return json({ error: "sandbox not found" }, 404);+ const cell = await lookupCell(env, row.cell_id);+ if (!cell) return json({ error: `cell ${row.cell_id} not registered` }, 503);+ const target = cell.base_url.replace(/\/$/, "") + url.pathname + url.search;+ return new Response(null, { status: 307, headers: { location: target } });+}++// ── entrypoint ───────────────────────────────────────────────────────────+export default {async fetch(req: Request, env: Env): Promise<Response> {const url = new URL(req.url);+ const path = url.pathname;- if (url.pathname === "/health") {- return new Response(- JSON.stringify({ ok: true, env: env.WORKER_ENV, cells: env.CELLS.split(",") }),- { headers: { "content-type": "application/json" } },- );+ if (path === "/health") {+ return json({ ok: true, env: env.WORKER_ENV, cells: env.CELLS.split(",") });}- // TODO routes (in this order, see docs/dev-cutover-runbook.md):- // POST /auth/login- // POST /auth/refresh- // POST /auth/logout- // POST /webhooks/stripe- // POST /api/sandboxes — auth, /check on DO, cell select, cap-mint, proxy- // GET /api/sandboxes — D1 sandboxes_index- // GET /api/sandboxes/{id} — metadata + cell_endpoint- // ANY /api/sandboxes/{id}/* — 307 to {cell_id}.app.opensandbox.ai- // GET /internal/halt-list — HMAC, called by CP halt_reconciler+ // /api/sandboxes and /api/sandboxes/:id[/...]+ if (path === "/api/sandboxes") {+ if (req.method === "POST") return createSandbox(req, env);+ if (req.method === "GET") return listSandboxes(req, env);+ return json({ error: "method not allowed" }, 405);+ }+ const m = path.match(/^\/api\/sandboxes\/([^/]+)(\/.*)?$/);+ if (m) {+ const id = m[1];+ const rest = m[2]; // undefined for /api/sandboxes/:id, "/exec/run" etc otherwise+ if (!rest) {+ if (req.method === "GET") return getSandbox(req, env, id);+ if (req.method === "DELETE") return redirectToCell(req, env, id, url); // delete runs on the cell+ return json({ error: "method not allowed" }, 405);+ }+ // Anything under /:id/* (exec, files, pty, hibernate, …) lives on the cell.+ return redirectToCell(req, env, id, url);+ }+ // Not yet implemented: /auth/*, /webhooks/stripe, /internal/halt-list.return new Response("not implemented", { status: 501 });},} satisfies ExportedHandler<Env>;diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.tomlindex 106cba4f..56b67f0f 100644--- a/cloudflare-workers/api-edge/wrangler.toml+++ b/cloudflare-workers/api-edge/wrangler.toml@@ -50,6 +50,8 @@ new_sqlite_classes = ["CreditAccount"][vars]WORKER_ENV = "dev"-# Cells available in this deployment. The edge Worker uses this to validate-# cell_id selections and to construct cell_endpoint URLs.-CELLS = "azure-westus2-cell-a"+# Cells available in this deployment — comma-separated cell_ids. The edge+# validates cell selections against this list; each cell's base_url comes from+# the D1 `cells` table (see schema.sql + scripts/seed_dev_xcell.sh).+# Cross-cell testbed: dev2 (Azure westus2) + dev3 (AWS us-east-1).+CELLS = "azure-westus2-cell-b,aws-us-east-1-cell-a"diff --git a/cloudflare-workers/schema.sql b/cloudflare-workers/schema.sqlindex 7ca7a945..10373da0 100644--- a/cloudflare-workers/schema.sql+++ b/cloudflare-workers/schema.sql@@ -95,6 +95,25 @@ CREATE TABLE IF NOT EXISTS secret_store_entries (CREATE UNIQUE INDEX IF NOT EXISTS idx_secret_entries_unique ON secret_store_entries(store_id, name);CREATE INDEX IF NOT EXISTS idx_secret_entries_store ON secret_store_entries(store_id);+-- Cell registry ----------------------------------------------------------+-- One row per regional control plane. The edge Worker uses base_url to:+-- - proxy POST /api/sandboxes → {base_url}/internal/sandboxes/create+-- - dispatch admin callbacks → {base_url}/admin/halt-org, /admin/resume-org+-- - 307-redirect dumb clients → {base_url}/api/sandboxes/{id}/...+-- (In production the public 307 target and the internal edge→CP URL may+-- diverge — e.g. an internal-only hostname for /internal/*. Split into two+-- columns then; one URL is enough while every cell exposes both on one host.)+-- orgs.home_cell, sandboxes_index.cell_id, and events.cell_id all reference+-- cell_id here, but D1 has no cross-table FKs so it's by convention.+CREATE TABLE IF NOT EXISTS cells (+ cell_id TEXT PRIMARY KEY, -- "{cloud}-{region}-cell-{slot}"+ cloud TEXT NOT NULL, -- "azure" | "aws" | "gcp"+ region TEXT NOT NULL,+ base_url TEXT NOT NULL, -- regional CP base URL (scheme+host[:port])+ status TEXT NOT NULL DEFAULT 'active', -- active | draining | down+ created_at INTEGER NOT NULL+);+-- Global sandbox index (cross-region routing and listing) -----------------CREATE TABLE IF NOT EXISTS sandboxes_index (diff --git a/cmd/server/main.go b/cmd/server/main.goindex 9ad6e293..c2a431c4 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -55,10 +55,12 @@ func main() {// Build server optionsopts := &api.ServerOpts{- Mode: cfg.Mode,- WorkerID: cfg.WorkerID,- Region: cfg.Region,- HTTPAddr: cfg.HTTPAddr,+ Mode: cfg.Mode,+ WorkerID: cfg.WorkerID,+ Region: cfg.Region,+ HTTPAddr: cfg.HTTPAddr,+ CellID: cfg.CellID,+ SessionJWTSecret: cfg.SessionJWTSecret,}// Initialize PostgreSQL if configureddiff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.gonew file mode 100644index 00000000..f2737fa9--- /dev/null+++ b/internal/api/internal_sandbox.go@@ -0,0 +1,87 @@+package api++import (+ "net/http"+ "strings"++ "github.com/google/uuid"+ "github.com/labstack/echo/v4"++ "github.com/opensandbox/opensandbox/internal/auth"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// capClaimsKey is the echo.Context key under which capTokenMiddleware stashes+// the validated capability claims for downstream handlers.+const capClaimsKey = "cap_claims"++// capTokenMiddleware authenticates requests on the /internal/* group with a+// capability token (Authorization: Bearer <jwt>, HMAC-signed by the api-edge+// Worker with the shared session-JWT secret). It verifies the signature, the+// expiry, the issuer, and that the token's cell_id matches this control+// plane's cell — so a token minted for another cell can't be replayed here.+func (s *Server) capTokenMiddleware(next echo.HandlerFunc) echo.HandlerFunc {+ return func(c echo.Context) error {+ authHdr := c.Request().Header.Get("Authorization")+ if !strings.HasPrefix(authHdr, "Bearer ") {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "missing capability token"})+ }+ token := strings.TrimPrefix(authHdr, "Bearer ")+ claims, err := s.capTokenIssuer.ValidateCapabilityToken(token)+ if err != nil {+ return c.JSON(http.StatusForbidden, map[string]string{"error": "invalid capability token: " + err.Error()})+ }+ if claims.CellID != s.cellID {+ return c.JSON(http.StatusForbidden, map[string]string{+ "error": "capability token is for cell " + claims.CellID + ", this is " + s.cellID,+ })+ }+ c.Set(capClaimsKey, claims)+ return next(c)+ }+}++// internalCreateSandbox is the edge→CP create path: the api-edge Worker has+// already authenticated the caller (API key or session JWT against D1) and+// chosen this cell; it hands us a capability token carrying the org identity.+// We trust org_id from the token, run the normal worker-dispatch path, and+// return the same body as POST /api/sandboxes. The edge records the resulting+// sandbox in D1's sandboxes_index — we don't touch any global tables.+func (s *Server) internalCreateSandbox(c echo.Context) error {+ claims, _ := c.Get(capClaimsKey).(*auth.CapabilityClaims)+ if claims == nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "missing capability claims"})+ }+ orgID, err := uuid.Parse(claims.OrgID)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "capability token org_id is not a UUID"})+ }+ auth.SetOrgID(c, orgID)+ if claims.UserID != nil {+ if uid, uerr := uuid.Parse(*claims.UserID); uerr == nil {+ auth.SetUserID(c, uid)+ }+ }++ var cfg types.SandboxConfig+ if err := c.Bind(&cfg); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})+ }++ // Same defaults the public POST /api/sandboxes applies.+ if cfg.MemoryMB == 0 {+ cfg.MemoryMB = 4096+ cfg.CpuCount = 1+ }+ if cfg.DiskMB == 0 {+ cfg.DiskMB = 20480+ }+ if err := types.ValidateResourceTier(&cfg); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }++ // Reuse the normal remote-create path — picks a worker, dispatches via+ // gRPC, persists the session, writes the {sandboxID, token, status, ...}+ // response body.+ return s.createSandboxRemote(c, c.Request().Context(), cfg, orgID, true)+}diff --git a/internal/api/router.go b/internal/api/router.goindex 5fcd77d0..8bfb6dea 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -39,6 +39,8 @@ type Server struct {ptyManager *sandbox.PTYManagerstore *db.Store // nil in combined/dev mode without PGjwtIssuer *auth.JWTIssuer // nil if JWT not configured+ capTokenIssuer *auth.JWTIssuer // verifies edge→CP capability tokens; nil if SESSION_JWT_SECRET unset+ cellID string // this control plane's cell_id (for the cap-token cell check)mode string // "server", "worker", "combined"workerID string // this worker's IDregion string // this worker's region@@ -68,6 +70,8 @@ type pendingCreate struct {type ServerOpts struct {Store *db.StoreJWTIssuer *auth.JWTIssuer+ SessionJWTSecret string // shared edge↔CP HMAC secret; enables /internal/sandboxes/create+ CellID string // this control plane's cell_idMode string // "server", "worker", "combined"WorkerID stringRegion string@@ -102,6 +106,10 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oif opts != nil {s.store = opts.Stores.jwtIssuer = opts.JWTIssuer+ if opts.SessionJWTSecret != "" {+ s.capTokenIssuer = auth.NewJWTIssuer(opts.SessionJWTSecret)+ }+ s.cellID = opts.CellIDs.mode = opts.Modes.workerID = opts.WorkerIDs.region = opts.Region@@ -186,6 +194,15 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oe.GET("/api/sandboxes/:id/files/download", s.signedDownload)e.PUT("/api/sandboxes/:id/files/upload", s.signedUpload)+ // Internal routes — called by the api-edge Worker, authenticated by a+ // capability token (HMAC with the shared session-JWT secret). Only mounted+ // when that secret is configured and this is a server-mode CP that can+ // dispatch to workers.+ if s.capTokenIssuer != nil && s.workerRegistry != nil {+ internal := e.Group("/internal", s.capTokenMiddleware)+ internal.POST("/sandboxes/create", s.internalCreateSandbox)+ }+// API routes (with API key auth)api := e.Group("/api")api.Use(auth.PGAPIKeyMiddleware(s.store, apiKey))diff --git a/internal/auth/jwt.go b/internal/auth/jwt.goindex 7e8d26d1..d6ff4e80 100644--- a/internal/auth/jwt.go+++ b/internal/auth/jwt.go@@ -106,6 +106,68 @@ func (j *JWTIssuer) ValidateIdentityToken(tokenStr string) (*IdentityClaims, errreturn claims, nil}+// CapabilityClaims are the claims for a capability token: the short-lived JWT+// the api-edge Worker mints and hands to a regional control plane when it+// proxies POST /api/sandboxes. The CP trusts org_id from this token (the edge+// is the authority on org identity now) and rejects the token if cell_id+// doesn't match its own OPENSANDBOX_CELL_ID — so a token minted for cell A+// can't be replayed against cell B.+//+// Signed with the shared session-JWT secret (SESSION_JWT_SECRET / the CP's+// OPENSANDBOX_SESSION_JWT_SECRET). Distinguished from session JWTs by Issuer.+type CapabilityClaims struct {+ jwt.RegisteredClaims+ OrgID string `json:"org_id"`+ CellID string `json:"cell_id"`+ UserID *string `json:"user_id,omitempty"`+}++// CapabilityIssuer is the Issuer string on capability tokens — lets the CP+// reject a session JWT presented where a capability token is expected.+const CapabilityIssuer = "opensandbox-edge"++// IssueCapabilityToken mints a capability token for (orgID, cellID). userID may+// be nil (API-key-authenticated callers have no user).+func (j *JWTIssuer) IssueCapabilityToken(orgID, cellID string, userID *string, ttl time.Duration) (string, error) {+ now := time.Now()+ claims := CapabilityClaims{+ RegisteredClaims: jwt.RegisteredClaims{+ Subject: orgID,+ IssuedAt: jwt.NewNumericDate(now),+ ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),+ Issuer: CapabilityIssuer,+ },+ OrgID: orgID,+ CellID: cellID,+ UserID: userID,+ }+ token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)+ return token.SignedString(j.secret)+}++// ValidateCapabilityToken parses and validates a capability token. It checks+// the signature, expiry, and Issuer; the caller must additionally verify that+// claims.CellID matches the local cell.+func (j *JWTIssuer) ValidateCapabilityToken(tokenStr string) (*CapabilityClaims, error) {+ token, err := jwt.ParseWithClaims(tokenStr, &CapabilityClaims{}, func(t *jwt.Token) (interface{}, error) {+ if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {+ return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])+ }+ return j.secret, nil+ }, jwt.WithIssuer(CapabilityIssuer))+ if err != nil {+ return nil, fmt.Errorf("invalid capability token: %w", err)+ }+ claims, ok := token.Claims.(*CapabilityClaims)+ if !ok || !token.Valid {+ return nil, fmt.Errorf("invalid capability token claims")+ }+ if claims.OrgID == "" || claims.CellID == "" {+ return nil, fmt.Errorf("capability token missing org_id or cell_id")+ }+ return claims, nil+}+// SigningSecret returns the raw HMAC secret for use by other signing functions (e.g. signed URLs).func (j *JWTIssuer) SigningSecret() []byte { return j.secret }diff --git a/scripts/seed_dev_xcell.sh b/scripts/seed_dev_xcell.shnew file mode 100755index 00000000..e4e032d4--- /dev/null+++ b/scripts/seed_dev_xcell.sh@@ -0,0 +1,88 @@+#!/usr/bin/env bash+# seed_dev_xcell.sh — seed the dev D1 database with the fixtures needed for a+# cross-cell test: two cells, one user, two orgs (one homed in each cell), and+# one API key per org.+#+# Idempotent (INSERT OR REPLACE) — safe to re-run, e.g. once dev3's CP URL is+# known you can re-run with the real value.+#+# Usage:+# scripts/seed_dev_xcell.sh <DEV2_CP_URL> [DEV3_CP_URL]+#+# Example:+# scripts/seed_dev_xcell.sh http://20.94.201.157:8080 http://3.91.x.x:8080+#+# Requires: wrangler logged in to the CF account that owns `opencomputer-dev`+# (run `wrangler login` first, or export CLOUDFLARE_API_TOKEN).++set -euo pipefail++D1_DB="opencomputer-dev"+DEV2_CP_URL="${1:?usage: seed_dev_xcell.sh <DEV2_CP_URL> [DEV3_CP_URL]}"+DEV3_CP_URL="${2:-http://DEV3-CP-NOT-PROVISIONED-YET:8080}"++# Fixed test fixtures — deterministic so the smoke test knows exactly what to send.+ORG_A_ID="aaaaaaaa-0000-0000-0000-000000000001" # home_cell = azure-westus2-cell-b+ORG_B_ID="bbbbbbbb-0000-0000-0000-000000000001" # home_cell = aws-us-east-1-cell-a+USER_ID="cccccccc-0000-0000-0000-000000000001"+KEY_A_ID="a11ce11a-0000-0000-0000-000000000001"+KEY_B_ID="b11ce11b-0000-0000-0000-000000000001"++# Plaintext API keys (osb_ + 64 hex). Obviously-test values; the edge looks up+# by sha256(plaintext) so only the hash is stored.+KEY_A_PLAINTEXT="osb_a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0"+KEY_B_PLAINTEXT="osb_b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1"++sha256_hex() { printf '%s' "$1" | shasum -a 256 | cut -d' ' -f1; }+KEY_A_HASH="$(sha256_hex "$KEY_A_PLAINTEXT")"+KEY_B_HASH="$(sha256_hex "$KEY_B_PLAINTEXT")"+KEY_A_PREFIX="${KEY_A_PLAINTEXT:0:12}"+KEY_B_PREFIX="${KEY_B_PLAINTEXT:0:12}"++SQL_FILE="$(mktemp -t seed_dev_xcell.XXXXXX.sql)"+trap 'rm -f "$SQL_FILE"' EXIT++cat > "$SQL_FILE" <<SQL+-- Cells: the two regional control planes the edge will route between.+INSERT OR REPLACE INTO cells (cell_id, cloud, region, base_url, status, created_at) VALUES+ ('azure-westus2-cell-b', 'azure', 'westus2', '${DEV2_CP_URL}', 'active', strftime('%s','now')),+ ('aws-us-east-1-cell-a', 'aws', 'us-east-1', '${DEV3_CP_URL}', 'active', strftime('%s','now'));++-- One user, owner of both test orgs.+INSERT OR REPLACE INTO users (id, email, name, created_at) VALUES+ ('${USER_ID}', '[email protected]', 'X-Cell Test', strftime('%s','now'));++-- Two orgs, each homed in a different cell — so a create with each org's key+-- exercises a different cell.+INSERT OR REPLACE INTO orgs (id, name, slug, plan, home_cell, is_personal, owner_user_id, created_at, updated_at) VALUES+ ('${ORG_A_ID}', 'X-Cell Test A (dev2)', 'xcell-test-a', 'pro', 'azure-westus2-cell-b', 0, '${USER_ID}', strftime('%s','now'), strftime('%s','now')),+ ('${ORG_B_ID}', 'X-Cell Test B (dev3)', 'xcell-test-b', 'pro', 'aws-us-east-1-cell-a', 0, '${USER_ID}', strftime('%s','now'), strftime('%s','now'));++INSERT OR REPLACE INTO org_memberships (org_id, user_id, role, created_at) VALUES+ ('${ORG_A_ID}', '${USER_ID}', 'owner', strftime('%s','now')),+ ('${ORG_B_ID}', '${USER_ID}', 'owner', strftime('%s','now'));++-- One API key per org.+INSERT OR REPLACE INTO api_keys (id, org_id, created_by, key_hash, key_prefix, name, scopes, created_at) VALUES+ ('${KEY_A_ID}', '${ORG_A_ID}', '${USER_ID}', '${KEY_A_HASH}', '${KEY_A_PREFIX}', 'xcell-test-a', 'sandbox:*', strftime('%s','now')),+ ('${KEY_B_ID}', '${ORG_B_ID}', '${USER_ID}', '${KEY_B_HASH}', '${KEY_B_PREFIX}', 'xcell-test-b', 'sandbox:*', strftime('%s','now'));+SQL++echo "Applying seed to D1 '${D1_DB}' (remote)..."+echo " cell azure-westus2-cell-b -> ${DEV2_CP_URL}"+echo " cell aws-us-east-1-cell-a -> ${DEV3_CP_URL}"+wrangler d1 execute "$D1_DB" --remote --file "$SQL_FILE"++cat <<DONE++Seed applied. Test credentials:++ Org A (home_cell=azure-westus2-cell-b, expect sandbox on dev2):+ X-API-Key: ${KEY_A_PLAINTEXT}++ Org B (home_cell=aws-us-east-1-cell-a, expect sandbox on dev3):+ X-API-Key: ${KEY_B_PLAINTEXT}++If dev3 isn't provisioned yet, re-run this with its real CP URL once it is:+ scripts/seed_dev_xcell.sh ${DEV2_CP_URL} http://<dev3-cp-ip>:8080+DONE