Skip to content

An open-source, faster Devin alternative

TypeScript

edge stripe provisioning

Brian Reardonc3d52cf49168
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 13c1f725..0aafc639 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1252,6 +1252,21 @@ async function stripeWebhook(req: Request, env: Env): Promise<Response> {
console.error(`stripe: ${event.type} without org_id metadata; logging and skipping`);
return json({ received: true, skipped: "no org_id" });
}
+ // A completed setup-checkout IS the upgrade: provision the Stripe
+ // subscription (every metered price from the D1 catalog + $30 credit)
+ // BEFORE marking pro, so an org is never pro-but-unprovisioned. ONLY on
+ // the setup checkout — never on customer.subscription.created, which our
+ // own provisioning fires (that would loop). Idempotent, so Stripe webhook
+ // retries can't create a second subscription.
+ if (event.type === "checkout.session.completed" && obj.metadata?.type === "setup" && obj.customer) {
+ try {
+ await provisionProSubscription(env, orgID, obj.customer);
+ } catch (e) {
+ console.error(`stripe: provision subscription for ${orgID} failed`, e);
+ return json({ error: "provisioning failed" }, 500); // 5xx → Stripe retries
+ }
+ }
+
const stub = env.CREDIT_ACCOUNT.get(env.CREDIT_ACCOUNT.idFromName(orgID));
const resp = await stub.fetch(`https://do/mark-pro?org_id=${encodeURIComponent(orgID)}`, { method: "POST" });
if (resp.status >= 400) {
@@ -1289,6 +1304,95 @@ async function stripeWebhook(req: Request, env: Env): Promise<Response> {
}
}
+// provisionProSubscription creates the org's Stripe subscription with every
+// metered price from the D1 catalog (billing_prices, written once by
+// cmd/ensure-products), applies the $30 promo credit, and persists the
+// subscription + item IDs to D1. This is the edge replacement for the cell's
+// CreateSubscription — necessary because the public Stripe webhook must
+// terminate on the edge, not the (private) cell. Idempotent: a no-op if the
+// org already has a subscription, and the Stripe-side Idempotency-Key keeps a
+// retry/concurrent delivery from ever creating two.
+async function provisionProSubscription(env: Env, orgID: string, customerID: string): Promise<void> {
+ const existing = await env.OPENCOMPUTER_DB.prepare(
+ "SELECT stripe_subscription_id FROM orgs WHERE id = ?1",
+ )
+ .bind(orgID)
+ .first<{ stripe_subscription_id: string | null }>();
+ if (existing?.stripe_subscription_id) {
+ return; // already provisioned — retry no-op
+ }
+
+ // Global price catalog. Empty = cmd/ensure-products hasn't run; refuse rather
+ // than create a subscription with no metered items (silent under-bill).
+ const cat = await env.OPENCOMPUTER_DB.prepare("SELECT key, price_id FROM billing_prices").all<{
+ key: string;
+ price_id: string;
+ }>();
+ const catalog = cat.results ?? [];
+ if (catalog.length === 0) {
+ throw new Error("billing_prices catalog empty — run cmd/ensure-products before provisioning");
+ }
+
+ // Subscription with every catalog price as a line item (mirrors the cell's
+ // CreateSubscription: per-tier + overage + reserved + disk). Idempotency-Key
+ // is org-scoped so a duplicate delivery can't create a second subscription.
+ const subForm = new URLSearchParams();
+ subForm.set("customer", customerID);
+ catalog.forEach((r, i) => subForm.set(`items[${i}][price]`, r.price_id));
+ const sub = await stripePost(env, "/v1/subscriptions", subForm, `sub-create-${orgID}`);
+
+ // $30 promotional credit (negative customer balance), same as the cell.
+ await stripePost(env, `/v1/customers/${encodeURIComponent(customerID)}`, new URLSearchParams({ balance: "-3000" }));
+
+ const now = Math.floor(Date.now() / 1000);
+ await env.OPENCOMPUTER_DB.prepare(
+ "UPDATE orgs SET stripe_subscription_id = ?1, updated_at = ?2 WHERE id = ?3",
+ )
+ .bind(sub.id, now, orgID)
+ .run();
+
+ // Persist item IDs, mapping each back to its catalog key.
+ const keyByPrice = new Map(catalog.map((r) => [r.price_id, r.key]));
+ const itemStmt = env.OPENCOMPUTER_DB.prepare(
+ `INSERT INTO org_subscription_items (org_id, tier, stripe_item_id, price_id)
+ VALUES (?1, ?2, ?3, ?4)
+ ON CONFLICT(org_id, tier) DO UPDATE SET stripe_item_id = excluded.stripe_item_id, price_id = excluded.price_id`,
+ );
+ const items = (sub.items?.data ?? []) as Array<{ id: string; price?: { id: string } }>;
+ const batch: D1PreparedStatement[] = [];
+ for (const it of items) {
+ const priceID = it.price?.id ?? "";
+ const key = keyByPrice.get(priceID);
+ if (key) batch.push(itemStmt.bind(orgID, key, it.id, priceID));
+ }
+ if (batch.length > 0) await env.OPENCOMPUTER_DB.batch(batch);
+
+ console.log(`stripe: provisioned subscription ${sub.id} for org ${orgID} (${batch.length} items, $30 credit)`);
+}
+
+// stripePost POSTs form-urlencoded to the Stripe API and returns parsed JSON,
+// throwing on non-2xx. An optional Idempotency-Key makes a call safe to retry.
+async function stripePost(env: Env, path: string, form: URLSearchParams, idempotencyKey?: string): Promise<any> {
+ const headers: Record<string, string> = {
+ authorization: "Bearer " + env.STRIPE_API_KEY,
+ "stripe-version": "2024-06-20",
+ "content-type": "application/x-www-form-urlencoded",
+ };
+ if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
+ const resp = await fetch(`https://api.stripe.com${path}`, { method: "POST", headers, body: form.toString() });
+ const text = await resp.text();
+ let parsed: any;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ parsed = { raw: text };
+ }
+ if (!resp.ok) {
+ throw new Error(parsed?.error?.message ?? parsed?.raw ?? `stripe ${path} returned ${resp.status}`);
+ }
+ return parsed;
+}
+
// verifyStripeSignature checks the t=… v1=… Stripe-Signature header.
// Stripe signs `${timestamp}.${body}` with HMAC-SHA256.
async function verifyStripeSignature(secret: string, header: string, body: string): Promise<boolean> {
diff --git a/cloudflare-workers/schema.sql b/cloudflare-workers/schema.sql
index 52a4914e..20f11441 100644
--- a/cloudflare-workers/schema.sql
+++ b/cloudflare-workers/schema.sql
@@ -235,6 +235,19 @@ CREATE TABLE IF NOT EXISTS usage_meter_events (
CREATE INDEX IF NOT EXISTS idx_meter_events_pending ON usage_meter_events(state, bucket_start) WHERE state = 'pending';
CREATE INDEX IF NOT EXISTS idx_meter_events_org_bucket ON usage_meter_events(org_id, bucket_start);
+-- Stripe price catalog — the resolved metered Price IDs the edge attaches when
+-- it provisions a pro subscription. The catalog is GLOBAL (one Stripe account,
+-- same prices for every cell), so it's written by a single deploy-time step
+-- (cmd/ensure-products), NOT by per-cell publishing — 40 cells must not each
+-- race to write it. The edge reads every row and attaches each price_id as a
+-- subscription item (mirrors the CP's CreateSubscription).
+-- key: "tier_1024".."tier_65536" | "overage" | "reserved" | "disk_overage"
+CREATE TABLE IF NOT EXISTS billing_prices (
+ key TEXT PRIMARY KEY,
+ price_id TEXT NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+
CREATE TABLE IF NOT EXISTS org_subscription_items (
org_id TEXT NOT NULL,
tier TEXT NOT NULL, -- e.g. "memory" | "cpu"
diff --git a/cmd/ensure-products/main.go b/cmd/ensure-products/main.go
new file mode 100644
index 00000000..3a66bc33
--- /dev/null
+++ b/cmd/ensure-products/main.go
@@ -0,0 +1,85 @@
+// Command ensure-products is the single, global step that establishes the
+// Stripe price catalog and publishes the resolved price IDs to D1 for the edge.
+//
+// The catalog is a GLOBAL concern — one Stripe account, the same metered Prices
+// for every cell — so it must be established once, not by all 40 cells racing
+// on every startup. This runs EnsureProducts (idempotent: creates/verifies the
+// Stripe meters + Prices) and emits `billing_prices` upsert SQL on stdout. Pipe
+// it into the appropriate D1:
+//
+// STRIPE_SECRET_KEY=sk_live_... go run ./cmd/ensure-products > /tmp/catalog.sql
+// wrangler d1 execute opencomputer-prod --remote --file /tmp/catalog.sql
+//
+// Run it once per deploy / pricing change (i.e. whenever a TierPriceKey is
+// bumped in internal/billing/pricing.go) — not on cell startup.
+package main
+
+import (
+ "fmt"
+ "os"
+ "sort"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/billing"
+ "github.com/opensandbox/opensandbox/internal/config"
+)
+
+func main() {
+ // Load STRIPE_SECRET_KEY from the cloud vault when a trigger is set
+ // (SECRETS_VAULT_NAME → Azure Key Vault, OPENSANDBOX_SECRETS_ARN → AWS),
+ // exactly as cmd/server does — so this runs anywhere a CP can. No-op if
+ // neither trigger is set (then STRIPE_SECRET_KEY must be in the env).
+ _ = config.LoadSecretsFromKeyVault()
+ _ = config.LoadSecretsFromSecretsManager()
+
+ secret := os.Getenv("STRIPE_SECRET_KEY")
+ if secret == "" {
+ fmt.Fprintln(os.Stderr, "ensure-products: STRIPE_SECRET_KEY not set (env or vault)")
+ os.Exit(1)
+ }
+
+ sc := billing.NewStripeClient(secret, "", "", "")
+ if err := sc.EnsureProducts(); err != nil {
+ fmt.Fprintf(os.Stderr, "ensure-products: EnsureProducts failed: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Resolved catalog → (key, price_id). Mirrors exactly the line items
+ // CreateSubscription attaches: every per-tier compute price plus the flat
+ // overage / reserved / disk-overage prices.
+ type row struct{ key, priceID string }
+ var rows []row
+ tiers := make([]int, 0, len(sc.PriceIDs))
+ for mb := range sc.PriceIDs {
+ tiers = append(tiers, mb)
+ }
+ sort.Ints(tiers)
+ for _, mb := range tiers {
+ rows = append(rows, row{fmt.Sprintf("tier_%d", mb), sc.PriceIDs[mb]})
+ }
+ if sc.OveragePriceID != "" {
+ rows = append(rows, row{"overage", sc.OveragePriceID})
+ }
+ if sc.ReservedPriceID != "" {
+ rows = append(rows, row{"reserved", sc.ReservedPriceID})
+ }
+ if sc.DiskOveragePriceID != "" {
+ rows = append(rows, row{"disk_overage", sc.DiskOveragePriceID})
+ }
+ if len(rows) == 0 {
+ fmt.Fprintln(os.Stderr, "ensure-products: no prices resolved — refusing to emit empty catalog")
+ os.Exit(1)
+ }
+
+ ts := time.Now().Unix()
+ fmt.Println("-- Stripe price catalog for the edge — generated by cmd/ensure-products.")
+ fmt.Println("-- Idempotent: re-running upserts the current price IDs.")
+ for _, r := range rows {
+ fmt.Printf(
+ "INSERT INTO billing_prices (key, price_id, updated_at) VALUES ('%s','%s',%d) "+
+ "ON CONFLICT(key) DO UPDATE SET price_id=excluded.price_id, updated_at=excluded.updated_at;\n",
+ r.key, r.priceID, ts,
+ )
+ }
+ fmt.Fprintf(os.Stderr, "ensure-products: emitted %d price rows\n", len(rows))
+}