Skip to content

An open-source, faster Devin alternative

TypeScript

Add per-second pricing with Stripe metered billing + free tier (#89)

Mohamed Habib7deca6c6b10f
diff --git a/.gitignore b/.gitignore
index 5f3bb37a..0a4d5e9e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -59,3 +59,4 @@ deploy/ec2/*.pem
*.log
delme
deploy/azure/.dev-env-state-*
+/server
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 233ad318..17452a4c 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -14,6 +14,7 @@ import (
"github.com/opensandbox/opensandbox/internal/api"
"github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/billing"
"github.com/opensandbox/opensandbox/internal/cloudflare"
"github.com/opensandbox/opensandbox/internal/compute"
"github.com/opensandbox/opensandbox/internal/config"
@@ -273,9 +274,29 @@ func main() {
log.Println("opensandbox: Cloudflare custom hostnames configured")
}
+ // Initialize Stripe billing (if configured)
+ var stripeClient *billing.StripeClient
+ if cfg.StripeSecretKey != "" {
+ stripeClient = billing.NewStripeClient(cfg.StripeSecretKey, cfg.StripeWebhookSecret, cfg.StripeSuccessURL, cfg.StripeCancelURL)
+ if err := stripeClient.EnsureProducts(); err != nil {
+ log.Printf("opensandbox: Stripe product setup failed: %v (billing may not work)", err)
+ } else {
+ log.Println("opensandbox: Stripe billing configured")
+ }
+ opts.StripeClient = stripeClient
+ }
+
// Create API server
server := api.NewServer(mgr, ptyMgr, cfg.APIKey, opts)
+ // Start usage reporter (reports sandbox usage to Stripe every 5 min)
+ if opts.Store != nil && stripeClient != nil {
+ reporter := billing.NewUsageReporter(opts.Store, stripeClient)
+ reporter.Start()
+ defer reporter.Stop()
+ log.Println("opensandbox: usage reporter started (interval=5m)")
+ }
+
// Start NATS sync consumer if both PG and NATS are configured
if opts.Store != nil && cfg.NATSURL != "" {
consumer, err := db.NewSyncConsumer(opts.Store, cfg.NATSURL)
diff --git a/go.mod b/go.mod
index 72676092..cca2c070 100644
--- a/go.mod
+++ b/go.mod
@@ -72,6 +72,7 @@ require (
github.com/prometheus/common v0.55.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/spf13/pflag v1.0.9 // indirect
+ github.com/stripe/stripe-go/v82 v82.5.1 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
go.uber.org/atomic v1.11.0 // indirect
diff --git a/go.sum b/go.sum
index 30515526..af03c8b2 100644
--- a/go.sum
+++ b/go.sum
@@ -155,6 +155,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+github.com/stripe/stripe-go/v82 v82.5.1 h1:05q6ZDKoe8PLMpQV072obF74HCgP4XJeJYoNuRSX2+8=
+github.com/stripe/stripe-go/v82 v82.5.1/go.mod h1:majCQX6AfObAvJiHraPi/5udwHi4ojRvJnnxckvHrX8=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
diff --git a/internal/api/dashboard_billing.go b/internal/api/dashboard_billing.go
new file mode 100644
index 00000000..40df8bc2
--- /dev/null
+++ b/internal/api/dashboard_billing.go
@@ -0,0 +1,270 @@
+package api
+
+import (
+ "encoding/json"
+ "io"
+ "log"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/billing"
+)
+
+// billingSetup initiates the upgrade flow: creates Stripe customer + Checkout session.
+func (s *Server) billingSetup(c echo.Context) error {
+ if s.store == nil || s.stripeClient == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "billing not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})
+ }
+ ctx := c.Request().Context()
+ org, err := s.store.GetOrg(ctx, orgID)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "org not found"})
+ }
+
+ // Ensure Stripe customer exists
+ customerID := ""
+ if org.StripeCustomerID != nil {
+ customerID = *org.StripeCustomerID
+ }
+ if customerID == "" {
+ customerID, err = s.stripeClient.CreateCustomer(org.Name, "")
+ if err != nil {
+ log.Printf("billing: create customer failed for org %s: %v", orgID, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to create customer"})
+ }
+ if err := s.store.SetStripeCustomerID(ctx, orgID, customerID); err != nil {
+ log.Printf("billing: save customer ID failed for org %s: %v", orgID, err)
+ }
+ }
+
+ url, _, err := s.stripeClient.CreateSetupCheckoutSession(customerID, orgID.String())
+ if err != nil {
+ log.Printf("billing: create checkout session failed for org %s: %v", orgID, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to create checkout"})
+ }
+ return c.JSON(http.StatusOK, map[string]string{"url": url})
+}
+
+// billingGet returns the billing state for the current org.
+func (s *Server) billingGet(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})
+ }
+ ctx := c.Request().Context()
+ org, err := s.store.GetOrg(ctx, orgID)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "org not found"})
+ }
+
+ // Current month usage
+ now := time.Now()
+ monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
+ usage, _ := s.store.GetOrgUsage(ctx, orgID.String(), monthStart, now)
+
+ type tierUsage struct {
+ MemoryMB int `json:"memoryMB"`
+ VCPUs int `json:"vcpus"`
+ TotalSeconds float64 `json:"totalSeconds"`
+ CostCents float64 `json:"costCents"`
+ }
+ var tiers []tierUsage
+ var totalCost float64
+ for _, u := range usage {
+ rate := billing.TierPricePerSecond[u.MemoryMB]
+ cost := u.TotalSeconds * rate * 100
+ totalCost += cost
+ tiers = append(tiers, tierUsage{
+ MemoryMB: u.MemoryMB,
+ VCPUs: u.CPUPercent / 100,
+ TotalSeconds: u.TotalSeconds,
+ CostCents: cost,
+ })
+ }
+
+ // Stripe balance for pro users
+ var stripeCreditCents int64
+ if org.Plan == "pro" && org.StripeCustomerID != nil && s.stripeClient != nil {
+ bal, err := s.stripeClient.GetCustomerBalance(*org.StripeCustomerID)
+ if err == nil {
+ stripeCreditCents = -bal // negative balance = credit
+ }
+ }
+
+ return c.JSON(http.StatusOK, map[string]interface{}{
+ "plan": org.Plan,
+ "stripeCreditCents": stripeCreditCents,
+ "monthlySpendCapCents": org.MonthlySpendCapCents,
+ "hasPaymentMethod": org.StripeCustomerID != nil,
+ "currentUsage": map[string]interface{}{
+ "tiers": tiers,
+ "totalCostCents": totalCost,
+ },
+ })
+}
+
+// billingUpdateSettings updates the monthly spend cap.
+func (s *Server) billingUpdateSettings(c echo.Context) error {
+ if s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})
+ }
+ var req struct {
+ MonthlySpendCapCents *int `json:"monthlySpendCapCents"`
+ }
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request"})
+ }
+ if err := s.store.SetMonthlySpendCap(c.Request().Context(), orgID, req.MonthlySpendCapCents); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to update"})
+ }
+ return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
+}
+
+// billingInvoices returns past Stripe invoices.
+func (s *Server) billingInvoices(c echo.Context) error {
+ if s.store == nil || s.stripeClient == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})
+ }
+ orgID, ok := auth.GetOrgID(c)
+ if !ok {
+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})
+ }
+ org, err := s.store.GetOrg(c.Request().Context(), orgID)
+ if err != nil || org.StripeCustomerID == nil {
+ return c.JSON(http.StatusOK, map[string]interface{}{"invoices": []interface{}{}})
+ }
+
+ limit := 10
+ if l := c.QueryParam("limit"); l != "" {
+ if v, err := strconv.Atoi(l); err == nil && v > 0 && v <= 50 {
+ limit = v
+ }
+ }
+
+ invoices, err := s.stripeClient.ListInvoices(*org.StripeCustomerID, limit)
+ if err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to list invoices"})
+ }
+
+ type inv struct {
+ ID string `json:"id"`
+ Number string `json:"number"`
+ Status string `json:"status"`
+ AmountDue int64 `json:"amountDue"`
+ AmountPaid int64 `json:"amountPaid"`
+ Currency string `json:"currency"`
+ Created int64 `json:"created"`
+ HostedURL string `json:"hostedUrl"`
+ PDFURL string `json:"pdfUrl"`
+ }
+ var result []inv
+ for _, i := range invoices {
+ hostedURL := ""
+ pdfURL := ""
+ if i.HostedInvoiceURL != "" {
+ hostedURL = i.HostedInvoiceURL
+ }
+ if i.InvoicePDF != "" {
+ pdfURL = i.InvoicePDF
+ }
+ result = append(result, inv{
+ ID: i.ID,
+ Number: i.Number,
+ Status: string(i.Status),
+ AmountDue: i.AmountDue,
+ AmountPaid: i.AmountPaid,
+ Currency: string(i.Currency),
+ Created: i.Created,
+ HostedURL: hostedURL,
+ PDFURL: pdfURL,
+ })
+ }
+ return c.JSON(http.StatusOK, map[string]interface{}{"invoices": result})
+}
+
+// stripeWebhook handles Stripe webhook events.
+func (s *Server) stripeWebhook(c echo.Context) error {
+ if s.stripeClient == nil || s.store == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})
+ }
+ body, err := io.ReadAll(c.Request().Body)
+ if err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "read body failed"})
+ }
+ sig := c.Request().Header.Get("Stripe-Signature")
+ event, err := s.stripeClient.VerifyWebhookSignature(body, sig)
+ if err != nil {
+ log.Printf("billing: webhook sig failed: %v", err)
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid signature"})
+ }
+
+ ctx := c.Request().Context()
+
+ switch event.Type {
+ case "checkout.session.completed":
+ var sess struct {
+ ID string `json:"id"`
+ Mode string `json:"mode"`
+ Customer string `json:"customer"`
+ Metadata map[string]string `json:"metadata"`
+ }
+ if err := json.Unmarshal(event.Data.Raw, &sess); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "bad event data"})
+ }
+ if sess.Metadata["type"] == "setup" {
+ orgIDStr := sess.Metadata["org_id"]
+ orgID, err := uuid.Parse(orgIDStr)
+ if err != nil {
+ return c.JSON(http.StatusOK, map[string]string{"status": "ignored"})
+ }
+
+ // Create subscription with all metered prices
+ subID, itemIDs, err := s.stripeClient.CreateSubscription(sess.Customer)
+ if err != nil {
+ log.Printf("billing: create subscription failed for org %s: %v", orgID, err)
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "subscription failed"})
+ }
+ if err := s.store.SetStripeSubscriptionID(ctx, orgID, subID); err != nil {
+ log.Printf("billing: save subscription ID failed: %v", err)
+ }
+ if err := s.store.SaveSubscriptionItems(ctx, orgID, itemIDs); err != nil {
+ log.Printf("billing: save subscription items failed: %v", err)
+ }
+
+ // Apply $30 promotional credit
+ if err := s.stripeClient.ApplyPromotionalCredit(sess.Customer, 3000); err != nil {
+ log.Printf("billing: apply credit failed for org %s: %v", orgID, err)
+ }
+
+ // Upgrade plan
+ if err := s.store.UpdateOrgPlan(ctx, orgID, "pro"); err != nil {
+ log.Printf("billing: upgrade plan failed for org %s: %v", orgID, err)
+ }
+
+ log.Printf("billing: org %s upgraded to pro (subscription=%s, $30 credit applied)", orgID, subID)
+ }
+
+ case "invoice.paid":
+ log.Printf("billing: invoice paid: %s", string(event.Data.Raw)[:100])
+
+ case "invoice.payment_failed":
+ log.Printf("billing: invoice payment failed: %s", string(event.Data.Raw)[:100])
+ }
+
+ return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index e0b98b5b..219de025 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -13,6 +13,7 @@ import (
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/billing"
"github.com/opensandbox/opensandbox/internal/cloudflare"
"github.com/opensandbox/opensandbox/internal/controlplane"
"github.com/opensandbox/opensandbox/internal/db"
@@ -46,6 +47,7 @@ type Server struct {
cfClient *cloudflare.Client // nil if Cloudflare not configured
pendingCreates sync.Map // map[sandboxID]*pendingCreate — async sandbox creation tracking
sandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
+ stripeClient *billing.StripeClient // nil if Stripe not configured
}
// pendingCreate tracks an async sandbox creation.
@@ -73,6 +75,7 @@ type ServerOpts struct {
CheckpointStore *storage.CheckpointStore // nil if hibernation not configured
CFClient *cloudflare.Client // nil if Cloudflare not configured
SandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
+ StripeClient *billing.StripeClient // nil if Stripe not configured
}
// NewServer creates a new API server with all routes configured.
@@ -102,6 +105,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.sandboxDomain = opts.SandboxDomain
s.cfClient = opts.CFClient
s.sandboxAPIProxy = opts.SandboxAPIProxy
+ s.stripeClient = opts.StripeClient
// Wire up readiness waiting so the proxy blocks until async creates finish
if s.sandboxAPIProxy != nil {
@@ -318,6 +322,12 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
dash.POST("/org/switch", s.dashboardSwitchOrg)
dash.GET("/org/credits", s.dashboardGetCredits)
+ // Billing
+ dash.POST("/billing/setup", s.billingSetup)
+ dash.GET("/billing", s.billingGet)
+ dash.PUT("/billing/settings", s.billingUpdateSettings)
+ dash.GET("/billing/invoices", s.billingInvoices)
+
// Admin endpoints
dash.POST("/admin/backfill-workos-orgs", s.dashboardBackfillWorkOSOrgs)
@@ -331,6 +341,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
dash.DELETE("/sessions/:sandboxId/pty/:sessionId", s.dashboardKillPTY)
}
+ // Stripe webhook (public — verified by Stripe signature)
+ if s.stripeClient != nil {
+ e.POST("/webhooks/stripe", s.stripeWebhook)
+ }
+
// Auto-detect FrontendURL for dev: if web/dist doesn't exist, assume Vite dev on :3000
if frontendURL == "" && !dashboardDistExists() {
frontendURL = "http://localhost:3000"
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 2109d94d..ecb757eb 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -36,17 +36,32 @@ func (s *Server) createSandbox(c echo.Context) error {
ctx := c.Request().Context()
- // Check org quota if PG is available
+ // Check org quota and plan enforcement
orgID, hasOrg := auth.GetOrgID(c)
if hasOrg && s.store != nil {
org, err := s.store.GetOrg(ctx, orgID)
if err == nil {
+ // Concurrent sandbox limit
count, err := s.store.CountActiveSandboxes(ctx, orgID)
if err == nil && count >= org.MaxConcurrentSandboxes {
return c.JSON(http.StatusTooManyRequests, map[string]string{
"error": "concurrent sandbox limit reached",
})
}
+
+ // Free tier: 4GB / 1 vCPU only
+ if org.Plan == "free" {
+ if cfg.MemoryMB > 4096 || cfg.CpuCount > 1 {
+ return c.JSON(http.StatusPaymentRequired, map[string]string{
+ "error": "upgrade to pro for larger instances",
+ })
+ }
+ // Force 4GB/1vCPU if not specified
+ if cfg.MemoryMB == 0 {
+ cfg.MemoryMB = 4096
+ cfg.CpuCount = 1
+ }
+ }
}
}
diff --git a/internal/billing/pricing.go b/internal/billing/pricing.go
new file mode 100644
index 00000000..90c94c41
--- /dev/null
+++ b/internal/billing/pricing.go
@@ -0,0 +1,36 @@
+package billing
+
+import (
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// TierPricePerSecond maps memory_mb → USD per second.
+var TierPricePerSecond = map[int]float64{
+ 4096: 0.00003240740741, // 4GB / 1 vCPU
+ 8192: 0.000150462963, // 8GB / 2 vCPU
+ 16384: 0.0008101851852, // 16GB / 4 vCPU
+ 32768: 0.005787037037, // 32GB / 8 vCPU
+ 65536: 0.0162037037, // 64GB / 16 vCPU
+}
+
+// TierMetadataKey maps memory_mb → Stripe metadata key for price lookup.
+var TierMetadataKey = map[int]string{
+ 4096: "sandbox_4gb",
+ 8192: "sandbox_8gb",
+ 16384: "sandbox_16gb",
+ 32768: "sandbox_32gb",
+ 65536: "sandbox_64gb",
+}
+
+// CalculateUsageCostCents returns total cost in cents from usage summaries.
+func CalculateUsageCostCents(summaries []db.OrgUsageSummary) float64 {
+ var totalUSD float64
+ for _, s := range summaries {
+ rate, ok := TierPricePerSecond[s.MemoryMB]
+ if !ok {
+ continue
+ }
+ totalUSD += s.TotalSeconds * rate
+ }
+ return totalUSD * 100.0
+}
diff --git a/internal/billing/stripe.go b/internal/billing/stripe.go
new file mode 100644
index 00000000..dd98736b
--- /dev/null
+++ b/internal/billing/stripe.go
@@ -0,0 +1,303 @@
+package billing
+
+import (
+ "fmt"
+ "log"
+ "math"
+
+ "github.com/stripe/stripe-go/v82"
+ "github.com/stripe/stripe-go/v82/billing/meter"
+ "github.com/stripe/stripe-go/v82/billing/meterevent"
+ checkoutsession "github.com/stripe/stripe-go/v82/checkout/session"
+ "github.com/stripe/stripe-go/v82/customer"
+ "github.com/stripe/stripe-go/v82/invoice"
+ "github.com/stripe/stripe-go/v82/price"
+ "github.com/stripe/stripe-go/v82/product"
+ "github.com/stripe/stripe-go/v82/subscription"
+ "github.com/stripe/stripe-go/v82/webhook"
+)
+
+// StripeClient wraps the Stripe API for billing.
+type StripeClient struct {
+ webhookSecret string
+ successURL string
+ cancelURL string
+
+ // Populated by EnsureProducts — maps memoryMB → Stripe price ID
+ PriceIDs map[int]string
+ // Maps memoryMB → meter event_name (e.g. "sandbox_compute_4gb")
+ MeterEventNames map[int]string
+}
+
+// NewStripeClient creates a new Stripe client.
+func NewStripeClient(secretKey, webhookSecret, successURL, cancelURL string) *StripeClient {
+ stripe.Key = secretKey
+ return &StripeClient{
+ webhookSecret: webhookSecret,
+ successURL: successURL,
+ cancelURL: cancelURL,
+ PriceIDs: make(map[int]string),
+ MeterEventNames: make(map[int]string),
+ }
+}
+
+// EnsureProducts creates Billing Meters, a Product, and metered Prices if they don't exist.
+// This is idempotent — uses metadata to find existing resources.
+func (s *StripeClient) EnsureProducts() error {
+ // 1. Find or create meters (one per tier)
+ meterIDs := make(map[int]string) // memoryMB → meter ID
+ existingMeters := make(map[string]*stripe.BillingMeter)
+ iter := meter.List(&stripe.BillingMeterListParams{
+ Status: stripe.String(string(stripe.BillingMeterStatusActive)),
+ })
+ for iter.Next() {
+ m := iter.BillingMeter()
+ existingMeters[m.EventName] = m
+ }
+
+ for memMB, metaKey := range TierMetadataKey {
+ eventName := "sandbox_compute_" + metaKey
+ s.MeterEventNames[memMB] = eventName
+
+ if m, ok := existingMeters[eventName]; ok {
+ meterIDs[memMB] = m.ID
+ log.Printf("billing: found existing meter %s (id=%s)", eventName, m.ID)
+ continue
+ }
+
+ m, err := meter.New(&stripe.BillingMeterParams{
+ DisplayName: stripe.String(fmt.Sprintf("Sandbox Compute %s", metaKey)),
+ EventName: stripe.String(eventName),
+ DefaultAggregation: &stripe.BillingMeterDefaultAggregationParams{
+ Formula: stripe.String(string(stripe.BillingMeterDefaultAggregationFormulaSum)),
+ },
+ CustomerMapping: &stripe.BillingMeterCustomerMappingParams{
+ EventPayloadKey: stripe.String("stripe_customer_id"),
+ Type: stripe.String(string(stripe.BillingMeterCustomerMappingTypeByID)),
+ },
+ ValueSettings: &stripe.BillingMeterValueSettingsParams{
+ EventPayloadKey: stripe.String("value"),
+ },
+ })
+ if err != nil {
+ return fmt.Errorf("create meter %s: %w", eventName, err)
+ }
+ meterIDs[memMB] = m.ID
+ log.Printf("billing: created meter %s (id=%s)", eventName, m.ID)
+ }
+
+ // 2. Find or create product
+ productID := ""
+ prodIter := product.List(&stripe.ProductListParams{})
+ for prodIter.Next() {
+ p := prodIter.Product()
+ if p.Metadata["opensandbox"] == "compute" {
+ productID = p.ID
+ break
+ }
+ }
+ if productID == "" {
+ p, err := product.New(&stripe.ProductParams{
+ Name: stripe.String("Sandbox Compute"),
+ Metadata: map[string]string{"opensandbox": "compute"},
+ })
+ if err != nil {
+ return fmt.Errorf("create product: %w", err)
+ }
+ productID = p.ID
+ log.Printf("billing: created product %s", productID)
+ }
+
+ // 3. Find or create prices (one per tier, linked to meter)
+ existingPrices := make(map[string]string) // tier metadata key → price ID
+ priceIter := price.List(&stripe.PriceListParams{
+ Product: stripe.String(productID),
+ })
+ for priceIter.Next() {
+ p := priceIter.Price()
+ if key, ok := p.Metadata["tier"]; ok {
+ existingPrices[key] = p.ID
+ }
+ }
+
+ for memMB, metaKey := range TierMetadataKey {
+ if id, ok := existingPrices[metaKey]; ok {
+ s.PriceIDs[memMB] = id
+ log.Printf("billing: found existing price for %s (id=%s)", metaKey, id)
+ continue
+ }
+
+ meterID := meterIDs[memMB]
+ // Truncate to 12 decimal places to avoid Stripe precision errors
+ ratePerSecondCents := TierPricePerSecond[memMB] * 100
+ truncated := math.Floor(ratePerSecondCents*1e12) / 1e12
+
+ p, err := price.New(&stripe.PriceParams{
+ Product: stripe.String(productID),
+ Currency: stripe.String("usd"),
+ UnitAmountDecimal: stripe.Float64(truncated),
+ BillingScheme: stripe.String(string(stripe.PriceBillingSchemePerUnit)),
+ Recurring: &stripe.PriceRecurringParams{
+ Interval: stripe.String(string(stripe.PriceRecurringIntervalMonth)),
+ UsageType: stripe.String(string(stripe.PriceRecurringUsageTypeMetered)),
+ Meter: stripe.String(meterID),
+ },
+ Metadata: map[string]string{
+ "tier": metaKey,
+ "memory_mb": fmt.Sprintf("%d", memMB),
+ "opensandbox": "compute",
+ },
+ })
+ if err != nil {
+ return fmt.Errorf("create price for %s: %w", metaKey, err)
+ }
+ s.PriceIDs[memMB] = p.ID
+ log.Printf("billing: created price for %s (id=%s)", metaKey, p.ID)
+ }
+
+ return nil
+}
+
+// CreateCustomer creates a Stripe customer for an org.
+func (s *StripeClient) CreateCustomer(orgName, email string) (string, error) {
+ params := &stripe.CustomerParams{
+ Name: stripe.String(orgName),
+ }
+ if email != "" {
+ params.Email = stripe.String(email)
+ }
+ c, err := customer.New(params)
+ if err != nil {
+ return "", fmt.Errorf("create customer: %w", err)
+ }
+ return c.ID, nil
+}
+
+// CreateSetupCheckoutSession creates a Checkout session for adding a payment method.
+func (s *StripeClient) CreateSetupCheckoutSession(customerID, orgID string) (url, sessionID string, err error) {
+ params := &stripe.CheckoutSessionParams{
+ Customer: stripe.String(customerID),
+ Mode: stripe.String(string(stripe.CheckoutSessionModeSetup)),
+ Currency: stripe.String("usd"),
+ SuccessURL: stripe.String(s.successURL),
+ CancelURL: stripe.String(s.cancelURL),
+ Metadata: map[string]string{
+ "org_id": orgID,
+ "type": "setup",
+ },
+ }
+ sess, err := checkoutsession.New(params)
+ if err != nil {
+ return "", "", fmt.Errorf("create setup session: %w", err)
+ }
+ return sess.URL, sess.ID, nil
+}
+
+// CreateSubscription creates a subscription with metered prices for all tiers.
+// Returns subscription ID and map of memoryMB → subscription item ID.
+func (s *StripeClient) CreateSubscription(customerID string) (string, map[int]string, error) {
+ var items []*stripe.SubscriptionItemsParams
+ for _, priceID := range s.PriceIDs {
+ items = append(items, &stripe.SubscriptionItemsParams{
+ Price: stripe.String(priceID),
+ })
+ }
+
+ sub, err := subscription.New(&stripe.SubscriptionParams{
+ Customer: stripe.String(customerID),
+ Items: items,
+ })
+ if err != nil {
+ return "", nil, fmt.Errorf("create subscription: %w", err)
+ }
+
+ // Map subscription items back to memory tiers
+ itemIDs := make(map[int]string)
+ for _, si := range sub.Items.Data {
+ if si.Price != nil {
+ for memMB, priceID := range s.PriceIDs {
+ if si.Price.ID == priceID {
+ itemIDs[memMB] = si.ID
+ break
+ }
+ }
+ }
+ }
+
+ return sub.ID, itemIDs, nil
+}
+
+// ApplyPromotionalCredit sets a negative customer balance (credit).
+func (s *StripeClient) ApplyPromotionalCredit(customerID string, amountCents int64) error {
+ _, err := customer.Update(customerID, &stripe.CustomerParams{
+ Balance: stripe.Int64(-amountCents),
+ })
+ if err != nil {
+ return fmt.Errorf("apply credit: %w", err)
+ }
+ return nil
+}
+
+// ReportUsage sends a meter event for a specific tier.
+// customerID is the Stripe customer ID. seconds is the usage quantity.
+func (s *StripeClient) ReportUsage(customerID string, memoryMB int, seconds int64, timestamp int64) error {
+ eventName, ok := s.MeterEventNames[memoryMB]
+ if !ok {
+ return fmt.Errorf("no meter for tier %dMB", memoryMB)
+ }
+
+ _, err := meterevent.New(&stripe.BillingMeterEventParams{
+ EventName: stripe.String(eventName),
+ Timestamp: stripe.Int64(timestamp),
+ Payload: map[string]string{
+ "stripe_customer_id": customerID,
+ "value": fmt.Sprintf("%d", seconds),
+ },
+ })
+ if err != nil {
+ return fmt.Errorf("report usage for %s: %w", eventName, err)
+ }
+ return nil
+}
+
+// GetCustomerBalance returns the customer's balance in cents (negative = credit).
+func (s *StripeClient) GetCustomerBalance(customerID string) (int64, error) {
+ c, err := customer.Get(customerID, nil)
+ if err != nil {
+ return 0, err
+ }
+ return c.Balance, nil
+}
+
+// ListInvoices returns past invoices for a customer.
+func (s *StripeClient) ListInvoices(customerID string, limit int) ([]*stripe.Invoice, error) {
+ params := &stripe.InvoiceListParams{
+ Customer: stripe.String(customerID),
+ }
+ params.Filters.AddFilter("limit", "", fmt.Sprintf("%d", limit))
+
+ var invoices []*stripe.Invoice
+ iter := invoice.List(params)
+ for iter.Next() {
+ invoices = append(invoices, iter.Invoice())
+ }
+ return invoices, iter.Err()
+}
+
+// GetUpcomingInvoice returns a preview of the upcoming invoice.
+func (s *StripeClient) GetUpcomingInvoice(customerID string) (*stripe.Invoice, error) {
+ return invoice.CreatePreview(&stripe.InvoiceCreatePreviewParams{
+ Customer: stripe.String(customerID),
+ })
+}
+
+// VerifyWebhookSignature verifies a Stripe webhook event.
+func (s *StripeClient) VerifyWebhookSignature(payload []byte, sigHeader string) (*stripe.Event, error) {
+ event, err := webhook.ConstructEventWithOptions(payload, sigHeader, s.webhookSecret, webhook.ConstructEventOptions{
+ IgnoreAPIVersionMismatch: true,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &event, nil
+}
diff --git a/internal/billing/usage_reporter.go b/internal/billing/usage_reporter.go
new file mode 100644
index 00000000..21970cb8
--- /dev/null
+++ b/internal/billing/usage_reporter.go
@@ -0,0 +1,109 @@
+package billing
+
+import (
+ "context"
+ "log"
+ "math"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// UsageReporter periodically reports sandbox usage to Stripe via Billing Meter Events.
+type UsageReporter struct {
+ store *db.Store
+ stripe *StripeClient
+ interval time.Duration
+ stop chan struct{}
+ stopped chan struct{}
+}
+
+func NewUsageReporter(store *db.Store, stripe *StripeClient) *UsageReporter {
+ return &UsageReporter{
+ store: store,
+ stripe: stripe,
+ interval: 5 * time.Minute,
+ stop: make(chan struct{}),
+ stopped: make(chan struct{}),
+ }
+}
+
+func (r *UsageReporter) Start() { go r.loop() }
+func (r *UsageReporter) Stop() { close(r.stop); <-r.stopped }
+
+func (r *UsageReporter) loop() {
+ defer close(r.stopped)
+ ticker := time.NewTicker(r.interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ r.reportAll()
+ case <-r.stop:
+ return
+ }
+ }
+}
+
+func (r *UsageReporter) reportAll() {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+
+ orgIDs, err := r.store.ListBillableOrgIDs(ctx)
+ if err != nil {
+ log.Printf("usage-reporter: failed to list billable orgs: %v", err)
+ return
+ }
+ if len(orgIDs) == 0 {
+ return
+ }
+
+ log.Printf("usage-reporter: reporting for %d org(s)", len(orgIDs))
+ for _, orgID := range orgIDs {
+ if err := r.reportOrg(ctx, orgID); err != nil {
+ log.Printf("usage-reporter: org %s: %v", orgID, err)
+ }
+ }
+}
+
+func (r *UsageReporter) reportOrg(ctx context.Context, orgID uuid.UUID) error {
+ org, err := r.store.GetOrg(ctx, orgID)
+ if err != nil {
+ return err
+ }
+ if org.StripeCustomerID == nil {
+ return nil
+ }
+
+ now := time.Now()
+ from := org.LastUsageReportedAt
+ to := now
+
+ usage, err := r.store.GetOrgUsage(ctx, orgID.String(), from, to)
+ if err != nil {
+ return err
+ }
+
+ reported := 0
+ for _, u := range usage {
+ seconds := int64(math.Ceil(u.TotalSeconds))
+ if seconds < 1 {
+ continue
+ }
+ if err := r.stripe.ReportUsage(*org.StripeCustomerID, u.MemoryMB, seconds, now.Unix()); err != nil {
+ log.Printf("usage-reporter: org %s tier %dMB: %v", orgID, u.MemoryMB, err)
+ continue
+ }
+ reported++
+ }
+
+ if err := r.store.UpdateLastUsageReportedAt(ctx, orgID, to); err != nil {
+ log.Printf("usage-reporter: org %s: failed to update watermark: %v", orgID, err)
+ }
+
+ if reported > 0 {
+ log.Printf("usage-reporter: org %s — reported %d tier(s) to Stripe", orgID, reported)
+ }
+ return nil
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 191983e4..5d84cd33 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -97,6 +97,12 @@ type Config struct {
MinWorkersPerRegion int // Minimum workers per region (for pre-provisioned capacity), default 1
MaxWorkersPerRegion int // Maximum workers per region (hard cap), default 10
+ // Stripe billing
+ StripeSecretKey string
+ StripeWebhookSecret string
+ StripeSuccessURL string
+ StripeCancelURL string
+
// AWS Secrets Manager — if set, secrets are fetched at startup using IAM credentials.
// The secret should be a JSON object with keys matching env var names (e.g. OPENSANDBOX_JWT_SECRET).
// Env vars take precedence over secret values (for local overrides).
@@ -183,6 +189,11 @@ func Load() (*Config, error) {
MinWorkersPerRegion: envOrDefaultInt("OPENSANDBOX_MIN_WORKERS", 1),
MaxWorkersPerRegion: envOrDefaultInt("OPENSANDBOX_MAX_WORKERS", 10),
+ StripeSecretKey: os.Getenv("STRIPE_SECRET_KEY"),
+ StripeWebhookSecret: os.Getenv("STRIPE_WEBHOOK_SECRET"),
+ StripeSuccessURL: envOrDefault("STRIPE_SUCCESS_URL", "http://localhost:3000/billing?success=true"),
+ StripeCancelURL: envOrDefault("STRIPE_CANCEL_URL", "http://localhost:3000/billing?cancelled=true"),
+
SecretsARN: os.Getenv("OPENSANDBOX_SECRETS_ARN"),
SecretEncryptionKey: os.Getenv("OPENSANDBOX_SECRET_ENCRYPTION_KEY"),
diff --git a/internal/db/migrations/015_secret_allowed_hosts.up.sql b/internal/db/migrations/015_secret_allowed_hosts.up.sql
index 2c267f54..f82af007 100644
--- a/internal/db/migrations/015_secret_allowed_hosts.up.sql
+++ b/internal/db/migrations/015_secret_allowed_hosts.up.sql
@@ -26,10 +26,10 @@ CREATE TABLE IF NOT EXISTS secret_store_entries (
);
CREATE INDEX IF NOT EXISTS idx_secret_store_entries_store ON secret_store_entries(store_id);
--- Drop old project tables (secrets first due to FK)
+-- Remove project_id FK from sandbox_sessions first, then drop old tables
+ALTER TABLE sandbox_sessions DROP COLUMN IF EXISTS project_id;
DROP TABLE IF EXISTS project_secrets;
DROP TABLE IF EXISTS projects;
--- Update sandbox_sessions: replace project_id with secret_store_id
-ALTER TABLE sandbox_sessions DROP COLUMN IF EXISTS project_id;
+-- Add secret_store_id reference
ALTER TABLE sandbox_sessions ADD COLUMN IF NOT EXISTS secret_store_id UUID REFERENCES secret_stores(id);
diff --git a/internal/db/migrations/017_stripe_billing.down.sql b/internal/db/migrations/017_stripe_billing.down.sql
new file mode 100644
index 00000000..70077ac3
--- /dev/null
+++ b/internal/db/migrations/017_stripe_billing.down.sql
@@ -0,0 +1,5 @@
+DROP TABLE IF EXISTS org_subscription_items;
+ALTER TABLE orgs DROP COLUMN IF EXISTS last_usage_reported_at;
+ALTER TABLE orgs DROP COLUMN IF EXISTS monthly_spend_cap_cents;
+ALTER TABLE orgs DROP COLUMN IF EXISTS stripe_subscription_id;
+ALTER TABLE orgs DROP COLUMN IF EXISTS stripe_customer_id;
diff --git a/internal/db/migrations/017_stripe_billing.up.sql b/internal/db/migrations/017_stripe_billing.up.sql
new file mode 100644
index 00000000..81532f3c
--- /dev/null
+++ b/internal/db/migrations/017_stripe_billing.up.sql
@@ -0,0 +1,13 @@
+-- Stripe billing fields on orgs
+ALTER TABLE orgs ADD COLUMN stripe_customer_id TEXT UNIQUE;
+ALTER TABLE orgs ADD COLUMN stripe_subscription_id TEXT;
+ALTER TABLE orgs ADD COLUMN monthly_spend_cap_cents INT;
+ALTER TABLE orgs ADD COLUMN last_usage_reported_at TIMESTAMPTZ NOT NULL DEFAULT now();
+
+-- Mapping of org subscription items (one per metered price/tier)
+CREATE TABLE IF NOT EXISTS org_subscription_items (
+ org_id UUID NOT NULL REFERENCES orgs(id),
+ memory_mb INT NOT NULL,
+ stripe_subscription_item_id TEXT NOT NULL,
+ PRIMARY KEY (org_id, memory_mb)
+);
diff --git a/internal/db/store.go b/internal/db/store.go
index 933c8abd..1f8a53dd 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -88,6 +88,9 @@ func (s *Store) Migrate(ctx context.Context) error {
{14, "migrations/014_image_cache.up.sql"},
{15, "migrations/015_projects.up.sql"},
{16, "migrations/016_orgs_workos.up.sql"},
+ {17, "migrations/015_sandbox_usage.up.sql"},
+ {18, "migrations/015_secret_allowed_hosts.up.sql"},
+ {19, "migrations/017_stripe_billing.up.sql"},
}
for _, m := range migrations {
@@ -145,13 +148,20 @@ type Org struct {
IsPersonal bool `json:"isPersonal"`
OwnerUserID *uuid.UUID `json:"ownerUserId,omitempty"`
CreditBalanceCents int `json:"creditBalanceCents"`
+
+ // Stripe billing fields
+ StripeCustomerID *string `json:"stripeCustomerId,omitempty"`
+ StripeSubscriptionID *string `json:"stripeSubscriptionId,omitempty"`
+ MonthlySpendCapCents *int `json:"monthlySpendCapCents,omitempty"`
+ LastUsageReportedAt time.Time `json:"lastUsageReportedAt"`
}
// orgColumns is the list of columns returned by all Org queries.
const orgColumns = `id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_timeout_sec, created_at, updated_at,
custom_domain, cf_hostname_id, domain_verification_status, domain_ssl_status,
verification_txt_name, verification_txt_value, ssl_txt_name, ssl_txt_value,
- workos_org_id, is_personal, owner_user_id, credit_balance_cents`
+ workos_org_id, is_personal, owner_user_id, credit_balance_cents,
+ stripe_customer_id, stripe_subscription_id, monthly_spend_cap_cents, last_usage_reported_at`
// scanOrg scans a row into an Org struct.
func scanOrg(row pgx.Row) (*Org, error) {
@@ -162,6 +172,7 @@ func scanOrg(row pgx.Row) (*Org, error) {
&org.CustomDomain, &org.CFHostnameID, &org.DomainVerificationStatus, &org.DomainSSLStatus,
&org.VerificationTxtName, &org.VerificationTxtValue, &org.SSLTxtName, &org.SSLTxtValue,
&org.WorkOSOrgID, &org.IsPersonal, &org.OwnerUserID, &org.CreditBalanceCents,
+ &org.StripeCustomerID, &org.StripeSubscriptionID, &org.MonthlySpendCapCents, &org.LastUsageReportedAt,
)
return org, err
}
diff --git a/internal/db/usage.go b/internal/db/usage.go
index 0e4e0b17..c93ab80d 100644
--- a/internal/db/usage.go
+++ b/internal/db/usage.go
@@ -3,6 +3,8 @@ package db
import (
"context"
"time"
+
+ "github.com/google/uuid"
)
// ScaleEvent represents a period at a specific resource tier.
@@ -123,3 +125,134 @@ func (s *Store) GetOrgUsage(ctx context.Context, orgID string, from, to time.Tim
}
return results, rows.Err()
}
+
+// --- Stripe billing methods ---
+
+// SetStripeCustomerID sets the Stripe customer ID for an org.
+func (s *Store) SetStripeCustomerID(ctx context.Context, orgID uuid.UUID, customerID string) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE orgs SET stripe_customer_id = $2, updated_at = now() WHERE id = $1`,
+ orgID, customerID)
+ return err
+}
+
+// SetStripeSubscriptionID sets the Stripe subscription ID for an org.
+func (s *Store) SetStripeSubscriptionID(ctx context.Context, orgID uuid.UUID, subscriptionID string) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE orgs SET stripe_subscription_id = $2, updated_at = now() WHERE id = $1`,
+ orgID, subscriptionID)
+ return err
+}
+
+// UpdateOrgPlan changes the org plan (e.g. "free" -> "pro").
+func (s *Store) UpdateOrgPlan(ctx context.Context, orgID uuid.UUID, plan string) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE orgs SET plan = $2, updated_at = now() WHERE id = $1`,
+ orgID, plan)
+ return err
+}
+
+// SetMonthlySpendCap updates the monthly spend cap for an org.
+func (s *Store) SetMonthlySpendCap(ctx context.Context, orgID uuid.UUID, capCents *int) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE orgs SET monthly_spend_cap_cents = $2, updated_at = now() WHERE id = $1`,
+ orgID, capCents)
+ return err
+}
+
+// UpdateLastUsageReportedAt updates the usage reporting watermark.
+func (s *Store) UpdateLastUsageReportedAt(ctx context.Context, orgID uuid.UUID, t time.Time) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE orgs SET last_usage_reported_at = $2 WHERE id = $1`,
+ orgID, t)
+ return err
+}
+
+// ListBillableOrgIDs returns org IDs with plan="pro" and at least one open scale event.
+func (s *Store) ListBillableOrgIDs(ctx context.Context) ([]uuid.UUID, error) {
+ rows, err := s.pool.Query(ctx,
+ `SELECT DISTINCT se.org_id
+ FROM sandbox_scale_events se
+ JOIN orgs o ON o.id = se.org_id
+ WHERE se.ended_at IS NULL AND o.plan = 'pro'`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var ids []uuid.UUID
+ for rows.Next() {
+ var id uuid.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ ids = append(ids, id)
+ }
+ return ids, rows.Err()
+}
+
+// SubscriptionItem maps a memory tier to a Stripe subscription item ID.
+type SubscriptionItem struct {
+ OrgID uuid.UUID `json:"orgId"`
+ MemoryMB int `json:"memoryMB"`
+ StripeSubscriptionItemID string `json:"stripeSubscriptionItemId"`
+}
+
+// SaveSubscriptionItems inserts or updates the org's subscription item mapping.
+func (s *Store) SaveSubscriptionItems(ctx context.Context, orgID uuid.UUID, items map[int]string) error {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback(ctx)
+
+ for memoryMB, itemID := range items {
+ _, err := tx.Exec(ctx,
+ `INSERT INTO org_subscription_items (org_id, memory_mb, stripe_subscription_item_id)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (org_id, memory_mb) DO UPDATE SET stripe_subscription_item_id = $3`,
+ orgID, memoryMB, itemID)
+ if err != nil {
+ return err
+ }
+ }
+ return tx.Commit(ctx)
+}
+
+// DeductCredits subtracts cents from an org's credit balance.
+func (s *Store) DeductCredits(ctx context.Context, orgID uuid.UUID, amountCents int) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE orgs SET credit_balance_cents = credit_balance_cents - $2, updated_at = now() WHERE id = $1`,
+ orgID, amountCents)
+ return err
+}
+
+// AddCredits adds cents to an org's credit balance.
+func (s *Store) AddCredits(ctx context.Context, orgID uuid.UUID, amountCents int) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE orgs SET credit_balance_cents = credit_balance_cents + $2, updated_at = now() WHERE id = $1`,
+ orgID, amountCents)
+ return err
+}
+
+// GetSubscriptionItems returns the subscription item mapping for an org.
+func (s *Store) GetSubscriptionItems(ctx context.Context, orgID uuid.UUID) (map[int]string, error) {
+ rows, err := s.pool.Query(ctx,
+ `SELECT memory_mb, stripe_subscription_item_id FROM org_subscription_items WHERE org_id = $1`,
+ orgID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ items := make(map[int]string)
+ for rows.Next() {
+ var memMB int
+ var itemID string
+ if err := rows.Scan(&memMB, &itemID); err != nil {
+ return nil, err
+ }
+ items[memMB] = itemID
+ }
+ return items, rows.Err()
+}
diff --git a/web/src/App.tsx b/web/src/App.tsx
index 635bbb1a..f9737438 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -9,6 +9,7 @@ import APIKeys from './pages/APIKeys'
import Checkpoints from './pages/Checkpoints'
import Templates from './pages/Templates'
import Settings from './pages/Settings'
+import Billing from './pages/Billing'
import SessionDetail from './pages/SessionDetail'
export default function App() {
@@ -24,6 +25,7 @@ export default function App() {
<Route path="checkpoints" element={<Checkpoints />} />
<Route path="templates" element={<Templates />} />
<Route path="api-keys" element={<APIKeys />} />
+ <Route path="billing" element={<Billing />} />
<Route path="settings" element={<Settings />} />
</Route>
</Route>
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index a8bf72f5..9b6b5603 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -271,3 +271,49 @@ export const switchOrg = (orgId: string) =>
// Credits
export const getCredits = () => apiFetch<Credits>('/org/credits')
+
+// Billing types
+export interface BillingTierUsage {
+ memoryMB: number
+ vcpus: number
+ totalSeconds: number
+ costCents: number
+}
+
+export interface BillingState {
+ plan: string
+ stripeCreditCents: number
+ monthlySpendCapCents: number | null
+ hasPaymentMethod: boolean
+ currentUsage: {
+ tiers: BillingTierUsage[]
+ totalCostCents: number
+ }
+}
+
+export interface StripeInvoice {
+ id: string
+ number: string
+ status: string
+ amountDue: number
+ amountPaid: number
+ currency: string
+ created: number
+ hostedUrl: string
+ pdfUrl: string
+}
+
+// Billing API
+export const getBilling = () => apiFetch<BillingState>('/billing')
+
+export const billingSetup = () =>
+ apiFetch<{ url: string }>('/billing/setup', { method: 'POST' })
+
+export const updateBillingSettings = (settings: { monthlySpendCapCents: number | null }) =>
+ apiFetch<{ status: string }>('/billing/settings', {
+ method: 'PUT',
+ body: JSON.stringify(settings),
+ })
+
+export const getBillingInvoices = (limit = 10) =>
+ apiFetch<{ invoices: StripeInvoice[] }>(`/billing/invoices?limit=${limit}`)
diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsx
index d0cf41e3..ce51bd8a 100644
--- a/web/src/components/Layout.tsx
+++ b/web/src/components/Layout.tsx
@@ -38,6 +38,12 @@ const icons = {
<line x1="12" y1="22.08" x2="12" y2="12" />
</svg>
),
+ creditCard: (
+ <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
+ <rect x="1" y="4" width="22" height="16" rx="2" ry="2" />
+ <line x1="1" y1="10" x2="23" y2="10" />
+ </svg>
+ ),
gear: (
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="3" />
@@ -59,6 +65,7 @@ const navItems = [
{ to: '/checkpoints', label: 'Checkpoints', icon: icons.layers },
{ to: '/templates', label: 'Templates', icon: icons.box },
{ to: '/api-keys', label: 'API Keys', icon: icons.key },
+ { to: '/billing', label: 'Billing', icon: icons.creditCard },
{ to: '/settings', label: 'Settings', icon: icons.gear },
]
diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsx
new file mode 100644
index 00000000..232982b7
--- /dev/null
+++ b/web/src/pages/Billing.tsx
@@ -0,0 +1,298 @@
+import { useState } from 'react'
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import {
+ getBilling, billingSetup, updateBillingSettings, getBillingInvoices,
+ type BillingTierUsage, type StripeInvoice,
+} from '../api/client'
+
+const PRICING_TIERS = [
+ { memory: '4 GB', vcpus: 1, perSec: 0.00003240740741 },
+ { memory: '8 GB', vcpus: 2, perSec: 0.000150462963 },
+ { memory: '16 GB', vcpus: 4, perSec: 0.0008101851852 },
+ { memory: '32 GB', vcpus: 8, perSec: 0.005787037037 },
+ { memory: '64 GB', vcpus: 16, perSec: 0.0162037037 },
+]
+
+export default function Billing() {
+ const queryClient = useQueryClient()
+ const { data: billing, isLoading } = useQuery({ queryKey: ['billing'], queryFn: getBilling })
+ const { data: invoiceData } = useQuery({ queryKey: ['invoices'], queryFn: () => getBillingInvoices() })
+
+ const [spendCap, setSpendCap] = useState('')
+ const [settingsSaved, setSettingsSaved] = useState(false)
+
+ const setupMutation = useMutation({
+ mutationFn: billingSetup,
+ onSuccess: (data) => { window.location.href = data.url },
+ })
+
+ const settingsMutation = useMutation({
+ mutationFn: () => updateBillingSettings({
+ monthlySpendCapCents: spendCap ? Math.round(parseFloat(spendCap) * 100) : null,
+ }),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['billing'] })
+ setSettingsSaved(true)
+ setTimeout(() => setSettingsSaved(false), 2000)
+ },
+ })
+
+ const isPro = billing?.plan === 'pro'
+
+ return (
+ <div>
+ <div style={{ marginBottom: 32 }}>
+ <h1 className="page-title">Billing</h1>
+ <p className="page-subtitle">Manage your plan, usage, and payment settings</p>
+ </div>
+
+ {isLoading ? (
+ <div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>
+ <div className="loading-spinner" />
+ </div>
+ ) : (
+ <>
+ {/* Plan + Usage row */}
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
+
+ {/* Plan Card */}
+ <div className="glass-card animate-in stagger-1" style={{ padding: 28 }}>
+ <span className="section-title" style={{ marginBottom: 16, display: 'block' }}>
+ Current Plan
+ </span>
+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>
+ <span className="metric-value" style={{
+ fontSize: 36, fontWeight: 700,
+ color: isPro ? 'var(--accent-indigo)' : 'var(--text-primary)',
+ }}>
+ {isPro ? 'Pro' : 'Free'}
+ </span>
+ {!isPro && (
+ <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
+ 1 sandbox, 4GB / 1 vCPU
+ </span>
+ )}
+ </div>
+
+ {isPro && billing?.stripeCreditCents != null && billing.stripeCreditCents > 0 && (
+ <div style={{ fontSize: 13, color: 'var(--accent-emerald)', marginBottom: 12 }}>
+ ${(billing.stripeCreditCents / 100).toFixed(2)} promotional credit remaining
+ </div>
+ )}
+
+ {!isPro && (
+ <div style={{ marginTop: 16 }}>
+ <button
+ onClick={() => setupMutation.mutate()}
+ disabled={setupMutation.isPending}
+ style={{
+ padding: '10px 24px', fontSize: 14, fontWeight: 600,
+ fontFamily: 'var(--font-body)', cursor: 'pointer',
+ border: 'none', borderRadius: 'var(--radius-sm)',
+ background: 'var(--accent-indigo)', color: '#fff',
+ opacity: setupMutation.isPending ? 0.6 : 1,
+ }}
+ >
+ {setupMutation.isPending ? 'Redirecting...' : 'Upgrade to Pro — $30 free credit'}
+ </button>
+ {setupMutation.isError && (
+ <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 8 }}>
+ {(setupMutation.error as Error).message}
+ </p>
+ )}
+ </div>
+ )}
+
+ {isPro && (
+ <div style={{
+ fontSize: 11, color: 'var(--accent-emerald)', marginTop: 4,
+ display: 'flex', alignItems: 'center', gap: 6,
+ }}>
+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><polyline points="20 6 9 17 4 12" /></svg>
+ Payment method on file — billed monthly via Stripe
+ </div>
+ )}
+ </div>
+
+ {/* Current Usage */}
+ <div className="glass-card animate-in stagger-2" style={{ padding: 28 }}>
+ <span className="section-title" style={{ marginBottom: 16, display: 'block' }}>
+ Current Month Usage
+ </span>
+ {!billing?.currentUsage?.tiers?.length ? (
+ <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>
+ No usage this month
+ </div>
+ ) : (
+ <>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
+ {billing.currentUsage.tiers.map((tier: BillingTierUsage) => (
+ <div key={tier.memoryMB} style={{
+ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
+ padding: '8px 12px', borderRadius: 'var(--radius-sm)',
+ background: 'rgba(255,255,255,0.02)', border: '1px solid rgba(255,255,255,0.03)',
+ }}>
+ <div>
+ <span style={{ fontSize: 13, color: 'var(--text-primary)', fontWeight: 500 }}>
+ {tier.memoryMB / 1024} GB
+ </span>
+ <span style={{ fontSize: 11, color: 'var(--text-tertiary)', marginLeft: 8 }}>
+ {tier.vcpus} vCPU
+ </span>
+ </div>
+ <div style={{ textAlign: 'right' }}>
+ <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-primary)' }}>
+ ${(tier.costCents / 100).toFixed(4)}
+ </span>
+ <span style={{ fontSize: 10, color: 'var(--text-tertiary)', marginLeft: 8 }}>
+ {formatSeconds(tier.totalSeconds)}
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ <div style={{
+ display: 'flex', justifyContent: 'space-between', alignItems: 'center',
+ paddingTop: 12, borderTop: '1px solid var(--border-subtle)',
+ }}>
+ <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-secondary)' }}>Total</span>
+ <span className="metric-value" style={{ fontSize: 18, color: 'var(--accent-cyan)' }}>
+ ${(billing.currentUsage.totalCostCents / 100).toFixed(4)}
+ </span>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Pricing Table */}
+ <div className="glass-card animate-in stagger-3" style={{ padding: '22px 24px', marginBottom: 14 }}>
+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 0 }}>Pricing</span>
+ <span style={{ fontSize: 11, color: 'var(--accent-emerald)', fontFamily: 'var(--font-mono)' }}>
+ Hibernated sandboxes are not charged
+ </span>
+ </div>
+ <table className="data-table">
+ <thead>
+ <tr><th>Memory</th><th>vCPUs</th><th>Per Second</th></tr>
+ </thead>
+ <tbody>
+ {PRICING_TIERS.map(t => (
+ <tr key={t.memory}>
+ <td style={{ fontWeight: 600, color: 'var(--text-primary)' }}>{t.memory}</td>
+ <td>{t.vcpus}</td>
+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--accent-cyan)' }}>
+ ${t.perSec.toFixed(11)}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+
+ {/* Monthly Spend Cap (pro only) */}
+ {isPro && (
+ <div className="glass-card animate-in stagger-4" style={{ padding: '22px 24px', marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 16, display: 'block' }}>Spending Cap</span>
+ <div style={{ display: 'flex', alignItems: 'end', gap: 14 }}>
+ <div>
+ <label style={{ fontSize: 11, color: 'var(--text-tertiary)', display: 'block', marginBottom: 6 }}>
+ Max monthly spend (optional)
+ </label>
+ <div style={{ position: 'relative' }}>
+ <span style={{
+ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)',
+ color: 'var(--text-tertiary)', fontSize: 13,
+ }}>$</span>
+ <input
+ className="input"
+ type="number" min="0" placeholder="No limit"
+ value={spendCap}
+ onChange={e => setSpendCap(e.target.value)}
+ style={{ width: 200, paddingLeft: 22, boxSizing: 'border-box', fontFamily: 'var(--font-mono)', fontSize: 13 }}
+ />
+ </div>
+ </div>
+ <button
+ onClick={() => settingsMutation.mutate()}
+ disabled={settingsMutation.isPending}
+ style={{
+ padding: '8px 20px', fontSize: 13, fontWeight: 600,
+ fontFamily: 'var(--font-body)', cursor: 'pointer',
+ border: 'none', borderRadius: 'var(--radius-sm)',
+ background: 'var(--accent-indigo)', color: '#fff',
+ }}
+ >
+ Save
+ </button>
+ {settingsSaved && <span style={{ fontSize: 12, color: 'var(--accent-emerald)' }}>Saved</span>}
+ </div>
+ </div>
+ )}
+
+ {/* Invoice History (pro only) */}
+ {isPro && (
+ <div className="glass-card animate-in stagger-5" style={{ padding: '22px 24px' }}>
+ <span className="section-title" style={{ marginBottom: 14, display: 'block' }}>Invoices</span>
+ {!invoiceData?.invoices?.length ? (
+ <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-tertiary)', fontSize: 13 }}>
+ No invoices yet — your first invoice will appear at the end of the billing period
+ </div>
+ ) : (
+ <table className="data-table">
+ <thead>
+ <tr><th>Date</th><th>Number</th><th>Status</th><th>Amount</th><th></th></tr>
+ </thead>
+ <tbody>
+ {invoiceData.invoices.map((inv: StripeInvoice) => (
+ <tr key={inv.id}>
+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12 }}>
+ {new Date(inv.created * 1000).toLocaleDateString()}
+ </td>
+ <td style={{ fontSize: 12 }}>{inv.number}</td>
+ <td><InvoiceStatus status={inv.status} /></td>
+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 13, fontWeight: 600 }}>
+ ${(inv.amountDue / 100).toFixed(2)}
+ </td>
+ <td>
+ {inv.hostedUrl && (
+ <a href={inv.hostedUrl} target="_blank" rel="noreferrer"
+ style={{ fontSize: 12, color: 'var(--accent-indigo)', textDecoration: 'none' }}>
+ View
+ </a>
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ )
+}
+
+function InvoiceStatus({ status }: { status: string }) {
+ let color = 'var(--text-tertiary)'
+ let bg = 'rgba(255,255,255,0.04)'
+ if (status === 'paid') { color = 'var(--accent-emerald)'; bg = 'rgba(52,211,153,0.1)' }
+ else if (status === 'open') { color = 'var(--accent-cyan)'; bg = 'rgba(34,211,238,0.1)' }
+ else if (status === 'uncollectible') { color = 'var(--accent-rose)'; bg = 'rgba(244,63,94,0.1)' }
+ return (
+ <span style={{
+ display: 'inline-block', padding: '2px 8px', borderRadius: 4,
+ fontSize: 11, fontWeight: 600, color, background: bg,
+ textTransform: 'uppercase', letterSpacing: '0.5px',
+ }}>{status}</span>
+ )
+}
+
+function formatSeconds(s: number): string {
+ if (s < 60) return `${Math.round(s)}s`
+ if (s < 3600) return `${Math.round(s / 60)}m`
+ return `${(s / 3600).toFixed(1)}h`
+}
diff --git a/web/vite.config.ts b/web/vite.config.ts
index 52d9b760..910705a7 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -12,6 +12,7 @@ export default defineConfig({
target: 'http://localhost:8080',
ws: true,
},
+ '/webhooks': 'http://localhost:8080',
},
},
})