Skip to content

An open-source, faster Devin alternative

TypeScript

Refactor preview URLs to explicit port-based model with placeholder page

motatoesd8ae333409fe
diff --git a/cmd/server/main.go b/cmd/server/main.go
index d68f1c57..b9fbe6f7 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -182,9 +182,6 @@ func main() {
// Initialize subdomain reverse proxy
if cfg.SandboxDomain != "" {
sbProxy := proxy.New(cfg.SandboxDomain, mgr, sbRouter)
- if opts.Store != nil {
- sbProxy.SetStore(opts.Store)
- }
opts.SandboxProxy = sbProxy
opts.SandboxDomain = cfg.SandboxDomain
log.Printf("opensandbox: subdomain proxy configured (*.%s)", cfg.SandboxDomain)
diff --git a/internal/api/dashboard.go b/internal/api/dashboard.go
index 76781151..b15940bb 100644
--- a/internal/api/dashboard.go
+++ b/internal/api/dashboard.go
@@ -558,11 +558,6 @@ func (s *Server) dashboardGetSession(c echo.Context) error {
resp["errorMsg"] = *session.ErrorMsg
}
- // Compute domain (prefer org custom domain if verified)
- if domain := s.sandboxDomainForOrg(c.Request().Context(), orgID); domain != "" {
- resp["domain"] = fmt.Sprintf("%s.%s", sandboxID, domain)
- }
-
// Parse config JSON if available
if len(session.Config) > 0 {
var cfg map[string]interface{}
@@ -583,10 +578,12 @@ func (s *Server) dashboardGetSession(c echo.Context) error {
}
}
- // Include preview URL if one exists
- previewURL, err := s.store.GetPreviewURL(c.Request().Context(), sandboxID)
- if err == nil && previewURL != nil {
- resp["previewUrl"] = previewURL
+ // Include preview URLs
+ urls, err := s.store.ListPreviewURLs(c.Request().Context(), sandboxID)
+ if err == nil && len(urls) > 0 {
+ resp["previewUrls"] = urls
+ } else {
+ resp["previewUrls"] = []interface{}{}
}
return c.JSON(http.StatusOK, resp)
diff --git a/internal/api/router.go b/internal/api/router.go
index 7721cfe3..44955600 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -127,10 +127,10 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.POST("/sandboxes/:id/hibernate", s.hibernateSandbox)
api.POST("/sandboxes/:id/wake", s.wakeSandbox)
- // Preview URLs (on-demand custom domain)
+ // Preview URLs (on-demand port-based)
api.POST("/sandboxes/:id/preview", s.createPreviewURL)
- api.GET("/sandboxes/:id/preview", s.getPreviewURL)
- api.DELETE("/sandboxes/:id/preview", s.deletePreviewURL)
+ api.GET("/sandboxes/:id/preview", s.listPreviewURLs)
+ api.DELETE("/sandboxes/:id/preview/:port", s.deletePreviewURL)
// Commands
api.POST("/sandboxes/:id/commands", s.runCommand)
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 32f38df1..981ae596 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -8,18 +8,13 @@ import (
"net/http"
"time"
- "github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/pkg/types"
pb "github.com/opensandbox/opensandbox/proto/worker"
)
-// sandboxDomainForOrg returns the global sandbox domain (e.g. workers.opencomputer.dev).
-// Custom domain preview URLs are created on-demand via the /preview endpoints.
-func (s *Server) sandboxDomainForOrg(ctx context.Context, orgID uuid.UUID) string {
- return s.sandboxDomain
-}
func (s *Server) createSandbox(c echo.Context) error {
var cfg types.SandboxConfig
@@ -108,11 +103,6 @@ func (s *Server) createSandbox(c echo.Context) error {
}
}
- // Assign subdomain (prefer org custom domain if verified)
- if domain := s.sandboxDomainForOrg(ctx, orgID); domain != "" {
- sb.Domain = fmt.Sprintf("%s.%s", sb.ID, domain)
- }
-
// Write session record to PG if available
if s.store != nil && hasOrg {
cfgJSON, _ := json.Marshal(cfg)
@@ -212,9 +202,6 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
"region": region,
"workerID": worker.ID,
}
- if domain := s.sandboxDomainForOrg(ctx, orgID); domain != "" {
- resp["domain"] = fmt.Sprintf("%s.%s", grpcResp.SandboxId, domain)
- }
return c.JSON(http.StatusCreated, resp)
}
@@ -249,10 +236,6 @@ func (s *Server) getSandbox(c echo.Context) error {
}
}
- if domain := s.sandboxDomainForOrg(c.Request().Context(), orgID); domain != "" {
- sb.Domain = fmt.Sprintf("%s.%s", id, domain)
- }
-
return c.JSON(http.StatusOK, sb)
}
@@ -273,7 +256,6 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {
}
orgID, _ := auth.GetOrgID(c)
- domain := s.sandboxDomainForOrg(c.Request().Context(), orgID)
// Hibernated sandboxes have no worker
if session.Status == "hibernated" {
@@ -284,9 +266,6 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {
"template": session.Template,
"startedAt": session.StartedAt,
}
- if domain != "" {
- resp["domain"] = fmt.Sprintf("%s.%s", sandboxID, domain)
- }
return c.JSON(http.StatusOK, resp)
}
@@ -316,9 +295,6 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {
"startedAt": session.StartedAt,
"template": session.Template,
}
- if domain != "" {
- resp["domain"] = fmt.Sprintf("%s.%s", sandboxID, domain)
- }
return c.JSON(http.StatusOK, resp)
}
@@ -349,7 +325,7 @@ func (s *Server) killSandbox(c echo.Context) error {
if s.store != nil {
_ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), id, "stopped", nil)
- s.cleanupPreviewURL(c.Request().Context(), id)
+ s.cleanupPreviewURLs(c.Request().Context(), id)
}
if s.sandboxDBs != nil {
@@ -392,7 +368,7 @@ func (s *Server) killSandboxRemote(c echo.Context, sandboxID string) error {
}
_ = s.store.UpdateSandboxSessionStatus(c.Request().Context(), sandboxID, "stopped", nil)
- s.cleanupPreviewURL(c.Request().Context(), sandboxID)
+ s.cleanupPreviewURLs(c.Request().Context(), sandboxID)
return c.NoContent(http.StatusNoContent)
}
@@ -608,9 +584,6 @@ func (s *Server) hibernateSandboxRemote(c echo.Context, sandboxID string) error
"checkpointKey": grpcResp.CheckpointKey,
"sizeBytes": grpcResp.SizeBytes,
}
- if domain := s.sandboxDomainForOrg(c.Request().Context(), orgID); domain != "" {
- resp["domain"] = fmt.Sprintf("%s.%s", sandboxID, domain)
- }
return c.JSON(http.StatusOK, resp)
}
@@ -675,9 +648,6 @@ func (s *Server) wakeSandbox(c echo.Context) error {
}
sb.ConnectURL = s.httpAddr
- if domain := s.sandboxDomainForOrg(ctx, orgID); domain != "" {
- sb.Domain = fmt.Sprintf("%s.%s", id, domain)
- }
return c.JSON(http.StatusOK, sb)
}
@@ -751,9 +721,6 @@ func (s *Server) wakeSandboxRemote(c echo.Context, sandboxID string, req types.W
"region": region,
"workerID": worker.ID,
}
- if domain := s.sandboxDomainForOrg(c.Request().Context(), orgID); domain != "" {
- resp["domain"] = fmt.Sprintf("%s.%s", sandboxID, domain)
- }
return c.JSON(http.StatusOK, resp)
}
@@ -796,7 +763,7 @@ func (s *Server) listSessions(c echo.Context) error {
// --- Preview URL handlers ---
// createPreviewURL creates an on-demand preview URL for a running sandbox
-// using the org's verified custom domain.
+// targeting a specific container port. Hostname format: {sandboxID}-p{port}.{baseDomain}
func (s *Server) createPreviewURL(c echo.Context) error {
sandboxID := c.Param("id")
ctx := c.Request().Context()
@@ -806,11 +773,6 @@ func (s *Server) createPreviewURL(c echo.Context) error {
"error": "database not configured",
})
}
- if s.cfClient == nil {
- return c.JSON(http.StatusServiceUnavailable, map[string]string{
- "error": "Cloudflare not configured",
- })
- }
orgID, ok := auth.GetOrgID(c)
if !ok {
@@ -819,6 +781,25 @@ func (s *Server) createPreviewURL(c echo.Context) error {
})
}
+ // Parse request body — port is required
+ var req struct {
+ Port int `json:"port"`
+ AuthConfig json.RawMessage `json:"authConfig"`
+ }
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "invalid request body: " + err.Error(),
+ })
+ }
+ if req.Port < 1 || req.Port > 65535 {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "port must be between 1 and 65535",
+ })
+ }
+ if req.AuthConfig == nil {
+ req.AuthConfig = json.RawMessage("{}")
+ }
+
// Verify sandbox is running
sandboxRunning := false
if s.manager != nil {
@@ -838,57 +819,19 @@ func (s *Server) createPreviewURL(c echo.Context) error {
})
}
- // Check if preview URL already exists
- existing, err := s.store.GetPreviewURL(ctx, sandboxID)
+ // Check for duplicate port
+ existing, err := s.store.GetPreviewURLByPort(ctx, sandboxID, req.Port)
if err == nil && existing != nil {
return c.JSON(http.StatusConflict, map[string]string{
- "error": "preview URL already exists for this sandbox",
- })
- }
-
- // Check org has verified custom domain
- org, err := s.store.GetOrg(ctx, orgID)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": err.Error(),
- })
- }
- if org.CustomDomain == nil || *org.CustomDomain == "" || org.DomainVerificationStatus != "active" {
- return c.JSON(http.StatusBadRequest, map[string]string{
- "error": "org does not have a verified custom domain",
- })
- }
-
- // Parse optional auth config
- var req struct {
- AuthConfig json.RawMessage `json:"authConfig"`
- }
- _ = c.Bind(&req)
- if req.AuthConfig == nil {
- req.AuthConfig = json.RawMessage("{}")
- }
-
- // Build hostname: <sandbox-id>.<org-custom-domain>
- hostname := fmt.Sprintf("%s.%s", sandboxID, *org.CustomDomain)
-
- // Create Cloudflare custom hostname (HTTP DCV — auto-validates via CNAME)
- cfResult, err := s.cfClient.CreateCustomHostnameHTTP(hostname)
- if err != nil {
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": "Cloudflare API error: " + err.Error(),
+ "error": fmt.Sprintf("preview URL already exists for port %d", req.Port),
})
}
- cfID := cfResult.ID
- sslStatus := cfResult.SSL.Status
- if sslStatus == "" {
- sslStatus = "initializing"
- }
+ // Build hostname: {sandboxID}-p{port}.{baseDomain}
+ hostname := fmt.Sprintf("%s-p%d.%s", sandboxID, req.Port, s.sandboxDomain)
- previewURL, err := s.store.CreatePreviewURL(ctx, sandboxID, orgID, hostname, &cfID, sslStatus, req.AuthConfig)
+ previewURL, err := s.store.CreatePreviewURL(ctx, sandboxID, orgID, hostname, req.Port, nil, "active", req.AuthConfig)
if err != nil {
- // Best-effort cleanup of the CF hostname we just created
- _ = s.cfClient.DeleteCustomHostname(cfID)
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": err.Error(),
})
@@ -897,8 +840,8 @@ func (s *Server) createPreviewURL(c echo.Context) error {
return c.JSON(http.StatusCreated, previewURL)
}
-// getPreviewURL returns the preview URL for a sandbox.
-func (s *Server) getPreviewURL(c echo.Context) error {
+// listPreviewURLs returns all preview URLs for a sandbox.
+func (s *Server) listPreviewURLs(c echo.Context) error {
sandboxID := c.Param("id")
if s.store == nil {
@@ -907,19 +850,23 @@ func (s *Server) getPreviewURL(c echo.Context) error {
})
}
- previewURL, err := s.store.GetPreviewURL(c.Request().Context(), sandboxID)
+ urls, err := s.store.ListPreviewURLs(c.Request().Context(), sandboxID)
if err != nil {
- return c.JSON(http.StatusNotFound, map[string]string{
- "error": "no preview URL for this sandbox",
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": err.Error(),
})
}
+ if urls == nil {
+ urls = []db.PreviewURL{}
+ }
- return c.JSON(http.StatusOK, previewURL)
+ return c.JSON(http.StatusOK, urls)
}
-// deletePreviewURL removes the preview URL for a sandbox, cleaning up the CF hostname.
+// deletePreviewURL removes the preview URL for a sandbox on a specific port.
func (s *Server) deletePreviewURL(c echo.Context) error {
sandboxID := c.Param("id")
+ portStr := c.Param("port")
ctx := c.Request().Context()
if s.store == nil {
@@ -928,14 +875,21 @@ func (s *Server) deletePreviewURL(c echo.Context) error {
})
}
- previewURL, err := s.store.GetPreviewURL(ctx, sandboxID)
+ port := 0
+ if _, err := fmt.Sscanf(portStr, "%d", &port); err != nil || port < 1 || port > 65535 {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "invalid port",
+ })
+ }
+
+ previewURL, err := s.store.GetPreviewURLByPort(ctx, sandboxID, port)
if err != nil {
return c.JSON(http.StatusNotFound, map[string]string{
- "error": "no preview URL for this sandbox",
+ "error": "no preview URL for this port",
})
}
- // Delete from Cloudflare
+ // Delete from Cloudflare if applicable (for legacy custom domain URLs)
if s.cfClient != nil && previewURL.CFHostnameID != nil && *previewURL.CFHostnameID != "" {
if err := s.cfClient.DeleteCustomHostname(*previewURL.CFHostnameID); err != nil {
log.Printf("preview: failed to delete CF hostname %s: %v", *previewURL.CFHostnameID, err)
@@ -947,18 +901,20 @@ func (s *Server) deletePreviewURL(c echo.Context) error {
return c.NoContent(http.StatusNoContent)
}
-// cleanupPreviewURL removes the preview URL for a sandbox on kill (best-effort).
-func (s *Server) cleanupPreviewURL(ctx context.Context, sandboxID string) {
+// 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 {
return
}
- previewURL, err := s.store.DeletePreviewURLBySandbox(ctx, sandboxID)
+ urls, err := s.store.DeletePreviewURLsBySandbox(ctx, sandboxID)
if err != nil {
- return // no preview URL, nothing to clean up
+ return
}
- if s.cfClient != nil && previewURL.CFHostnameID != nil && *previewURL.CFHostnameID != "" {
- if err := s.cfClient.DeleteCustomHostname(*previewURL.CFHostnameID); err != nil {
- log.Printf("preview: cleanup failed for CF hostname %s: %v", *previewURL.CFHostnameID, err)
+ for _, u := range urls {
+ if s.cfClient != nil && u.CFHostnameID != nil && *u.CFHostnameID != "" {
+ if err := s.cfClient.DeleteCustomHostname(*u.CFHostnameID); err != nil {
+ log.Printf("preview: cleanup failed for CF hostname %s: %v", *u.CFHostnameID, err)
+ }
}
}
}
diff --git a/internal/db/migrations/007_preview_urls_port.down.sql b/internal/db/migrations/007_preview_urls_port.down.sql
new file mode 100644
index 00000000..44b5f3a3
--- /dev/null
+++ b/internal/db/migrations/007_preview_urls_port.down.sql
@@ -0,0 +1,3 @@
+DROP INDEX IF EXISTS idx_preview_urls_hostname;
+ALTER TABLE sandbox_preview_urls DROP CONSTRAINT IF EXISTS uq_preview_url_sandbox_port;
+ALTER TABLE sandbox_preview_urls DROP COLUMN IF EXISTS port;
diff --git a/internal/db/migrations/007_preview_urls_port.up.sql b/internal/db/migrations/007_preview_urls_port.up.sql
new file mode 100644
index 00000000..72fbc1ba
--- /dev/null
+++ b/internal/db/migrations/007_preview_urls_port.up.sql
@@ -0,0 +1,3 @@
+ALTER TABLE sandbox_preview_urls ADD COLUMN port INTEGER NOT NULL DEFAULT 80;
+ALTER TABLE sandbox_preview_urls ADD CONSTRAINT uq_preview_url_sandbox_port UNIQUE (sandbox_id, port);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_preview_urls_hostname ON sandbox_preview_urls(hostname);
diff --git a/internal/db/store.go b/internal/db/store.go
index 66043a84..4c7f70e1 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -70,6 +70,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{4, "migrations/004_seed_templates.up.sql"},
{5, "migrations/005_org_custom_domain.up.sql"},
{6, "migrations/006_sandbox_preview_urls.up.sql"},
+ {7, "migrations/007_preview_urls_port.up.sql"},
}
for _, m := range migrations {
@@ -816,78 +817,87 @@ type PreviewURL struct {
SandboxID string `json:"sandboxId"`
OrgID uuid.UUID `json:"orgId"`
Hostname string `json:"hostname"`
+ Port int `json:"port"`
CFHostnameID *string `json:"cfHostnameId,omitempty"`
SSLStatus string `json:"sslStatus"`
AuthConfig json.RawMessage `json:"authConfig"`
CreatedAt time.Time `json:"createdAt"`
}
-// CreatePreviewURL inserts a new preview URL record.
-func (s *Store) CreatePreviewURL(ctx context.Context, sandboxID string, orgID uuid.UUID, hostname string, cfHostnameID *string, sslStatus string, authConfig json.RawMessage) (*PreviewURL, error) {
+// CreatePreviewURL inserts a new preview URL record for a specific port.
+func (s *Store) CreatePreviewURL(ctx context.Context, sandboxID string, orgID uuid.UUID, hostname string, port int, cfHostnameID *string, sslStatus string, authConfig json.RawMessage) (*PreviewURL, error) {
p := &PreviewURL{}
err := s.pool.QueryRow(ctx,
- `INSERT INTO sandbox_preview_urls (sandbox_id, org_id, hostname, cf_hostname_id, ssl_status, auth_config)
- VALUES ($1, $2, $3, $4, $5, $6)
- RETURNING id, sandbox_id, org_id, hostname, cf_hostname_id, ssl_status, auth_config, created_at`,
- sandboxID, orgID, hostname, cfHostnameID, sslStatus, authConfig,
- ).Scan(&p.ID, &p.SandboxID, &p.OrgID, &p.Hostname, &p.CFHostnameID, &p.SSLStatus, &p.AuthConfig, &p.CreatedAt)
+ `INSERT INTO sandbox_preview_urls (sandbox_id, org_id, hostname, port, cf_hostname_id, ssl_status, auth_config)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ RETURNING id, sandbox_id, org_id, hostname, port, cf_hostname_id, ssl_status, auth_config, created_at`,
+ sandboxID, orgID, hostname, port, cfHostnameID, sslStatus, authConfig,
+ ).Scan(&p.ID, &p.SandboxID, &p.OrgID, &p.Hostname, &p.Port, &p.CFHostnameID, &p.SSLStatus, &p.AuthConfig, &p.CreatedAt)
if err != nil {
return nil, fmt.Errorf("failed to create preview URL: %w", err)
}
return p, nil
}
-// GetPreviewURL returns the preview URL for a sandbox (one per sandbox).
-func (s *Store) GetPreviewURL(ctx context.Context, sandboxID string) (*PreviewURL, error) {
+// ListPreviewURLs returns all preview URLs for a sandbox.
+func (s *Store) ListPreviewURLs(ctx context.Context, sandboxID string) ([]PreviewURL, error) {
+ rows, err := s.pool.Query(ctx,
+ `SELECT id, sandbox_id, org_id, hostname, port, cf_hostname_id, ssl_status, auth_config, created_at
+ FROM sandbox_preview_urls WHERE sandbox_id = $1 ORDER BY port`, sandboxID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to list preview URLs: %w", err)
+ }
+ defer rows.Close()
+
+ var urls []PreviewURL
+ for rows.Next() {
+ var p PreviewURL
+ if err := rows.Scan(&p.ID, &p.SandboxID, &p.OrgID, &p.Hostname, &p.Port, &p.CFHostnameID, &p.SSLStatus, &p.AuthConfig, &p.CreatedAt); err != nil {
+ return nil, fmt.Errorf("failed to scan preview URL: %w", err)
+ }
+ urls = append(urls, p)
+ }
+ return urls, nil
+}
+
+// GetPreviewURLByPort returns the preview URL for a sandbox on a specific port.
+func (s *Store) GetPreviewURLByPort(ctx context.Context, sandboxID string, port int) (*PreviewURL, error) {
p := &PreviewURL{}
err := s.pool.QueryRow(ctx,
- `SELECT id, sandbox_id, org_id, hostname, cf_hostname_id, ssl_status, auth_config, created_at
- FROM sandbox_preview_urls WHERE sandbox_id = $1 LIMIT 1`, sandboxID,
- ).Scan(&p.ID, &p.SandboxID, &p.OrgID, &p.Hostname, &p.CFHostnameID, &p.SSLStatus, &p.AuthConfig, &p.CreatedAt)
+ `SELECT id, sandbox_id, org_id, hostname, port, cf_hostname_id, ssl_status, auth_config, created_at
+ FROM sandbox_preview_urls WHERE sandbox_id = $1 AND port = $2`, sandboxID, port,
+ ).Scan(&p.ID, &p.SandboxID, &p.OrgID, &p.Hostname, &p.Port, &p.CFHostnameID, &p.SSLStatus, &p.AuthConfig, &p.CreatedAt)
if err != nil {
return nil, fmt.Errorf("preview URL not found: %w", err)
}
return p, nil
}
-// UpdatePreviewURLSSL updates the SSL status for a preview URL.
-func (s *Store) UpdatePreviewURLSSL(ctx context.Context, id uuid.UUID, sslStatus string) error {
- _, err := s.pool.Exec(ctx,
- `UPDATE sandbox_preview_urls SET ssl_status = $1 WHERE id = $2`,
- sslStatus, id)
- return err
-}
-
// DeletePreviewURL deletes a preview URL by ID.
func (s *Store) DeletePreviewURL(ctx context.Context, id uuid.UUID) error {
_, err := s.pool.Exec(ctx, `DELETE FROM sandbox_preview_urls WHERE id = $1`, id)
return err
}
-// GetPreviewURLByHostname looks up a preview URL by its hostname.
-// Used by the proxy middleware to route custom domain traffic to the correct sandbox.
-func (s *Store) GetPreviewURLByHostname(ctx context.Context, hostname string) (*PreviewURL, error) {
- p := &PreviewURL{}
- err := s.pool.QueryRow(ctx,
- `SELECT id, sandbox_id, org_id, hostname, cf_hostname_id, ssl_status, auth_config, created_at
- FROM sandbox_preview_urls WHERE hostname = $1 LIMIT 1`, hostname,
- ).Scan(&p.ID, &p.SandboxID, &p.OrgID, &p.Hostname, &p.CFHostnameID, &p.SSLStatus, &p.AuthConfig, &p.CreatedAt)
+// DeletePreviewURLsBySandbox deletes all preview URLs for a sandbox (cleanup on kill).
+// Returns the deleted records so callers can clean up CF hostnames.
+func (s *Store) DeletePreviewURLsBySandbox(ctx context.Context, sandboxID string) ([]PreviewURL, error) {
+ rows, err := s.pool.Query(ctx,
+ `DELETE FROM sandbox_preview_urls WHERE sandbox_id = $1
+ RETURNING id, sandbox_id, org_id, hostname, port, cf_hostname_id, ssl_status, auth_config, created_at`,
+ sandboxID)
if err != nil {
- return nil, fmt.Errorf("preview URL not found for hostname: %w", err)
+ return nil, err
}
- return p, nil
-}
+ defer rows.Close()
-// DeletePreviewURLBySandbox deletes the preview URL for a sandbox (cleanup on kill).
-func (s *Store) DeletePreviewURLBySandbox(ctx context.Context, sandboxID string) (*PreviewURL, error) {
- p := &PreviewURL{}
- err := s.pool.QueryRow(ctx,
- `DELETE FROM sandbox_preview_urls WHERE sandbox_id = $1
- RETURNING id, sandbox_id, org_id, hostname, cf_hostname_id, ssl_status, auth_config, created_at`,
- sandboxID,
- ).Scan(&p.ID, &p.SandboxID, &p.OrgID, &p.Hostname, &p.CFHostnameID, &p.SSLStatus, &p.AuthConfig, &p.CreatedAt)
- if err != nil {
- return nil, err // no preview URL is fine
+ var urls []PreviewURL
+ for rows.Next() {
+ var p PreviewURL
+ if err := rows.Scan(&p.ID, &p.SandboxID, &p.OrgID, &p.Hostname, &p.Port, &p.CFHostnameID, &p.SSLStatus, &p.AuthConfig, &p.CreatedAt); err != nil {
+ return nil, err
+ }
+ urls = append(urls, p)
}
- return p, nil
+ return urls, nil
}
diff --git a/internal/firecracker/manager.go b/internal/firecracker/manager.go
index 98bdb17b..120ffb03 100644
--- a/internal/firecracker/manager.go
+++ b/internal/firecracker/manager.go
@@ -749,6 +749,19 @@ func (m *Manager) HostPort(ctx context.Context, sandboxID string) (int, error) {
return vm.HostPort, nil
}
+// ContainerAddr returns the VM's guest IP and the requested port as "ip:port".
+// Used by the proxy to route preview URL traffic to a specific port inside the VM.
+func (m *Manager) ContainerAddr(ctx context.Context, sandboxID string, port int) (string, error) {
+ vm, err := m.getVM(sandboxID)
+ if err != nil {
+ return "", err
+ }
+ if vm.network == nil {
+ return "", fmt.Errorf("sandbox %s has no network config", sandboxID)
+ }
+ return fmt.Sprintf("%s:%d", vm.network.GuestIP, port), nil
+}
+
// DataDir returns the base data directory.
func (m *Manager) DataDir() string {
return m.cfg.DataDir
diff --git a/internal/podman/container.go b/internal/podman/container.go
index 337822f3..bb90f413 100644
--- a/internal/podman/container.go
+++ b/internal/podman/container.go
@@ -200,6 +200,11 @@ type ContainerInfo struct {
Labels map[string]string `json:"Labels"`
Image string `json:"Image"`
} `json:"Config"`
+ NetworkSettings struct {
+ Networks map[string]struct {
+ IPAddress string `json:"IPAddress"`
+ } `json:"Networks"`
+ } `json:"NetworkSettings"`
}
// InspectContainer returns detailed info about a container.
diff --git a/internal/proxy/controlplane_proxy.go b/internal/proxy/controlplane_proxy.go
index 69117850..07436ecd 100644
--- a/internal/proxy/controlplane_proxy.go
+++ b/internal/proxy/controlplane_proxy.go
@@ -50,51 +50,22 @@ func (p *ControlPlaneProxy) Middleware() echo.MiddlewareFunc {
hostOnly = host[:idx]
}
- sandboxID, ok := p.extractSandboxID(hostOnly)
+ // Parse preview hostname: {sandboxID}-p{port}.{domain}
+ sandboxID, port, ok := parsePreviewHostname(hostOnly)
if !ok {
- // Fallback: check if this hostname is a registered preview URL
- sandboxID, ok = p.extractSandboxIDFromPreviewURL(c.Request().Context(), hostOnly)
- if !ok {
- return next(c)
- }
+ return next(c)
}
- return p.doProxy(c, sandboxID)
+ return p.doProxy(c, sandboxID, port)
}
}
}
-// extractSandboxID parses "{sandboxID}.{baseDomain}" from the host.
-func (p *ControlPlaneProxy) extractSandboxID(host string) (string, bool) {
- suffix := "." + p.baseDomain
- if !strings.HasSuffix(host, suffix) {
- return "", false
- }
- sandboxID := strings.TrimSuffix(host, suffix)
- if sandboxID == "" || strings.Contains(sandboxID, ".") {
- return "", false
- }
- return sandboxID, true
-}
-
-// extractSandboxIDFromPreviewURL checks if the hostname matches a registered
-// preview URL in the database. This handles custom domain preview hostnames
-// like "sb-xxx.x.opensandbox.ai" that don't match the base domain pattern.
-func (p *ControlPlaneProxy) extractSandboxIDFromPreviewURL(ctx context.Context, host string) (string, bool) {
- if p.store == nil {
- return "", false
- }
- previewURL, err := p.store.GetPreviewURLByHostname(ctx, host)
- if err != nil || previewURL == nil {
- return "", false
- }
- return previewURL.SandboxID, true
-}
-
// doProxy looks up the worker that owns this sandbox and reverse-proxies to it.
// If the sandbox is hibernated, it triggers a wake-on-request: picks the least
// loaded worker, wakes the sandbox via gRPC, updates the DB, then proxies.
-func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string) error {
+// The port is encoded in the preview hostname and passed through to the worker.
+func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string, port int) error {
ctx := c.Request().Context()
// Look up which worker owns this sandbox
@@ -110,17 +81,15 @@ func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string) error {
worker, workerURL, err := p.wakeHibernatedSandbox(ctx, sandboxID)
if err != nil {
log.Printf("cp-proxy: wake-on-request failed for sandbox %s: %v", sandboxID, err)
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": fmt.Sprintf("sandbox %s: wake failed: %v", sandboxID, err),
- })
+ return serveUpstreamUnavailable(c, sandboxID, port)
}
log.Printf("cp-proxy: wake-on-request succeeded for sandbox %s → worker %s (%s)", sandboxID, worker.ID, workerURL)
if isWebSocketUpgrade(c.Request()) {
- return p.doWebSocket(c, sandboxID, workerURL)
+ return p.doWebSocket(c, sandboxID, workerURL, port)
}
- return p.doHTTP(c, sandboxID, workerURL)
+ return p.doHTTP(c, sandboxID, workerURL, port)
}
// If the sandbox is stopped/error, return a clear message
@@ -136,24 +105,22 @@ func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string) error {
worker := p.registry.GetWorker(session.WorkerID)
if worker == nil {
log.Printf("cp-proxy: sandbox %s session says running on worker %s, but worker not in registry", sandboxID, session.WorkerID)
- return p.tryRecoverOrFail(c, ctx, sandboxID, session)
+ return p.tryRecoverOrFail(c, ctx, sandboxID, session, port)
}
workerURL := worker.HTTPAddr
if workerURL == "" {
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": "worker has no HTTP address",
- })
+ return serveUpstreamUnavailable(c, sandboxID, port)
}
- log.Printf("cp-proxy: routing sandbox %s (worker %s) → %s", sandboxID, session.WorkerID, workerURL)
+ log.Printf("cp-proxy: routing sandbox %s port %d (worker %s) → %s", sandboxID, port, session.WorkerID, workerURL)
// WebSocket requests need raw TCP hijacking
if isWebSocketUpgrade(c.Request()) {
- return p.doWebSocket(c, sandboxID, workerURL)
+ return p.doWebSocket(c, sandboxID, workerURL, port)
}
- return p.doHTTP(c, sandboxID, workerURL)
+ return p.doHTTP(c, sandboxID, workerURL, port)
}
// tryRecoverOrFail handles the case where a sandbox session says "running" but
@@ -161,7 +128,7 @@ func (p *ControlPlaneProxy) doProxy(c echo.Context, sandboxID string) error {
// from (sandbox may have been hibernated but session not updated). If a checkpoint
// exists, it wakes the sandbox on a new worker. Otherwise, it marks the session
// as stopped and returns a clear error.
-func (p *ControlPlaneProxy) tryRecoverOrFail(c echo.Context, ctx context.Context, sandboxID string, session *db.SandboxSession) error {
+func (p *ControlPlaneProxy) tryRecoverOrFail(c echo.Context, ctx context.Context, sandboxID string, session *db.SandboxSession, port int) error {
// Check if there's a checkpoint we can wake from
checkpoint, err := p.store.GetActiveCheckpoint(ctx, sandboxID)
if err == nil && checkpoint != nil {
@@ -169,17 +136,15 @@ func (p *ControlPlaneProxy) tryRecoverOrFail(c echo.Context, ctx context.Context
worker, workerURL, err := p.wakeHibernatedSandbox(ctx, sandboxID)
if err != nil {
log.Printf("cp-proxy: recovery wake failed for sandbox %s: %v", sandboxID, err)
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": fmt.Sprintf("sandbox %s: recovery wake failed: %v", sandboxID, err),
- })
+ return serveUpstreamUnavailable(c, sandboxID, port)
}
log.Printf("cp-proxy: recovery wake succeeded for sandbox %s → worker %s (%s)", sandboxID, worker.ID, workerURL)
if isWebSocketUpgrade(c.Request()) {
- return p.doWebSocket(c, sandboxID, workerURL)
+ return p.doWebSocket(c, sandboxID, workerURL, port)
}
- return p.doHTTP(c, sandboxID, workerURL)
+ return p.doHTTP(c, sandboxID, workerURL, port)
}
// No checkpoint — sandbox is truly gone. Mark session as stopped.
@@ -239,7 +204,7 @@ func (p *ControlPlaneProxy) wakeHibernatedSandbox(ctx context.Context, sandboxID
// doHTTP reverse-proxies a normal HTTP request to the worker.
// If the worker returns a "not found" error for the sandbox (e.g., after worker restart),
// it marks the session as stopped so future requests get a clean 410.
-func (p *ControlPlaneProxy) doHTTP(c echo.Context, sandboxID, workerURL string) error {
+func (p *ControlPlaneProxy) doHTTP(c echo.Context, sandboxID, workerURL string, port int) error {
target, err := url.Parse(workerURL)
if err != nil {
return c.JSON(http.StatusBadGateway, map[string]string{
@@ -261,14 +226,13 @@ func (p *ControlPlaneProxy) doHTTP(c echo.Context, sandboxID, workerURL string)
proxyErr = err
}
- // The worker's proxy middleware matches on the Host header using baseDomain.
- // Rewrite the Host to {sandboxID}.{baseDomain} so the worker can always match,
- // even when the original request came via a custom domain preview URL.
- workerHost := sandboxID + "." + p.baseDomain
+ // Pass the hostname through as-is — the worker's proxy parses
+ // {sandboxID}-p{port} from the first subdomain label directly.
+ originalHost := c.Request().Host
proxy.Director = func(r *http.Request) {
r.URL.Scheme = target.Scheme
r.URL.Host = target.Host
- r.Host = workerHost
+ r.Host = originalHost
}
rec := &responseRecorder{
@@ -278,9 +242,7 @@ func (p *ControlPlaneProxy) doHTTP(c echo.Context, sandboxID, workerURL string)
if proxyErr != nil {
log.Printf("cp-proxy: error proxying sandbox %s to %s: %v", sandboxID, workerURL, proxyErr)
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": fmt.Sprintf("sandbox %s: worker unavailable", sandboxID),
- })
+ return serveUpstreamUnavailable(c, sandboxID, port)
}
// If the worker returned a 502 with "not found", the sandbox was lost
@@ -303,7 +265,7 @@ func (p *ControlPlaneProxy) doHTTP(c echo.Context, sandboxID, workerURL string)
}
// doWebSocket hijacks the connection and pipes it to the worker.
-func (p *ControlPlaneProxy) doWebSocket(c echo.Context, sandboxID, workerURL string) error {
+func (p *ControlPlaneProxy) doWebSocket(c echo.Context, sandboxID, workerURL string, port int) error {
target, err := url.Parse(workerURL)
if err != nil {
return c.JSON(http.StatusBadGateway, map[string]string{"error": "invalid worker URL"})
@@ -322,9 +284,7 @@ func (p *ControlPlaneProxy) doWebSocket(c echo.Context, sandboxID, workerURL str
upstream, err := net.DialTimeout("tcp", workerAddr, 5*time.Second)
if err != nil {
log.Printf("cp-proxy: websocket dial failed for sandbox %s (%s): %v", sandboxID, workerAddr, err)
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": fmt.Sprintf("sandbox %s: worker unavailable", sandboxID),
- })
+ return serveUpstreamUnavailable(c, sandboxID, port)
}
defer upstream.Close()
@@ -343,8 +303,7 @@ func (p *ControlPlaneProxy) doWebSocket(c echo.Context, sandboxID, workerURL str
}
defer clientConn.Close()
- // Rewrite Host to {sandboxID}.{baseDomain} so the worker's proxy can match
- c.Request().Host = sandboxID + "." + p.baseDomain
+ // Pass original Host through — worker's proxy parses preview hostname directly
if err := c.Request().Write(upstream); err != nil {
log.Printf("cp-proxy: websocket write request failed for sandbox %s: %v", sandboxID, err)
return nil
diff --git a/internal/proxy/placeholder.go b/internal/proxy/placeholder.go
new file mode 100644
index 00000000..ed1039f7
--- /dev/null
+++ b/internal/proxy/placeholder.go
@@ -0,0 +1,106 @@
+package proxy
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+
+ "github.com/labstack/echo/v4"
+)
+
+// placeholderHTML is the friendly waiting page shown to browsers when the
+// upstream port inside the sandbox isn't reachable yet. It auto-refreshes
+// every 3 seconds so the user sees the real page as soon as it comes up.
+const placeholderHTML = `<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta http-equiv="refresh" content="3">
+ <title>Waiting for port %d…</title>
+ <style>
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ body {
+ min-height: 100vh;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ background: #0a0a0a;
+ color: #e5e5e5;
+ }
+ .container {
+ text-align: center;
+ max-width: 480px;
+ padding: 2rem;
+ }
+ .spinner {
+ width: 40px;
+ height: 40px;
+ margin: 0 auto 1.5rem;
+ border: 3px solid #333;
+ border-top-color: #3b82f6;
+ border-radius: 50%%;
+ animation: spin 0.8s linear infinite;
+ }
+ @keyframes spin { to { transform: rotate(360deg); } }
+ h1 {
+ font-size: 1.25rem;
+ font-weight: 600;
+ margin-bottom: 0.75rem;
+ color: #f5f5f5;
+ }
+ p {
+ font-size: 0.875rem;
+ color: #a3a3a3;
+ line-height: 1.6;
+ }
+ .port {
+ display: inline-block;
+ background: #1e1e1e;
+ border: 1px solid #333;
+ border-radius: 4px;
+ padding: 0.1rem 0.4rem;
+ font-family: "SF Mono", SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;
+ font-size: 0.8rem;
+ color: #3b82f6;
+ }
+ .sandbox-id {
+ margin-top: 1.5rem;
+ font-size: 0.75rem;
+ color: #525252;
+ font-family: "SF Mono", SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;
+ }
+ </style>
+</head>
+<body>
+ <div class="container">
+ <div class="spinner"></div>
+ <h1>Waiting for your app…</h1>
+ <p>
+ Nothing is listening on port <span class="port">%d</span> yet.<br>
+ This page will auto-refresh until the port is ready.
+ </p>
+ <div class="sandbox-id">%s</div>
+ </div>
+</body>
+</html>`
+
+// wantsBrowserResponse checks if the request Accept header indicates a browser
+// (i.e. prefers text/html over JSON).
+func wantsBrowserResponse(r *http.Request) bool {
+ accept := r.Header.Get("Accept")
+ return strings.Contains(accept, "text/html")
+}
+
+// serveUpstreamUnavailable returns either a friendly HTML placeholder page
+// (for browsers) or a JSON error (for API clients / curl).
+func serveUpstreamUnavailable(c echo.Context, sandboxID string, port int) error {
+ if wantsBrowserResponse(c.Request()) {
+ html := fmt.Sprintf(placeholderHTML, port, port, sandboxID)
+ return c.HTML(http.StatusBadGateway, html)
+ }
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": fmt.Sprintf("sandbox %s: upstream unavailable", sandboxID),
+ })
+}
diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.go
index 0c782aa3..9fe749e7 100644
--- a/internal/proxy/proxy.go
+++ b/internal/proxy/proxy.go
@@ -3,19 +3,18 @@ package proxy
import (
"bytes"
"context"
- "fmt"
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
+ "strconv"
"strings"
"sync"
"time"
"github.com/labstack/echo/v4"
- "github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/sandbox"
)
@@ -25,7 +24,6 @@ type SandboxProxy struct {
baseDomain string
manager sandbox.Manager
router *sandbox.SandboxRouter
- store *db.Store // optional — for preview URL hostname lookup
}
// New creates a new SandboxProxy.
@@ -38,9 +36,30 @@ func New(baseDomain string, mgr sandbox.Manager, router *sandbox.SandboxRouter)
}
}
-// SetStore sets the database store for preview URL hostname lookups.
-func (p *SandboxProxy) SetStore(store *db.Store) {
- p.store = store
+// parsePreviewHostname extracts sandbox ID and port from a preview hostname.
+// Format: "{sandboxID}-p{port}.{anyDomain}" — the first subdomain label encodes both.
+// Returns ("", 0, false) if the hostname doesn't match the preview pattern.
+func parsePreviewHostname(host string) (sandboxID string, port int, ok bool) {
+ // Get the first subdomain label (before the first dot)
+ dot := strings.Index(host, ".")
+ if dot < 0 {
+ return "", 0, false
+ }
+ label := host[:dot]
+
+ // Find last "-p" to split sandboxID and port
+ idx := strings.LastIndex(label, "-p")
+ if idx < 0 {
+ return "", 0, false
+ }
+
+ sandboxID = label[:idx]
+ portStr := label[idx+2:]
+ p, err := strconv.Atoi(portStr)
+ if err != nil || p < 1 || p > 65535 || sandboxID == "" {
+ return "", 0, false
+ }
+ return sandboxID, p, true
}
// Middleware returns an Echo middleware that intercepts subdomain requests
@@ -56,106 +75,67 @@ func (p *SandboxProxy) Middleware() echo.MiddlewareFunc {
hostOnly = host[:idx]
}
- sandboxID, ok := p.extractSandboxID(hostOnly)
+ // Parse preview hostname: {sandboxID}-p{port}.{domain}
+ sandboxID, port, ok := parsePreviewHostname(hostOnly)
if !ok {
- // Fallback: check if this hostname is a registered preview URL
- sandboxID, ok = p.extractSandboxIDFromPreviewURL(c.Request().Context(), hostOnly)
- if !ok {
- return next(c)
- }
+ return next(c)
}
- return p.doProxy(c, sandboxID)
+ return p.doProxy(c, sandboxID, port)
}
}
}
-// extractSandboxID parses "{sandboxID}.{baseDomain}" from the host.
-// For baseDomain "localhost", matches "{sandboxID}.localhost".
-// For baseDomain "workers.opensandbox.dev", matches "{sandboxID}.workers.opensandbox.dev".
-func (p *SandboxProxy) extractSandboxID(host string) (string, bool) {
- suffix := "." + p.baseDomain
- if !strings.HasSuffix(host, suffix) {
- return "", false
- }
- sandboxID := strings.TrimSuffix(host, suffix)
- if sandboxID == "" || strings.Contains(sandboxID, ".") {
- return "", false
- }
- return sandboxID, true
-}
-
-// extractSandboxIDFromPreviewURL checks if the hostname matches a registered
-// preview URL in the database.
-func (p *SandboxProxy) extractSandboxIDFromPreviewURL(ctx context.Context, host string) (string, bool) {
- if p.store == nil {
- return "", false
- }
- previewURL, err := p.store.GetPreviewURLByHostname(ctx, host)
- if err != nil || previewURL == nil {
- return "", false
- }
- return previewURL.SandboxID, true
-}
-
// isWebSocketUpgrade returns true if the request is a WebSocket upgrade.
func isWebSocketUpgrade(r *http.Request) bool {
return strings.EqualFold(r.Header.Get("Upgrade"), "websocket") &&
strings.Contains(strings.ToLower(r.Header.Get("Connection")), "upgrade")
}
-// doProxy looks up the sandbox's host port and reverse-proxies the request.
-// If the sandbox is hibernated, it auto-wakes via the router first.
+// doProxy looks up the sandbox's container address for the given port and reverse-proxies
+// the request. If the sandbox is hibernated, it auto-wakes via the router first.
// WebSocket upgrade requests are handled via raw TCP hijacking.
// Normal HTTP requests use a buffered reverse proxy with retry logic
// for transient connection errors after CRIU restore.
-func (p *SandboxProxy) doProxy(c echo.Context, sandboxID string) error {
+func (p *SandboxProxy) doProxy(c echo.Context, sandboxID string, port int) error {
ctx := c.Request().Context()
// Route through the sandbox router for auto-wake and rolling timeout reset
- var hostPort int
- var portErr error
+ var addr string
+ var addrErr error
routeOp := func(ctx context.Context) error {
- hostPort, portErr = p.manager.HostPort(ctx, sandboxID)
- return portErr
+ addr, addrErr = p.manager.ContainerAddr(ctx, sandboxID, port)
+ return addrErr
}
if p.router != nil {
if err := p.router.Route(ctx, sandboxID, "proxy", routeOp); err != nil {
log.Printf("proxy: route failed for sandbox %s: %v", sandboxID, err)
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": fmt.Sprintf("sandbox %s not available: %v", sandboxID, err),
- })
+ return serveUpstreamUnavailable(c, sandboxID, port)
}
} else {
if err := routeOp(ctx); err != nil {
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": fmt.Sprintf("sandbox %s not available: %v", sandboxID, err),
- })
+ return serveUpstreamUnavailable(c, sandboxID, port)
}
}
- addr := fmt.Sprintf("127.0.0.1:%d", hostPort)
-
// WebSocket requests need raw TCP hijacking — can't buffer these.
if isWebSocketUpgrade(c.Request()) {
- return p.doWebSocket(c, sandboxID, addr)
+ return p.doWebSocket(c, sandboxID, addr, port)
}
- return p.doHTTP(c, sandboxID, addr, hostPort)
+ return p.doHTTP(c, sandboxID, addr, port)
}
// doWebSocket hijacks the client connection and pipes it to the upstream
// container over raw TCP, enabling WebSocket (and any other Upgrade) traffic.
-func (p *SandboxProxy) doWebSocket(c echo.Context, sandboxID, addr string) error {
+func (p *SandboxProxy) doWebSocket(c echo.Context, sandboxID, addr string, port int) error {
// Dial the upstream container
upstream, err := net.DialTimeout("tcp", addr, 5*time.Second)
if err != nil {
log.Printf("proxy: websocket dial failed for sandbox %s (%s): %v", sandboxID, addr, err)
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": fmt.Sprintf("sandbox %s: upstream unavailable", sandboxID),
- })
+ return serveUpstreamUnavailable(c, sandboxID, port)
}
defer upstream.Close()
@@ -288,9 +268,7 @@ func (p *SandboxProxy) doHTTP(c echo.Context, sandboxID, addr string, hostPort i
}
log.Printf("proxy: error proxying to sandbox %s (port %d) after %d attempts: %v",
sandboxID, hostPort, attempt+1, proxyErr)
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": fmt.Sprintf("sandbox %s: upstream unavailable", sandboxID),
- })
+ return serveUpstreamUnavailable(c, sandboxID, hostPort)
}
// Success — flush the recorded response to the real client.
@@ -299,9 +277,7 @@ func (p *SandboxProxy) doHTTP(c echo.Context, sandboxID, addr string, hostPort i
}
// Should not reach here, but just in case.
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": fmt.Sprintf("sandbox %s: upstream unavailable after retries", sandboxID),
- })
+ return serveUpstreamUnavailable(c, sandboxID, hostPort)
}
// responseRecorder captures an HTTP response in memory so we can decide
diff --git a/internal/sandbox/interface.go b/internal/sandbox/interface.go
index bc1ef491..a42fb45a 100644
--- a/internal/sandbox/interface.go
+++ b/internal/sandbox/interface.go
@@ -46,6 +46,7 @@ type Manager interface {
// Monitoring
Stats(ctx context.Context, sandboxID string) (*SandboxStats, error)
HostPort(ctx context.Context, sandboxID string) (int, error)
+ ContainerAddr(ctx context.Context, sandboxID string, port int) (string, error)
DataDir() string
// Sandbox name (for logging/cleanup)
diff --git a/internal/sandbox/manager.go b/internal/sandbox/manager.go
index 3787bd0d..ae90de0f 100644
--- a/internal/sandbox/manager.go
+++ b/internal/sandbox/manager.go
@@ -253,6 +253,23 @@ func (m *PodmanManager) HostPort(ctx context.Context, sandboxID string) (int, er
return port, nil
}
+// ContainerAddr returns the container's bridge IP and the requested port as "ip:port".
+// Used by the proxy to route preview URL traffic directly to a specific container port.
+func (m *PodmanManager) ContainerAddr(ctx context.Context, sandboxID string, port int) (string, error) {
+ name := m.ContainerName(sandboxID)
+ info, err := m.podman.InspectContainer(ctx, name)
+ if err != nil {
+ return "", fmt.Errorf("sandbox %s not found: %w", sandboxID, err)
+ }
+ // Find bridge IP from network settings
+ for _, net := range info.NetworkSettings.Networks {
+ if net.IPAddress != "" {
+ return fmt.Sprintf("%s:%d", net.IPAddress, port), nil
+ }
+ }
+ return "", fmt.Errorf("sandbox %s has no network IP", sandboxID)
+}
+
// Stats returns live CPU/memory stats for a running sandbox.
func (m *PodmanManager) Stats(ctx context.Context, sandboxID string) (*SandboxStats, error) {
name := m.ContainerName(sandboxID)
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index 675d4d2c..bb66b32d 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -27,7 +27,6 @@ type Sandbox struct {
MachineID string `json:"machineID,omitempty"`
ConnectURL string `json:"connectURL,omitempty"` // Direct worker URL for SDK access
Token string `json:"token,omitempty"` // Sandbox-scoped JWT for worker auth
- Domain string `json:"domain,omitempty"` // Subdomain for web access (e.g., "abc123.workers.opensandbox.dev")
HostPort int `json:"hostPort,omitempty"` // Mapped host port for the sandbox's container port
}
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 04459ab1..7cae976b 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -20,7 +20,6 @@ class Sandbox:
sandbox_id: str
status: str = "running"
template: str = ""
- domain: str = ""
_api_url: str = ""
_api_key: str = ""
_connect_url: str = ""
@@ -81,7 +80,6 @@ class Sandbox:
sandbox_id=data["sandboxID"],
status=data.get("status", "running"),
template=template,
- domain=data.get("domain", ""),
_api_url=url,
_api_key=key,
_connect_url=connect_url,
@@ -129,7 +127,6 @@ class Sandbox:
sandbox_id=sandbox_id,
status=data.get("status", "running"),
template=data.get("templateID", ""),
- domain=data.get("domain", ""),
_api_url=url,
_api_key=key,
_connect_url=connect_url,
@@ -187,26 +184,24 @@ 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, auth_config: dict | None = None) -> dict:
- """Create an on-demand preview URL using the org's verified custom domain."""
+ async def create_preview_url(self, port: int, auth_config: dict | None = None) -> dict:
+ """Create a preview URL targeting a specific container port."""
resp = await self._client.post(
f"/sandboxes/{self.sandbox_id}/preview",
- json={"authConfig": auth_config or {}},
+ json={"port": port, "authConfig": auth_config or {}},
)
resp.raise_for_status()
return resp.json()
- async def get_preview_url(self) -> dict | None:
- """Get the preview URL for this sandbox, or None if not set."""
+ async def list_preview_urls(self) -> list[dict]:
+ """List all preview URLs for this sandbox."""
resp = await self._client.get(f"/sandboxes/{self.sandbox_id}/preview")
- if resp.status_code == 404:
- return None
resp.raise_for_status()
return resp.json()
- async def delete_preview_url(self) -> None:
- """Delete the preview URL for this sandbox."""
- resp = await self._client.delete(f"/sandboxes/{self.sandbox_id}/preview")
+ async def delete_preview_url(self, port: int) -> None:
+ """Delete the preview URL for a specific port."""
+ resp = await self._client.delete(f"/sandboxes/{self.sandbox_id}/preview/{port}")
if resp.status_code != 404:
resp.raise_for_status()
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 1e3b46c5..c480a192 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -24,7 +24,6 @@ interface SandboxData {
templateID?: string;
connectURL?: string;
token?: string;
- domain?: string;
}
export interface PreviewURLResult {
@@ -32,6 +31,7 @@ export interface PreviewURLResult {
sandboxId: string;
orgId: string;
hostname: string;
+ port: number;
cfHostnameId?: string;
sslStatus: string;
authConfig: Record<string, unknown>;
@@ -40,7 +40,6 @@ export interface PreviewURLResult {
export class Sandbox {
readonly sandboxId: string;
- readonly domain: string;
readonly files: Filesystem;
readonly commands: Commands;
readonly pty: Pty;
@@ -53,7 +52,6 @@ export class Sandbox {
private constructor(data: SandboxData, apiUrl: string, apiKey: string) {
this.sandboxId = data.sandboxID;
- this.domain = data.domain || "";
this._status = data.status;
this.apiUrl = apiUrl;
this.apiKey = apiKey;
@@ -208,14 +206,14 @@ export class Sandbox {
}
}
- async createPreviewURL(opts?: { authConfig?: Record<string, unknown> }): Promise<PreviewURLResult> {
+ async createPreviewURL(opts: { port: number; 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({ authConfig: opts?.authConfig ?? {} }),
+ body: JSON.stringify({ port: opts.port, authConfig: opts.authConfig ?? {} }),
});
if (!resp.ok) {
@@ -226,21 +224,20 @@ export class Sandbox {
return resp.json();
}
- async getPreviewURL(): Promise<PreviewURLResult | null> {
+ async listPreviewURLs(): Promise<PreviewURLResult[]> {
const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview`, {
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
- if (resp.status === 404) return null;
if (!resp.ok) {
- throw new Error(`Failed to get preview URL: ${resp.status}`);
+ throw new Error(`Failed to list preview URLs: ${resp.status}`);
}
return resp.json();
}
- async deletePreviewURL(): Promise<void> {
- const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview`, {
+ async deletePreviewURL(port: number): Promise<void> {
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview/${port}`, {
method: "DELETE",
headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
});
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index dcca35d0..feb7a39f 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -123,6 +123,7 @@ export interface PreviewURL {
sandboxId: string
orgId: string
hostname: string
+ port: number
cfHostnameId?: string
sslStatus: string
authConfig: Record<string, unknown>
@@ -137,7 +138,6 @@ export interface SessionDetail {
startedAt: string
stoppedAt?: string
errorMsg?: string
- domain?: string
config?: {
timeout?: number
cpuCount?: number
@@ -150,7 +150,7 @@ export interface SessionDetail {
sizeBytes: number
hibernatedAt: string
}
- previewUrl?: PreviewURL
+ previewUrls?: PreviewURL[]
}
export interface SandboxStats {
diff --git a/web/src/pages/SessionDetail.tsx b/web/src/pages/SessionDetail.tsx
index 122ee9fb..edb57838 100644
--- a/web/src/pages/SessionDetail.tsx
+++ b/web/src/pages/SessionDetail.tsx
@@ -59,7 +59,7 @@ function StatCard({ label, value, sub }: { label: string; value: string; sub?: s
export default function SessionDetail() {
const { sandboxId } = useParams<{ sandboxId: string }>()
const navigate = useNavigate()
- const [copied, setCopied] = useState(false)
+ const [copiedPort, setCopiedPort] = useState<number | null>(null)
const [showTerminal, setShowTerminal] = useState(false)
const { data: session, isLoading } = useQuery({
@@ -76,12 +76,10 @@ export default function SessionDetail() {
retry: false,
})
- const copyUrl = () => {
- if (session?.domain) {
- navigator.clipboard.writeText(`https://${session.domain}`)
- setCopied(true)
- setTimeout(() => setCopied(false), 2000)
- }
+ const copyUrl = (hostname: string, port: number) => {
+ navigator.clipboard.writeText(`https://${hostname}`)
+ setCopiedPort(port)
+ setTimeout(() => setCopiedPort(null), 2000)
}
if (isLoading) {
@@ -186,35 +184,48 @@ export default function SessionDetail() {
</div>
)}
- {/* Live URL */}
- {session.domain && (session.status === 'running' || session.status === 'hibernated') && (
+ {/* Preview URLs */}
+ {session.previewUrls && session.previewUrls.length > 0 && (
<div className="glass-card animate-in stagger-2" style={{ padding: 20, marginBottom: 16 }}>
<div style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-tertiary)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 10 }}>
- Live URL
+ Preview URLs
</div>
- <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
- <div style={{
- flex: 1,
- background: 'var(--bg-deep)',
- border: '1px solid var(--border-subtle)',
- borderRadius: 'var(--radius-sm)',
- padding: '10px 14px',
- fontFamily: 'var(--font-mono)',
- fontSize: 13,
- color: 'var(--text-accent)',
- }}>
- <a
- href={`https://${session.domain}`}
- target="_blank"
- rel="noopener noreferrer"
- style={{ color: 'var(--text-accent)', textDecoration: 'none' }}
- >
- https://{session.domain}
- </a>
- </div>
- <button className="btn-ghost" onClick={copyUrl} style={{ whiteSpace: 'nowrap' }}>
- {copied ? '✓ Copied' : 'Copy'}
- </button>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
+ {session.previewUrls.map((url) => (
+ <div key={url.id} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
+ <div style={{
+ minWidth: 60,
+ fontSize: 12,
+ fontWeight: 600,
+ color: 'var(--text-tertiary)',
+ fontFamily: 'var(--font-mono)',
+ }}>
+ :{url.port}
+ </div>
+ <div style={{
+ flex: 1,
+ background: 'var(--bg-deep)',
+ border: '1px solid var(--border-subtle)',
+ borderRadius: 'var(--radius-sm)',
+ padding: '10px 14px',
+ fontFamily: 'var(--font-mono)',
+ fontSize: 13,
+ color: 'var(--text-accent)',
+ }}>
+ <a
+ href={`https://${url.hostname}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ style={{ color: 'var(--text-accent)', textDecoration: 'none' }}
+ >
+ https://{url.hostname}
+ </a>
+ </div>
+ <button className="btn-ghost" onClick={() => copyUrl(url.hostname, url.port)} style={{ whiteSpace: 'nowrap' }}>
+ {copiedPort === url.port ? 'Copied' : 'Copy'}
+ </button>
+ </div>
+ ))}
</div>
</div>
)}