Skip to content

An open-source, faster Devin alternative

TypeScript

Make preview URL creation idempotent and add custom domain support

motatoesbbb7eb000d79
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 981ae596..648b68f6 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -6,8 +6,10 @@ import (
"fmt"
"log"
"net/http"
+ "strings"
"time"
+ "github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/db"
@@ -784,6 +786,7 @@ func (s *Server) createPreviewURL(c echo.Context) error {
// Parse request body — port is required
var req struct {
Port int `json:"port"`
+ Domain string `json:"domain"`
AuthConfig json.RawMessage `json:"authConfig"`
}
if err := c.Bind(&req); err != nil {
@@ -819,25 +822,71 @@ func (s *Server) createPreviewURL(c echo.Context) error {
})
}
- // Check for duplicate port
+ // Look up org for custom domain support
+ org, err := s.store.GetOrg(ctx, orgID)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "failed to look up org",
+ })
+ }
+ var customDomain string
+ if org.CustomDomain != nil && *org.CustomDomain != "" {
+ customDomain = *org.CustomDomain
+ }
+
+ // If preview URL already exists for this port, return it
existing, err := s.store.GetPreviewURLByPort(ctx, sandboxID, req.Port)
if err == nil && existing != nil {
- return c.JSON(http.StatusConflict, map[string]string{
- "error": fmt.Sprintf("preview URL already exists for port %d", req.Port),
- })
+ return c.JSON(http.StatusOK, previewURLToMap(*existing, customDomain))
}
- // Build hostname: {sandboxID}-p{port}.{baseDomain}
- hostname := fmt.Sprintf("%s-p%d.%s", sandboxID, req.Port, s.sandboxDomain)
+ // Determine hostname based on whether a custom domain was requested
+ var hostname string
+ var cfHostnameID *string
- previewURL, err := s.store.CreatePreviewURL(ctx, sandboxID, orgID, hostname, req.Port, nil, "active", req.AuthConfig)
+ if req.Domain != "" {
+ // Validate the requested domain matches the org's verified custom domain
+ if customDomain == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "org has no custom domain configured",
+ })
+ }
+ if req.Domain != customDomain {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": fmt.Sprintf("domain %q does not match org custom domain %q", req.Domain, customDomain),
+ })
+ }
+ if org.DomainVerificationStatus != "active" {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": fmt.Sprintf("custom domain %q is not verified (status: %s)", req.Domain, org.DomainVerificationStatus),
+ })
+ }
+
+ hostname = fmt.Sprintf("%s-p%d.%s", sandboxID, req.Port, req.Domain)
+
+ // Register with Cloudflare if configured
+ if s.cfClient != nil {
+ cfResult, err := s.cfClient.CreateCustomHostnameHTTP(hostname)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "failed to register custom hostname with Cloudflare: " + err.Error(),
+ })
+ }
+ cfHostnameID = &cfResult.ID
+ }
+ } else {
+ // Default: use the platform sandbox domain
+ hostname = fmt.Sprintf("%s-p%d.%s", sandboxID, req.Port, s.sandboxDomain)
+ }
+
+ previewURL, err := s.store.CreatePreviewURL(ctx, sandboxID, orgID, hostname, req.Port, cfHostnameID, "active", req.AuthConfig)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": err.Error(),
})
}
- return c.JSON(http.StatusCreated, previewURL)
+ return c.JSON(http.StatusCreated, previewURLToMap(*previewURL, customDomain))
}
// listPreviewURLs returns all preview URLs for a sandbox.
@@ -850,17 +899,22 @@ func (s *Server) listPreviewURLs(c echo.Context) error {
})
}
+ orgID, _ := auth.GetOrgID(c)
+ customDomain := s.getOrgCustomDomain(c.Request().Context(), orgID)
+
urls, err := s.store.ListPreviewURLs(c.Request().Context(), sandboxID)
if err != nil {
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": err.Error(),
})
}
- if urls == nil {
- urls = []db.PreviewURL{}
+
+ result := make([]map[string]interface{}, len(urls))
+ for i, u := range urls {
+ result[i] = previewURLToMap(u, customDomain)
}
- return c.JSON(http.StatusOK, urls)
+ return c.JSON(http.StatusOK, result)
}
// deletePreviewURL removes the preview URL for a sandbox on a specific port.
@@ -901,6 +955,41 @@ func (s *Server) deletePreviewURL(c echo.Context) error {
return c.NoContent(http.StatusNoContent)
}
+// previewURLToMap converts a PreviewURL to a response map, including customHostname if provided.
+func previewURLToMap(u db.PreviewURL, customDomain string) map[string]interface{} {
+ m := map[string]interface{}{
+ "id": u.ID,
+ "sandboxId": u.SandboxID,
+ "orgId": u.OrgID,
+ "hostname": u.Hostname,
+ "port": u.Port,
+ "sslStatus": u.SSLStatus,
+ "authConfig": u.AuthConfig,
+ "createdAt": u.CreatedAt,
+ }
+ if u.CFHostnameID != nil {
+ m["cfHostnameId"] = *u.CFHostnameID
+ }
+ if customDomain != "" {
+ if dot := strings.Index(u.Hostname, "."); dot > 0 {
+ m["customHostname"] = u.Hostname[:dot+1] + customDomain
+ }
+ }
+ return m
+}
+
+// getOrgCustomDomain returns the org's custom domain, or "" if none.
+func (s *Server) getOrgCustomDomain(ctx context.Context, orgID uuid.UUID) string {
+ if s.store == nil {
+ return ""
+ }
+ org, err := s.store.GetOrg(ctx, orgID)
+ if err == nil && org.CustomDomain != nil && *org.CustomDomain != "" {
+ return *org.CustomDomain
+ }
+ return ""
+}
+
// cleanupPreviewURLs removes all preview URLs for a sandbox on kill (best-effort).
func (s *Server) cleanupPreviewURLs(ctx context.Context, sandboxID string) {
if s.store == nil {
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 7cae976b..3d106203 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -184,11 +184,20 @@ class Sandbox:
pty_key = self._token or self._api_key
return Pty(self._ops_client, self.sandbox_id, pty_url, pty_key)
- async def create_preview_url(self, port: int, auth_config: dict | None = None) -> dict:
- """Create a preview URL targeting a specific container port."""
+ async def create_preview_url(self, port: int, domain: str | None = None, auth_config: dict | None = None) -> dict:
+ """Create a preview URL targeting a specific container port.
+
+ Args:
+ port: The container port to expose (1-65535).
+ domain: Optional custom domain (must be verified on the org).
+ auth_config: Optional auth configuration for the preview URL.
+ """
+ body: dict = {"port": port, "authConfig": auth_config or {}}
+ if domain:
+ body["domain"] = domain
resp = await self._client.post(
f"/sandboxes/{self.sandbox_id}/preview",
- json={"port": port, "authConfig": auth_config or {}},
+ json=body,
)
resp.raise_for_status()
return resp.json()
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index c480a192..f123b6a0 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -31,6 +31,7 @@ export interface PreviewURLResult {
sandboxId: string;
orgId: string;
hostname: string;
+ customHostname?: string;
port: number;
cfHostnameId?: string;
sslStatus: string;
@@ -206,14 +207,14 @@ export class Sandbox {
}
}
- async createPreviewURL(opts: { port: number; authConfig?: Record<string, unknown> }): Promise<PreviewURLResult> {
+ async createPreviewURL(opts: { port: number; domain?: string; authConfig?: Record<string, unknown> }): Promise<PreviewURLResult> {
const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...(this.apiKey ? { "X-API-Key": this.apiKey } : {}),
},
- body: JSON.stringify({ port: opts.port, authConfig: opts.authConfig ?? {} }),
+ body: JSON.stringify({ port: opts.port, ...(opts.domain ? { domain: opts.domain } : {}), authConfig: opts.authConfig ?? {} }),
});
if (!resp.ok) {
diff --git a/test-preview-urls.ts b/test-preview-urls.ts
new file mode 100644
index 00000000..ce249519
--- /dev/null
+++ b/test-preview-urls.ts
@@ -0,0 +1,165 @@
+/**
+ * Test script for preview URLs with hibernate/wake cycle.
+ * Tests idempotent creation, custom domain support, and hibernate persistence.
+ *
+ * Usage:
+ * OPENCOMPUTER_API_KEY=<key> npx tsx test-preview-urls.ts
+ *
+ * Optional env vars:
+ * CUSTOM_DOMAIN=mycompany.com — test custom domain preview URLs
+ */
+
+import { Sandbox, type PreviewURLResult } from "./sdks/typescript/src/sandbox";
+import * as readline from "readline";
+
+function assert(cond: boolean, msg: string) {
+ if (!cond) { console.error(` FAIL: ${msg}`); process.exit(1); }
+ console.log(` PASS: ${msg}`);
+}
+
+function waitForEnter(prompt: string): Promise<void> {
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
+ return new Promise(resolve => {
+ rl.question(prompt, () => { rl.close(); resolve(); });
+ });
+}
+
+const PORTS = [3000, 8080, 5173];
+const CUSTOM_DOMAIN = process.env.CUSTOM_DOMAIN || "";
+
+async function startServers(sandbox: Sandbox) {
+ for (const port of PORTS) {
+ await sandbox.commands.run(
+ `sh -c 'mkdir -p /tmp/www-${port} && cat > /tmp/www-${port}/index.html << "HTMLEOF"
+<!DOCTYPE html><html><head><title>Port ${port}</title></head>
+<body style="font-family:system-ui;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#0f172a;color:#e2e8f0">
+<div style="text-align:center">
+<h1 style="color:#3b82f6">Port ${port}</h1>
+<p style="color:#64748b;font-size:0.875rem">Each port gets its own preview URL</p>
+</div></body></html>
+HTMLEOF'`,
+ );
+ await sandbox.commands.run(`busybox httpd -p ${port} -h /tmp/www-${port}`);
+ console.log(` PASS: server started on port ${port}`);
+ }
+}
+
+async function main() {
+ let sandbox: Sandbox | null = null;
+
+ try {
+ // ── 1. Create sandbox ──────────────────────────────────────────────
+ console.log("\n1. Creating sandbox...");
+ sandbox = await Sandbox.create({ template: "base", timeout: 300 });
+ console.log(` sandboxId = ${sandbox.sandboxId}`);
+ assert(sandbox.status === "running", `status = ${sandbox.status}`);
+
+ // ── 2. Start HTTP servers ──────────────────────────────────────────
+ console.log(`\n2. Starting HTTP servers on ports ${PORTS.join(", ")}...`);
+ await startServers(sandbox);
+
+ // ── 3. Create preview URLs ─────────────────────────────────────────
+ console.log("\n3. Creating preview URLs...");
+ const previews: PreviewURLResult[] = [];
+ for (const port of PORTS) {
+ const opts: { port: number; domain?: string } = { port };
+ if (CUSTOM_DOMAIN) opts.domain = CUSTOM_DOMAIN;
+ const pv = await sandbox.createPreviewURL(opts);
+ assert(pv.port === port, `port = ${pv.port}`);
+ assert(pv.hostname.includes(sandbox.sandboxId), `hostname contains sandbox ID`);
+ if (CUSTOM_DOMAIN) {
+ assert(pv.hostname.endsWith(CUSTOM_DOMAIN), `hostname ends with custom domain`);
+ }
+ if (pv.customHostname) {
+ console.log(` customHostname: ${pv.customHostname}`);
+ }
+ previews.push(pv);
+ }
+
+ // ── 4. Idempotent re-creation ──────────────────────────────────────
+ console.log("\n4. Re-creating same preview URLs (idempotent)...");
+ for (const port of PORTS) {
+ const opts: { port: number; domain?: string } = { port };
+ if (CUSTOM_DOMAIN) opts.domain = CUSTOM_DOMAIN;
+ const pv = await sandbox.createPreviewURL(opts);
+ assert(pv.port === port, `idempotent: port ${port} returned`);
+ const original = previews.find(p => p.port === port)!;
+ assert(pv.id === original.id, `idempotent: same id for port ${port}`);
+ assert(pv.hostname === original.hostname, `idempotent: same hostname for port ${port}`);
+ }
+
+ console.log(`\n${"=".repeat(60)}`);
+ console.log(" Preview URLs:\n");
+ for (const pv of previews) {
+ const displayHost = pv.customHostname || pv.hostname;
+ console.log(` port ${pv.port} → https://${displayHost}`);
+ }
+ console.log(`\n Dashboard: https://app.opencomputer.dev/sessions/${sandbox.sandboxId}`);
+ console.log(`${"=".repeat(60)}\n`);
+
+ // ── 5. List preview URLs ───────────────────────────────────────────
+ console.log("5. Listing preview URLs...");
+ const listed = await sandbox.listPreviewURLs();
+ assert(listed.length === PORTS.length, `list returns ${PORTS.length} URLs`);
+ for (const u of listed) {
+ if (CUSTOM_DOMAIN) {
+ assert(!!u.customHostname, `list: customHostname present for port ${u.port}`);
+ }
+ }
+
+ await waitForEnter("Check dashboard shows preview URLs, then press Enter to hibernate...\n");
+
+ // ── 6. Hibernate ───────────────────────────────────────────────────
+ console.log("\n6. Hibernating sandbox...");
+ await sandbox.hibernate();
+ console.log(" PASS: hibernated");
+
+ // Verify preview URLs still in DB
+ const listHibernated = await sandbox.listPreviewURLs();
+ assert(listHibernated.length === PORTS.length, `preview URLs after hibernate = ${listHibernated.length}`);
+
+ await waitForEnter("Check dashboard shows preview URLs while hibernated, then press Enter to wake...\n");
+
+ // ── 7. Wake ────────────────────────────────────────────────────────
+ console.log("\n7. Waking sandbox...");
+ await sandbox.wake({ timeout: 300 });
+ console.log(" PASS: woken");
+
+ // Verify preview URLs still persist
+ const listWoken = await sandbox.listPreviewURLs();
+ assert(listWoken.length === PORTS.length, `preview URLs after wake = ${listWoken.length}`);
+
+ // Restart servers (processes don't survive hibernate on base template)
+ console.log("\n8. Restarting HTTP servers...");
+ await startServers(sandbox);
+
+ console.log(`\n${"=".repeat(60)}`);
+ console.log(" URLs should still work after wake:\n");
+ for (const pv of previews) {
+ const displayHost = pv.customHostname || pv.hostname;
+ console.log(` port ${pv.port} → https://${displayHost}`);
+ }
+ console.log(`\n Dashboard: https://app.opencomputer.dev/sessions/${sandbox.sandboxId}`);
+ console.log(`${"=".repeat(60)}\n`);
+
+ await waitForEnter("Check dashboard + URLs after wake, then press Enter to kill...\n");
+
+ // ── 9. Kill ────────────────────────────────────────────────────────
+ console.log("\n9. Killing sandbox...");
+ await sandbox.kill();
+ sandbox = null;
+ console.log(" PASS: sandbox killed");
+
+ console.log("\n All tests passed!\n");
+ } catch (err) {
+ console.error("\nTest error:", err);
+ process.exit(1);
+ } finally {
+ if (sandbox) {
+ console.log(`\nCleaning up sandbox ${sandbox.sandboxId}...`);
+ await sandbox.kill().catch(() => {});
+ }
+ }
+}
+
+main();