An open-source, faster Devin alternative
TypeScript
ensure checks
Brian Reardon4df328209e67
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 123a1224..5c73051c 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -313,9 +313,11 @@ 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, plan, is_halted FROM orgs WHERE id = ?1")+ const org = await env.OPENCOMPUTER_DB.prepare(+ "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes FROM orgs WHERE id = ?1",+ ).bind(caller.orgID)- .first<{ home_cell: string; plan: string; is_halted: number }>();+ .first<{ home_cell: string; plan: string; is_halted: number; max_concurrent_sandboxes: number }>();if (!org) return json({ error: "org not found" }, 401);const plan = org.plan === "pro" ? "pro" : "free";@@ -358,6 +360,43 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {/* malformed JSON — let the CP reject with a proper 400 */}+ // Org-policy gates that used to live on the cell's public createSandbox+ // handler but were dropped from the edge-first internalCreateSandbox path+ // during cutover. Enforce them here in the edge — D1 has all the data+ // (org plan + max_concurrent_sandboxes + the active sandboxes_index+ // count) so we don't need a cell round-trip.+ //+ // Free-tier instance size: customers on the free plan can't request+ // bigger than 4GB / 1 vCPU. Pre-fix the limit was silently ignored at+ // the edge-first path; free users could spin up 64GB / 16 vCPU+ // instances at no cost.+ if (plan === "free" && (bodyMemoryMB > 4096 || bodyCpuCount > 1)) {+ return json({ error: "upgrade to pro for larger instances" }, 402);+ }++ // Concurrent sandbox limit: every plan has one. D1's sandboxes_index is+ // the cross-cell source of truth for active counts (status=running OR+ // hibernated counts toward the limit, since hibernated still costs+ // S3 storage). Pre-fix Jordan reported running 7 sandboxes against a+ // (displayed) limit of 5 — the gate wasn't enforced anywhere.+ const limit = org.max_concurrent_sandboxes ?? 5;+ const countRow = await env.OPENCOMPUTER_DB.prepare(+ "SELECT COUNT(*) AS n FROM sandboxes_index WHERE org_id = ?1 AND status IN ('running', 'hibernated')",+ )+ .bind(caller.orgID)+ .first<{ n: number }>();+ const active = countRow?.n ?? 0;+ if (active >= limit) {+ return json(+ {+ error: `concurrent sandbox limit reached (${active}/${limit}) — hibernate or delete one before creating another`,+ active,+ limit,+ },+ 429,+ );+ }+const cell = await pickCell(env, org.home_cell, requestedCellID);if (!cell) {return json(diff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.goindex 083ae9e3..64f0bb32 100644--- a/internal/api/internal_sandbox.go+++ b/internal/api/internal_sandbox.go@@ -1,6 +1,7 @@package apiimport (+ "fmt""net/http""strings"@@ -106,8 +107,13 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {if err := c.Bind(&cfg); err != nil {return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body: " + err.Error()})}+ // Default networkEnabled=true when caller omits it. Same as the public+ // createSandbox handler. Pre-fix the edge-first path persisted+ // networkEnabled=false (the zero value) into sandbox_sessions.config_json,+ // so forks of that sandbox inherited a no-network config.+ cfg.EnsureNetworkEnabledDefault()- // Same defaults the public POST /api/sandboxes applies.+ // Same memory/cpu defaults the public POST /api/sandboxes applies.if cfg.MemoryMB == 0 {cfg.MemoryMB = 4096cfg.CpuCount = 1@@ -119,6 +125,68 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})}+ // Disk size validation. Pre-fix any value was accepted — customer could+ // pass diskMB=1 (boot fails opaquely) or diskMB=10_000_000 (allocates+ // 10TB of storage per sandbox). Mirrors internal/api/sandbox.go bounds.+ if cfg.DiskMB < 20480 {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "diskMB must be at least 20480 (20GB)"})+ }+ if cfg.DiskMB > 262144 {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "diskMB cannot exceed 262144 (256GB)"})+ }+ // Per-org disk gates: free-tier capped at 20GB, paid orgs may have a+ // custom max_disk_mb. Look up the cell-local org (upserted at top of+ // this handler from the cap-token claims).+ if s.store != nil {+ if org, oerr := s.store.GetOrg(c.Request().Context(), orgID); oerr == nil && org != nil {+ if org.Plan == "free" && cfg.DiskMB > 20480 {+ return c.JSON(http.StatusPaymentRequired, map[string]string{"error": "upgrade to pro for larger disk sizes"})+ }+ maxDisk := org.MaxDiskMB+ if maxDisk == 0 {+ maxDisk = 20480+ }+ if cfg.DiskMB > maxDisk {+ return c.JSON(http.StatusForbidden, map[string]string{"error": fmt.Sprintf("disk size %dMB exceeds org limit of %dMB", cfg.DiskMB, maxDisk)})+ }+ }+ }++ // Declarative image or named snapshot → resolve to a checkpoint and use+ // the createFromCheckpoint flow. Mirrors the public createSandbox handler+ // (internal/api/sandbox.go) which gates on this same condition. Pre-fix+ // this branch was missing from internalCreateSandbox, so every customer+ // hitting POST /api/sandboxes through the edge-first path with an+ // `image` or `snapshot` field got a plain base sandbox — the manifest+ // was silently discarded by createSandboxRemote below. Confirmed by+ // reproducing with a `run` step that touched a marker file: file was+ // missing on the resulting sandbox.+ if len(cfg.ImageManifest) > 0 || cfg.Snapshot != "" {+ var checkpointID uuid.UUID+ var err error+ if cfg.Snapshot != "" {+ checkpointID, err = s.resolveSnapshot(c.Request().Context(), orgID, cfg.Snapshot)+ } else {+ checkpointID, err = s.resolveImageManifest(c.Request().Context(), orgID, cfg.ImageManifest, nil)+ }+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }++ // createFromCheckpointCore reads the checkpoint id from the+ // "checkpointId" path param. Inject it the same way the public+ // /api/sandboxes/from-checkpoint/:checkpointId route would.+ c.SetParamNames("checkpointId")+ c.SetParamValues(checkpointID.String())+ // Forward user-supplied envs + secret store + metadata so they're+ // applied at fork time. Same semantics as the public path.+ result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata)+ if cpErr != nil {+ return c.JSON(status, map[string]string{"error": cpErr.Error()})+ }+ return c.JSON(status, result)+ }+// Resolve secret store binding (if cfg.SecretStore is set). The edge-first// path puts the user's POST /api/sandboxes body through this handler// verbatim, so any caller passing {"secretStore": "<name>"} expects it to