Skip to content

An open-source, faster Devin alternative

TypeScript

Fix metered billing gaps, enforce free tier scaling, add promo codes (#93)

Mohamed Habibfab434befa8a
diff --git a/go.mod b/go.mod
index cca2c070..48569fe0 100644
--- a/go.mod
+++ b/go.mod
@@ -3,11 +3,14 @@ module github.com/opensandbox/opensandbox
go 1.24.0
require (
+ github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0
+ github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1
+ github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute v1.0.0
+ github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0
github.com/aws/aws-sdk-go-v2 v1.41.2
github.com/aws/aws-sdk-go-v2/config v1.32.10
github.com/aws/aws-sdk-go-v2/credentials v1.19.10
github.com/aws/aws-sdk-go-v2/service/ec2 v1.290.1
- github.com/aws/aws-sdk-go-v2/service/ecr v1.55.2
github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0
github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.41.2
github.com/creack/pty v1.1.24
@@ -22,6 +25,7 @@ require (
github.com/prometheus/client_golang v1.20.5
github.com/redis/go-redis/v9 v9.18.0
github.com/spf13/cobra v1.10.2
+ github.com/stripe/stripe-go/v82 v82.5.1
github.com/workos/workos-go/v4 v4.46.1
golang.org/x/sys v0.41.0
golang.org/x/term v0.40.0
@@ -30,11 +34,7 @@ require (
)
require (
- github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 // indirect
- github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 // indirect
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect
- github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute v1.0.0 // indirect
- github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.18 // indirect
@@ -72,7 +72,6 @@ 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 af03c8b2..02896a0b 100644
--- a/go.sum
+++ b/go.sum
@@ -2,12 +2,20 @@ github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 h1:fou+2+WFTib47nS+nz/ozhEB
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0/go.mod h1:t76Ruy8AHvUAC8GfMWJMa0ElSbuIcO03NLpynfbgsPA=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 h1:Hk5QBxZQC1jb2Fwj6mpzme37xbCDdNTxU7O9eb5+LB4=
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1/go.mod h1:IYus9qsFobWIc2YVwe/WPjcnyCkPKtnHAqUYeebc8z0=
+github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2 h1:yz1bePFlP5Vws5+8ez6T3HWXPmwOK7Yvq8QxDBD3SKY=
+github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.3.2/go.mod h1:Pa9ZNPuoNu/GztvBSKk9J1cDJW6vk/n0zLtV4mgd8N8=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 h1:9iefClla7iYpfYWdzPCRDozdmndjTm8DXdpCzPajMgA=
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2/go.mod h1:XtLgD3ZD34DAaVIIAyG3objl5DynM3CQ/vMcbBNJZGI=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute v1.0.0 h1:/Di3vB4sNeQ+7A8efjUVENvyB945Wruvstucqp7ZArg=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute v1.0.0/go.mod h1:gM3K25LQlsET3QR+4V74zxCsFAy0r6xMNN9n80SZn+4=
+github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal v1.0.0 h1:lMW1lD/17LUA5z1XTURo7LcVG2ICBPlyMHjIUrcFZNQ=
+github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal v1.0.0/go.mod h1:ceIuwmxDWptoW3eCqSXlnPsZFKh4X+R38dWPv7GS9Vs=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0 h1:QM6sE5k2ZT/vI5BEe0r7mqjsUSnhVBFbOsVkEuaEfiA=
github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0/go.mod h1:243D9iHbcQXoFUtgHJwL7gl2zx1aDuDMjvBZVGr2uW0=
+github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.0.0 h1:ECsQtyERDVz3NP3kvDOTLvbQhqWp/x9EsGKtb4ogUr8=
+github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.0.0/go.mod h1:s1tW/At+xHqjNFvWU4G0c0Qv33KOhvbGNj0RCTQDV8s=
+github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
+github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs=
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk=
github.com/aws/aws-sdk-go-v2 v1.41.2 h1:LuT2rzqNQsauaGkPK/7813XxcZ3o3yePY0Iy891T2ls=
@@ -30,8 +38,6 @@ github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 h1:JqcdRG//czea7Ppjb+g/n4o8i/R
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17/go.mod h1:CO+WeGmIdj/MlPel2KwID9Gt7CNq4M65HUfBW97liM0=
github.com/aws/aws-sdk-go-v2/service/ec2 v1.290.1 h1:iNxv8JSlaMFSo/DDDGsAPgvPuONsfNp6kyJnzjHgIQ4=
github.com/aws/aws-sdk-go-v2/service/ec2 v1.290.1/go.mod h1:2dMnUs1QzlGzsm46i9oBHAxVHQp7b6qF7PljWcgVEVE=
-github.com/aws/aws-sdk-go-v2/service/ecr v1.55.2 h1:eEiC82g/AJpNtBB73Par9iO/EbWXcl8vh6tbM8wb+EM=
-github.com/aws/aws-sdk-go-v2/service/ecr v1.55.2/go.mod h1:cpYRXx5BkmS3mwWRKPbWSPKmyAUNL7aLWAPiiinwk/U=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.5 h1:CeY9LUdur+Dxoeldqoun6y4WtJ3RQtzk0JMP2gfUay0=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.5/go.mod h1:AZLZf2fMaahW5s/wMRciu1sYbdsikT/UHwbUjOdEVTc=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 h1:Z5EiPIzXKewUQK0QTMkutjiaPVeVYXX7KIqhXu/0fXs=
@@ -76,8 +82,6 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
-github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
-github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
@@ -100,6 +104,8 @@ github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI=
github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
+github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRtuthU=
+github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k=
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
@@ -153,8 +159,9 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
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/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
+github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
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=
@@ -178,16 +185,10 @@ go.opentelemetry.io/otel/trace v1.31.0/go.mod h1:TXZkRk7SM2ZQLtR6eoAWQFIHPvzQ06F
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
-golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
-golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
-golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
-golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
-golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
-golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -197,8 +198,6 @@ golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
-golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
-golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=
diff --git a/internal/api/dashboard_billing.go b/internal/api/dashboard_billing.go
index 40df8bc2..34749c84 100644
--- a/internal/api/dashboard_billing.go
+++ b/internal/api/dashboard_billing.go
@@ -103,10 +103,10 @@ func (s *Server) billingGet(c echo.Context) error {
}
return c.JSON(http.StatusOK, map[string]interface{}{
- "plan": org.Plan,
- "stripeCreditCents": stripeCreditCents,
- "monthlySpendCapCents": org.MonthlySpendCapCents,
- "hasPaymentMethod": org.StripeCustomerID != nil,
+ "plan": org.Plan,
+ "stripeCreditCents": stripeCreditCents,
+ "maxConcurrentSandboxes": org.MaxConcurrentSandboxes,
+ "hasPaymentMethod": org.StripeCustomerID != nil,
"currentUsage": map[string]interface{}{
"tiers": tiers,
"totalCostCents": totalCost,
@@ -114,25 +114,41 @@ func (s *Server) billingGet(c echo.Context) error {
})
}
-// 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"})
+// billingRedeem redeems a promotion code and applies the credit to the org's Stripe balance.
+func (s *Server) billingRedeem(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"})
}
var req struct {
- MonthlySpendCapCents *int `json:"monthlySpendCapCents"`
+ Code string `json:"code"`
}
- if err := c.Bind(&req); err != nil {
- return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request"})
+ if err := c.Bind(&req); err != nil || req.Code == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "code is required"})
}
- 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"})
+
+ 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"})
}
- return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
+ if org.StripeCustomerID == nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "billing not set up — upgrade to Pro first"})
+ }
+
+ amountCents, err := s.stripeClient.RedeemPromotionCode(*org.StripeCustomerID, req.Code)
+ if err != nil {
+ log.Printf("billing: redeem failed for org %s: %v", orgID, err)
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
+ }
+
+ log.Printf("billing: org %s redeemed promo code %q for $%.2f", orgID, req.Code, float64(amountCents)/100)
+ return c.JSON(http.StatusOK, map[string]interface{}{
+ "creditAppliedCents": amountCents,
+ })
}
// billingInvoices returns past Stripe invoices.
diff --git a/internal/api/router.go b/internal/api/router.go
index 219de025..798e2695 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -325,8 +325,8 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// Billing
dash.POST("/billing/setup", s.billingSetup)
dash.GET("/billing", s.billingGet)
- dash.PUT("/billing/settings", s.billingUpdateSettings)
dash.GET("/billing/invoices", s.billingInvoices)
+ dash.POST("/billing/redeem", s.billingRedeem)
// Admin endpoints
dash.POST("/admin/backfill-workos-orgs", s.dashboardBackfillWorkOSOrgs)
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 81255781..d794e57e 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -792,6 +792,17 @@ func (s *Server) setLimits(c echo.Context) error {
}
}
+ // Free tier: block scaling beyond 4GB / 1 vCPU
+ if orgID, hasOrg := auth.GetOrgID(c); hasOrg && s.store != nil {
+ if org, err := s.store.GetOrg(ctx, orgID); err == nil && org.Plan == "free" {
+ if req.MemoryMB > 4096 || req.CPUPercent > 100 {
+ return c.JSON(http.StatusPaymentRequired, map[string]string{
+ "error": "upgrade to pro for larger instances",
+ })
+ }
+ }
+ }
+
// Convert to cgroup values
maxMemoryBytes := int64(req.MemoryMB) * 1024 * 1024
cpuMaxUsec := int64(req.CPUPercent) * 1000
@@ -837,6 +848,18 @@ func (s *Server) scaleSandbox(c echo.Context) error {
if err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
}
+
+ // Free tier: block scaling beyond 4GB / 1 vCPU
+ if orgID, hasOrg := auth.GetOrgID(c); hasOrg && s.store != nil {
+ if org, err := s.store.GetOrg(c.Request().Context(), orgID); err == nil && org.Plan == "free" {
+ if req.MemoryMB > 4096 {
+ return c.JSON(http.StatusPaymentRequired, map[string]string{
+ "error": "upgrade to pro for larger instances",
+ })
+ }
+ }
+ }
+
cpuPercent := vcpus * 100
maxMemoryBytes := int64(req.MemoryMB) * 1024 * 1024
cpuMaxUsec := int64(cpuPercent) * 1000
diff --git a/internal/billing/stripe.go b/internal/billing/stripe.go
index dd98736b..45714329 100644
--- a/internal/billing/stripe.go
+++ b/internal/billing/stripe.go
@@ -10,9 +10,11 @@ import (
"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/customerbalancetransaction"
"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/promotioncode"
"github.com/stripe/stripe-go/v82/subscription"
"github.com/stripe/stripe-go/v82/webhook"
)
@@ -291,6 +293,63 @@ func (s *StripeClient) GetUpcomingInvoice(customerID string) (*stripe.Invoice, e
})
}
+// RedeemPromotionCode validates a promotion code and applies the credit to the customer's balance.
+// Returns the credit amount in cents.
+func (s *StripeClient) RedeemPromotionCode(customerID, code string) (int64, error) {
+ // Look up the promotion code
+ iter := promotioncode.List(&stripe.PromotionCodeListParams{
+ Code: stripe.String(code),
+ Active: stripe.Bool(true),
+ })
+ if !iter.Next() {
+ return 0, fmt.Errorf("invalid or expired promotion code")
+ }
+ promo := iter.PromotionCode()
+
+ // Check redemption limits
+ if promo.MaxRedemptions > 0 && promo.TimesRedeemed >= promo.MaxRedemptions {
+ return 0, fmt.Errorf("promotion code has already been redeemed")
+ }
+
+ // Check if restricted to a specific customer
+ if promo.Customer != nil && promo.Customer.ID != customerID {
+ return 0, fmt.Errorf("promotion code is not valid for this account")
+ }
+
+ // Get credit amount from coupon
+ if promo.Coupon == nil || promo.Coupon.AmountOff == 0 {
+ return 0, fmt.Errorf("promotion code has no credit amount")
+ }
+ amountCents := promo.Coupon.AmountOff
+
+ // Deactivate first to prevent concurrent redemptions
+ _, err := promotioncode.Update(promo.ID, &stripe.PromotionCodeParams{
+ Active: stripe.Bool(false),
+ })
+ if err != nil {
+ return 0, fmt.Errorf("failed to redeem promotion code: %w", err)
+ }
+
+ // Apply credit to customer balance (negative = credit in Stripe)
+ _, err = customerbalancetransaction.New(&stripe.CustomerBalanceTransactionParams{
+ Customer: stripe.String(customerID),
+ Amount: stripe.Int64(-amountCents),
+ Currency: stripe.String("usd"),
+ Description: stripe.String(fmt.Sprintf("Promotion code: %s", code)),
+ })
+ if err != nil {
+ // Re-activate the code since credit application failed
+ if _, reErr := promotioncode.Update(promo.ID, &stripe.PromotionCodeParams{
+ Active: stripe.Bool(true),
+ }); reErr != nil {
+ log.Printf("billing: CRITICAL: promo code %s deactivated but credit failed — manual fix needed: %v", promo.ID, reErr)
+ }
+ return 0, fmt.Errorf("apply credit: %w", err)
+ }
+
+ return amountCents, nil
+}
+
// 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{
diff --git a/internal/db/migrations/018_drop_spend_cap.down.sql b/internal/db/migrations/018_drop_spend_cap.down.sql
new file mode 100644
index 00000000..f0850a78
--- /dev/null
+++ b/internal/db/migrations/018_drop_spend_cap.down.sql
@@ -0,0 +1 @@
+ALTER TABLE orgs ADD COLUMN monthly_spend_cap_cents INT;
diff --git a/internal/db/migrations/018_drop_spend_cap.up.sql b/internal/db/migrations/018_drop_spend_cap.up.sql
new file mode 100644
index 00000000..6c1a25c3
--- /dev/null
+++ b/internal/db/migrations/018_drop_spend_cap.up.sql
@@ -0,0 +1 @@
+ALTER TABLE orgs DROP COLUMN IF EXISTS monthly_spend_cap_cents;
diff --git a/internal/db/store.go b/internal/db/store.go
index bf4430b9..c86828ad 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -99,6 +99,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{17, "migrations/015_sandbox_usage.up.sql"},
{18, "migrations/015_secret_allowed_hosts.up.sql"},
{19, "migrations/017_stripe_billing.up.sql"},
+ {20, "migrations/018_drop_spend_cap.up.sql"},
}
for _, m := range migrations {
@@ -160,7 +161,6 @@ type Org struct {
// Stripe billing fields
StripeCustomerID *string `json:"stripeCustomerId,omitempty"`
StripeSubscriptionID *string `json:"stripeSubscriptionId,omitempty"`
- MonthlySpendCapCents *int `json:"monthlySpendCapCents,omitempty"`
LastUsageReportedAt time.Time `json:"lastUsageReportedAt"`
}
@@ -169,7 +169,7 @@ const orgColumns = `id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_
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,
- stripe_customer_id, stripe_subscription_id, monthly_spend_cap_cents, last_usage_reported_at`
+ stripe_customer_id, stripe_subscription_id, last_usage_reported_at`
// scanOrg scans a row into an Org struct.
func scanOrg(row pgx.Row) (*Org, error) {
@@ -180,7 +180,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,
+ &org.StripeCustomerID, &org.StripeSubscriptionID, &org.LastUsageReportedAt,
)
return org, err
}
diff --git a/internal/db/usage.go b/internal/db/usage.go
index c93ab80d..8504779e 100644
--- a/internal/db/usage.go
+++ b/internal/db/usage.go
@@ -152,14 +152,6 @@ func (s *Store) UpdateOrgPlan(ctx context.Context, orgID uuid.UUID, plan string)
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,
@@ -168,13 +160,15 @@ func (s *Store) UpdateLastUsageReportedAt(ctx context.Context, orgID uuid.UUID,
return err
}
-// ListBillableOrgIDs returns org IDs with plan="pro" and at least one open scale event.
+// ListBillableOrgIDs returns org IDs with plan="pro" that have unreported usage:
+// either a currently-running sandbox or a scale event that ended after the last report.
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'`)
+ WHERE o.plan = 'pro'
+ AND (se.ended_at IS NULL OR se.ended_at > o.last_usage_reported_at)`)
if err != nil {
return nil, err
}
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 9b6b5603..d1fd1917 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -283,7 +283,7 @@ export interface BillingTierUsage {
export interface BillingState {
plan: string
stripeCreditCents: number
- monthlySpendCapCents: number | null
+ maxConcurrentSandboxes: number
hasPaymentMethod: boolean
currentUsage: {
tiers: BillingTierUsage[]
@@ -309,11 +309,11 @@ 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}`)
+
+export const redeemPromoCode = (code: string) =>
+ apiFetch<{ creditAppliedCents: number }>('/billing/redeem', {
+ method: 'POST',
+ body: JSON.stringify({ code }),
+ })
diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsx
index 232982b7..e2c9b933 100644
--- a/web/src/pages/Billing.tsx
+++ b/web/src/pages/Billing.tsx
@@ -1,7 +1,7 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
- getBilling, billingSetup, updateBillingSettings, getBillingInvoices,
+ getBilling, billingSetup, getBillingInvoices, redeemPromoCode,
type BillingTierUsage, type StripeInvoice,
} from '../api/client'
@@ -18,22 +18,21 @@ export default function Billing() {
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 [promoCode, setPromoCode] = useState('')
+ const [redeemSuccess, setRedeemSuccess] = useState('')
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: () => {
+ const redeemMutation = useMutation({
+ mutationFn: () => redeemPromoCode(promoCode),
+ onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['billing'] })
- setSettingsSaved(true)
- setTimeout(() => setSettingsSaved(false), 2000)
+ setPromoCode('')
+ setRedeemSuccess(`$${(data.creditAppliedCents / 100).toFixed(2)} credit applied!`)
+ setTimeout(() => setRedeemSuccess(''), 4000)
},
})
@@ -67,11 +66,11 @@ export default function Billing() {
}}>
{isPro ? 'Pro' : 'Free'}
</span>
- {!isPro && (
- <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
- 1 sandbox, 4GB / 1 vCPU
- </span>
- )}
+ <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
+ {isPro
+ ? `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, all tiers`
+ : `${billing?.maxConcurrentSandboxes ?? 5} concurrent sandboxes, 4GB / 1 vCPU`}
+ </span>
</div>
{isPro && billing?.stripeCreditCents != null && billing.stripeCreditCents > 0 && (
@@ -82,6 +81,9 @@ export default function Billing() {
{!isPro && (
<div style={{ marginTop: 16 }}>
+ <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 10 }}>
+ Unlock larger machine sizes and get $30 free credit
+ </div>
<button
onClick={() => setupMutation.mutate()}
disabled={setupMutation.isPending}
@@ -93,7 +95,7 @@ export default function Billing() {
opacity: setupMutation.isPending ? 0.6 : 1,
}}
>
- {setupMutation.isPending ? 'Redirecting...' : 'Upgrade to Pro — $30 free credit'}
+ {setupMutation.isPending ? 'Redirecting...' : 'Upgrade to Pro'}
</button>
{setupMutation.isError && (
<p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 8 }}>
@@ -112,6 +114,14 @@ export default function Billing() {
Payment method on file — billed monthly via Stripe
</div>
)}
+
+ <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 12 }}>
+ Need more concurrency?{' '}
+ <a href="https://cal.com/team/digger/opencomputer-founder-chat" target="_blank" rel="noreferrer"
+ style={{ color: 'var(--accent-indigo)', textDecoration: 'none' }}>
+ Talk to us
+ </a>
+ </div>
</div>
{/* Current Usage */}
@@ -178,56 +188,64 @@ export default function Billing() {
<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>
- ))}
+ {PRICING_TIERS.map((t, i) => {
+ const locked = !isPro && i > 0
+ return (
+ <tr key={t.memory} style={{ opacity: locked ? 0.35 : 1 }}>
+ <td style={{ fontWeight: 600, color: 'var(--text-primary)' }}>
+ {t.memory}{locked && ' — Pro'}
+ </td>
+ <td>{t.vcpus}</td>
+ <td style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: locked ? 'var(--text-tertiary)' : 'var(--accent-cyan)' }}>
+ ${t.perSec.toFixed(11)}
+ </td>
+ </tr>
+ )
+ })}
</tbody>
</table>
</div>
- {/* Monthly Spend Cap (pro only) */}
+ {/* Redeem Promotion Code (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>
+ <span className="section-title" style={{ marginBottom: 12, display: 'block' }}>Promotion Code</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)
+ Enter a promotion code to apply credit
</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>
+ <input
+ className="input"
+ type="text"
+ placeholder="e.g. WELCOME100"
+ value={promoCode}
+ onChange={e => setPromoCode(e.target.value.toUpperCase())}
+ style={{ width: 240, fontFamily: 'var(--font-mono)', fontSize: 13 }}
+ />
</div>
<button
- onClick={() => settingsMutation.mutate()}
- disabled={settingsMutation.isPending}
+ onClick={() => redeemMutation.mutate()}
+ disabled={redeemMutation.isPending || !promoCode.trim()}
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',
+ opacity: redeemMutation.isPending || !promoCode.trim() ? 0.5 : 1,
}}
>
- Save
+ {redeemMutation.isPending ? 'Applying...' : 'Redeem'}
</button>
- {settingsSaved && <span style={{ fontSize: 12, color: 'var(--accent-emerald)' }}>Saved</span>}
</div>
+ {redeemSuccess && (
+ <p style={{ fontSize: 13, color: 'var(--accent-emerald)', marginTop: 10 }}>{redeemSuccess}</p>
+ )}
+ {redeemMutation.isError && (
+ <p style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>
+ {(redeemMutation.error as Error).message}
+ </p>
+ )}
</div>
)}