From 6a42613d910b1f250dce6ea918e0323c7e8b8748 Mon Sep 17 00:00:00 2001 From: divyanshujethi Date: Tue, 24 Nov 2026 22:54:48 +0530 Subject: [PATCH] feat(billing): implement Remote Cloud Cache tiers, quota paywall, and Dodo Payments integration --- README.md | 36 ++++- src/billing/types.ts | 68 ++++++++++ src/metadata/store.ts | 65 +++++++++ src/metadata/types.ts | 12 +- src/routes/artifacts.ts | 47 +++++++ src/routes/billing.ts | 285 ++++++++++++++++++++++++++++++++++++++++ src/server.ts | 2 + tests/billing.test.ts | 198 ++++++++++++++++++++++++++++ 8 files changed, 711 insertions(+), 2 deletions(-) create mode 100644 src/billing/types.ts create mode 100644 src/routes/billing.ts create mode 100644 tests/billing.test.ts diff --git a/README.md b/README.md index 5ebd811..a6bb796 100644 --- a/README.md +++ b/README.md @@ -292,13 +292,47 @@ Response: | `DEFAULT_ADMIN_TOKEN` | *(auto)* | Master cluster administrator token | | `MAX_ARTIFACT_SIZE_BYTES`| `2147483648` (2GB) | Maximum single artifact size | | `COMPUTE_COST_PER_HOUR_USD`| `0.08` | Runner cost per hour for ROI calculation | +| `DODO_WEBHOOK_SECRET` | *(none)* | Webhook secret for automated subscription fulfillment | + +--- + +## ๐Ÿ’Ž Remote Cache Storage Tiers & Commercial Billing + +`poly-cloud-api` provides a turnkey remote caching service with self-serve subscription billing powered by **Dodo Payments**: + +| Tier | Price | Cache Quota | Retention | Max Artifact | Ideal For | +| :--- | :--- | :--- | :--- | :--- | :--- | +| **Developer Free** | **$0** / mo | **1 GB** | 7 Days | 100 MB | Individual open-source developers | +| **Pro Team** | **$29** / mo | **50 GB** | 30 Days | 500 MB | High-velocity engineering teams & CI/CD | +| **Enterprise Cloud** | **$199** / mo | **500 GB** | 90 Days | 2 GB | Large monorepos with multi-runner matrix pipelines | + +### ๐Ÿš€ Automatic Paywall & Quota Enforcement +When a workspace on the Free tier exhausts its storage quota, `PUT /v8/artifacts/:hash` returns `HTTP 402 Payment Required` along with an `X-Poly-Upgrade-Url` header: + +```json +{ + "error": "Payment Required", + "code": "QUOTA_EXCEEDED", + "message": "Storage quota of 1.00 GB exceeded for workspace 'acme-corp' on free tier. Upgrade to Pro (50 GB) to continue caching.", + "tier": "free", + "currentUsageBytes": 1094000000, + "quotaBytes": 1073741824, + "upgradeUrl": "https://checkout.dodopayments.com/buy/pdt_0NpjONNytUpW7gzjoDlYW?quantity=1&metadata.workspace=acme-corp&metadata.tier=pro" +} +``` + +### ๐Ÿ’ณ Billing & Webhook API Endpoints +- `GET /api/v1/billing/tiers`: Returns all tier specifications, limits, and pricing. +- `POST /api/v1/billing/checkout`: Generates a Dodo Payments checkout session for workspace upgrades (`{ workspaceSlug, tier }`). +- `POST /api/v1/billing/webhooks/dodo`: Listens for `payment.succeeded`, `subscription.active`, and `subscription.cancelled` events with HMAC-SHA256 signature verification to update workspace tier and quota in real time. +- `GET /api/v1/workspaces/:slug/billing`: Inspects current workspace tier, quota, usage percentage, and subscription renewal status. --- ## ๐Ÿงช Testing & Verification ```bash -# Run unit & integration test suite (94 tests) +# Run unit & integration test suite (101 tests) npm test # Run Biome formatting & linter verification diff --git a/src/billing/types.ts b/src/billing/types.ts new file mode 100644 index 0000000..c0415fb --- /dev/null +++ b/src/billing/types.ts @@ -0,0 +1,68 @@ +import type { WorkspaceTier } from "../metadata/types.js"; + +export interface TierConfig { + tier: WorkspaceTier; + name: string; + priceMonthlyUsd: number; + quotaBytes: number; + quotaLabel: string; + maxArtifactSizeBytes: number; + defaultTtlSeconds: number; + dodoProductId?: string; + checkoutUrl?: string; + features: string[]; +} + +export const TIER_CONFIGS: Record = { + free: { + tier: "free", + name: "Developer Free Tier", + priceMonthlyUsd: 0, + quotaBytes: 1 * 1024 * 1024 * 1024, // 1 GB + quotaLabel: "1 GB", + maxArtifactSizeBytes: 100 * 1024 * 1024, // 100 MB + defaultTtlSeconds: 7 * 86400, // 7 days + features: [ + "1 GB remote build cache storage", + "Turborepo & Poly CLI protocol support", + "7-day cache retention", + "Community GitHub support" + ] + }, + pro: { + tier: "pro", + name: "Pro Team Cloud Cache", + priceMonthlyUsd: 29, + quotaBytes: 50 * 1024 * 1024 * 1024, // 50 GB + quotaLabel: "50 GB", + maxArtifactSizeBytes: 500 * 1024 * 1024, // 500 MB + defaultTtlSeconds: 30 * 86400, // 30 days + dodoProductId: "pdt_0NpjONNytUpW7gzjoDlYW", + checkoutUrl: "https://checkout.dodopayments.com/buy/pdt_0NpjONNytUpW7gzjoDlYW", + features: [ + "50 GB high-speed global remote cache", + "30-day cache retention with deduplication", + "GitHub Actions OIDC zero-secret authentication", + "Sub-15ms cache hits via Cloudflare R2 / S3", + "Priority developer support" + ] + }, + enterprise: { + tier: "enterprise", + name: "Enterprise Dedicated Cloud", + priceMonthlyUsd: 199, + quotaBytes: 500 * 1024 * 1024 * 1024, // 500 GB + quotaLabel: "500 GB", + maxArtifactSizeBytes: 2 * 1024 * 1024 * 1024, // 2 GB + defaultTtlSeconds: 90 * 86400, // 90 days + dodoProductId: "pdt_0NrFSmrXT8zU2u5BKGJ7y", + checkoutUrl: "https://checkout.dodopayments.com/buy/pdt_0NrFSmrXT8zU2u5BKGJ7y", + features: [ + "500 GB dedicated enterprise cache", + "90-day retention with LRU watermark auto-eviction", + "Cryptographic SLSA Provenance & Ed25519 in-toto verification", + "Role-Based Team Tokens & SSO Integration", + "99.99% uptime SLA" + ] + } +}; diff --git a/src/metadata/store.ts b/src/metadata/store.ts index 5ffeca6..ab2b824 100644 --- a/src/metadata/store.ts +++ b/src/metadata/store.ts @@ -10,6 +10,7 @@ import type { TokenRole, Workspace, WorkspaceStats, + WorkspaceTier, } from "./types.js"; function hashToken(rawToken: string): string { @@ -45,6 +46,7 @@ export class MemoryMetadataStore implements MetadataStore { slug: string, name?: string, quotaBytes = 107374182400, + tier: WorkspaceTier = "free", ): Promise { const existing = await this.getWorkspaceBySlug(slug); if (existing) return existing; @@ -55,6 +57,7 @@ export class MemoryMetadataStore implements MetadataStore { slug, name: name || slug, quotaBytes, // Default 100GB + tier, defaultTtlSeconds: 604800, // 7 days createdAt: new Date().toISOString(), }; @@ -63,6 +66,20 @@ export class MemoryMetadataStore implements MetadataStore { return ws; } + async updateWorkspace( + id: string, + updates: Partial> + ): Promise { + const ws = this.workspaces.get(id); + if (!ws) return null; + const updated: Workspace = { ...ws, ...updates }; + this.workspaces.set(id, updated); + if (updated.slug) { + this.workspacesBySlug.set(updated.slug, id); + } + return updated; + } + async listWorkspaces(): Promise { return Array.from(this.workspaces.values()); } @@ -486,6 +503,18 @@ export class SqliteMetadataStore extends MemoryMetadataStore { try { db.exec("ALTER TABLE artifacts ADD COLUMN sha256 TEXT;"); } catch {} + try { + db.exec("ALTER TABLE workspaces ADD COLUMN tier TEXT;"); + } catch {} + try { + db.exec("ALTER TABLE workspaces ADD COLUMN subscription_id TEXT;"); + } catch {} + try { + db.exec("ALTER TABLE workspaces ADD COLUMN subscription_status TEXT;"); + } catch {} + try { + db.exec("ALTER TABLE workspaces ADD COLUMN subscription_expires_at TEXT;"); + } catch {} try { db.exec("ALTER TABLE artifacts ADD COLUMN is_attested INTEGER;"); } catch {} @@ -529,6 +558,10 @@ export class SqliteMetadataStore extends MemoryMetadataStore { slug: r.slug, name: r.name, quotaBytes: r.quota_bytes, + tier: (r as any).tier || "free", + subscriptionId: (r as any).subscription_id, + subscriptionStatus: (r as any).subscription_status, + subscriptionExpiresAt: (r as any).subscription_expires_at, defaultTtlSeconds: r.default_ttl_seconds, createdAt: r.created_at, }; @@ -564,6 +597,38 @@ export class SqliteMetadataStore extends MemoryMetadataStore { } } + override async updateWorkspace( + id: string, + updates: Partial> + ): Promise { + const updated = await super.updateWorkspace(id, updates); + if (!updated || !this.db) return updated; + try { + const db = this.db as any; + db.prepare(` + UPDATE workspaces SET + name = COALESCE(?, name), + quota_bytes = COALESCE(?, quota_bytes), + tier = COALESCE(?, tier), + subscription_id = COALESCE(?, subscription_id), + subscription_status = COALESCE(?, subscription_status), + subscription_expires_at = COALESCE(?, subscription_expires_at), + default_ttl_seconds = COALESCE(?, default_ttl_seconds) + WHERE id = ? + `).run( + updates.name ?? null, + updates.quotaBytes ?? null, + updates.tier ?? null, + updates.subscriptionId ?? null, + updates.subscriptionStatus ?? null, + updates.subscriptionExpiresAt ?? null, + updates.defaultTtlSeconds ?? null, + id + ); + } catch {} + return updated; + } + override async close(): Promise { if (this.db && typeof (this.db as { close?: () => void }).close === "function") { (this.db as { close: () => void }).close(); diff --git a/src/metadata/types.ts b/src/metadata/types.ts index 4550a4d..0075b0f 100644 --- a/src/metadata/types.ts +++ b/src/metadata/types.ts @@ -1,10 +1,16 @@ import type { DsseEnvelope, InTotoStatement } from "../attestation/types.js"; +export type WorkspaceTier = "free" | "pro" | "enterprise"; + export interface Workspace { id: string; slug: string; name: string; quotaBytes: number; + tier?: WorkspaceTier; + subscriptionId?: string; + subscriptionStatus?: string; + subscriptionExpiresAt?: string; defaultTtlSeconds: number; createdAt: string; } @@ -76,7 +82,11 @@ export interface MetadataStore { // Workspaces getWorkspaceBySlug(slug: string): Promise; getWorkspaceById(id: string): Promise; - ensureWorkspace(slug: string, name?: string, quotaBytes?: number): Promise; + ensureWorkspace(slug: string, name?: string, quotaBytes?: number, tier?: WorkspaceTier): Promise; + updateWorkspace( + id: string, + updates: Partial> + ): Promise; listWorkspaces(): Promise; // Tokens diff --git a/src/routes/artifacts.ts b/src/routes/artifacts.ts index 2eef13b..9bb897b 100644 --- a/src/routes/artifacts.ts +++ b/src/routes/artifacts.ts @@ -2,6 +2,7 @@ import crypto from "node:crypto"; import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import type { CorporateAttestationPolicy, DsseEnvelope } from "../attestation/types.js"; import { AttestationVerifier } from "../attestation/verifier.js"; +import { TIER_CONFIGS } from "../billing/types.js"; import type { PolyCloudConfig } from "../config.js"; import type { MetadataStore } from "../metadata/types.js"; import { createAuthHook } from "../middleware/auth.js"; @@ -194,6 +195,28 @@ export async function registerArtifactRoutes( }); } + // Quota and tier enforcement check + if (workspace.quotaBytes > 0) { + const stats = await store.getWorkspaceStats(workspace.slug); + const incoming = sizeBytes || 0; + if (stats.totalSizeBytes + incoming > workspace.quotaBytes) { + const tier = workspace.tier || "free"; + const proConfig = TIER_CONFIGS.pro; + const upgradeUrl = `${proConfig.checkoutUrl}?quantity=1&metadata.workspace=${encodeURIComponent( + workspace.slug, + )}&metadata.tier=pro`; + + reply.header("X-Poly-Upgrade-Url", upgradeUrl); + return reply.code(402).send({ + error: "Payment Required", + code: "QUOTA_EXCEEDED", + message: `Storage quota exceeded for workspace '${workspace.slug}' on ${tier} tier. Upgrade to Pro to continue caching.`, + tier, + upgradeUrl, + }); + } + } + const uploadUrl = await storage.getPresignedPutUrl(storageKey, { expiresInSeconds: config.presignedExpirySeconds, sizeBytes, @@ -394,6 +417,30 @@ export async function registerArtifactRoutes( }); } + // Quota and tier enforcement check + if (workspace.quotaBytes > 0) { + const stats = await store.getWorkspaceStats(workspace.slug); + const incoming = contentLength || 0; + if (stats.totalSizeBytes + incoming > workspace.quotaBytes) { + const tier = workspace.tier || "free"; + const proConfig = TIER_CONFIGS.pro; + const upgradeUrl = `${proConfig.checkoutUrl}?quantity=1&metadata.workspace=${encodeURIComponent( + workspace.slug, + )}&metadata.tier=pro`; + + reply.header("X-Poly-Upgrade-Url", upgradeUrl); + return reply.code(402).send({ + error: "Payment Required", + code: "QUOTA_EXCEEDED", + message: `Storage quota of ${(workspace.quotaBytes / (1024 * 1024 * 1024)).toFixed(2)} GB exceeded for workspace '${workspace.slug}' on ${tier} tier. Upgrade to Pro (50 GB) to continue caching.`, + tier, + currentUsageBytes: stats.totalSizeBytes, + quotaBytes: workspace.quotaBytes, + upgradeUrl, + }); + } + } + const putResult = await storage.put(storageKey, bodyData, contentLength); const payloadSha256 = putResult.sha256 || ""; diff --git a/src/routes/billing.ts b/src/routes/billing.ts new file mode 100644 index 0000000..c7ecd0e --- /dev/null +++ b/src/routes/billing.ts @@ -0,0 +1,285 @@ +import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; +import * as crypto from "node:crypto"; +import type { PolyCloudConfig } from "../config.js"; +import type { MetadataStore, WorkspaceTier } from "../metadata/types.js"; +import { TIER_CONFIGS } from "../billing/types.js"; + +export interface BillingRouteOptions { + store: MetadataStore; + config: PolyCloudConfig; + dodoWebhookSecret?: string; +} + +export async function registerBillingRoutes( + app: FastifyInstance, + options: BillingRouteOptions, +): Promise { + const { store, config } = options; + const webhookSecret = options.dodoWebhookSecret || process.env.DODO_WEBHOOK_SECRET; + const processedWebhookEvents = new Set(); + + // 1. GET /api/v1/billing/tiers - Public listing of cache storage tiers & pricing + app.get("/api/v1/billing/tiers", async (_request, reply) => { + return reply.code(200).send({ + success: true, + service: "Poly Remote Cloud Cache Tiering", + tiers: TIER_CONFIGS, + }); + }); + + // 2. POST /api/v1/billing/checkout - Generate Dodo Payments checkout session for workspace upgrade + app.post<{ + Body: { + workspaceSlug: string; + tier: "pro" | "enterprise"; + email?: string; + returnUrl?: string; + }; + }>("/api/v1/billing/checkout", async (request, reply) => { + const { workspaceSlug, tier, email, returnUrl } = request.body || {}; + + if (!workspaceSlug) { + return reply.code(400).send({ + error: "Bad Request", + message: "workspaceSlug is required to initiate an upgrade checkout", + }); + } + + if (!tier || !["pro", "enterprise"].includes(tier)) { + return reply.code(400).send({ + error: "Bad Request", + message: "tier must be either 'pro' or 'enterprise'", + }); + } + + const ws = await store.getWorkspaceBySlug(workspaceSlug); + if (!ws) { + return reply.code(404).send({ + error: "Not Found", + message: `Workspace '${workspaceSlug}' not found`, + }); + } + + const tierConfig = TIER_CONFIGS[tier]; + const callback = returnUrl || "https://poly.ritualdev.in/dashboard?upgrade=success"; + const checkoutUrl = `${tierConfig.checkoutUrl}?quantity=1&metadata.workspace=${encodeURIComponent( + workspaceSlug, + )}&metadata.tier=${tier}${email ? `&email=${encodeURIComponent(email)}` : ""}&return_url=${encodeURIComponent( + callback, + )}`; + + return reply.code(200).send({ + success: true, + workspaceSlug, + tier, + productId: tierConfig.dodoProductId, + priceMonthlyUsd: tierConfig.priceMonthlyUsd, + quotaBytes: tierConfig.quotaBytes, + quotaLabel: tierConfig.quotaLabel, + checkoutUrl, + }); + }); + + // 3. GET /api/v1/workspaces/:slug/billing - Detailed workspace billing status & usage + app.get<{ Params: { slug: string } }>( + "/api/v1/workspaces/:slug/billing", + async (request, reply) => { + const slug = request.params.slug; + const ws = await store.getWorkspaceBySlug(slug); + + if (!ws) { + return reply.code(404).send({ + error: "Not Found", + message: `Workspace '${slug}' not found`, + }); + } + + const stats = await store.getWorkspaceStats(slug); + const tier: WorkspaceTier = ws.tier || "free"; + const currentTierConfig = TIER_CONFIGS[tier]; + + return reply.code(200).send({ + workspaceSlug: ws.slug, + name: ws.name, + tier, + tierName: currentTierConfig.name, + priceMonthlyUsd: currentTierConfig.priceMonthlyUsd, + quotaBytes: ws.quotaBytes, + quotaLabel: currentTierConfig.quotaLabel, + usedBytes: stats.totalSizeBytes, + usedPercent: stats.quotaUsedPercent, + subscriptionId: ws.subscriptionId, + subscriptionStatus: ws.subscriptionStatus || "none", + subscriptionExpiresAt: ws.subscriptionExpiresAt, + upgradeAvailable: tier === "free" ? ["pro", "enterprise"] : tier === "pro" ? ["enterprise"] : [], + }); + }, + ); + + // 4. POST /api/v1/billing/webhooks/dodo - Dodo Payments subscription webhook processor + app.post("/api/v1/billing/webhooks/dodo", async (request, reply) => { + const webhookSecret = options.dodoWebhookSecret || process.env.DODO_WEBHOOK_SECRET; + + // Cryptographic signature check (Fail-closed) + const sigHeader = + (request.headers["webhook-signature"] as string) || + (request.headers["x-dodo-signature"] as string) || + (request.headers["signature"] as string); + + if (!webhookSecret) { + return reply.code(500).send({ + error: "Configuration Error", + message: "DODO_WEBHOOK_SECRET is not configured on server", + }); + } + + if (!sigHeader) { + return reply.code(401).send({ + error: "Unauthorized", + message: "Missing webhook signature header", + }); + } + + // Raw body validation + const rawBody = + typeof request.body === "string" + ? request.body + : Buffer.isBuffer(request.body) + ? request.body.toString("utf-8") + : JSON.stringify(request.body); + + const sigParts = sigHeader.includes("v1=") ? sigHeader.split(",") : [sigHeader]; + let signatureToCompare = sigHeader.replace(/^sha256=/, "").trim(); + for (const part of sigParts) { + const [k, v] = part.trim().split("="); + if (k === "v1") signatureToCompare = v; + } + + try { + const computedHex = crypto.createHmac("sha256", webhookSecret).update(rawBody).digest("hex"); + const sigBuf = Buffer.from(signatureToCompare, "hex"); + const compBuf = Buffer.from(computedHex, "hex"); + + if (sigBuf.length !== compBuf.length || !crypto.timingSafeEqual(sigBuf, compBuf)) { + return reply.code(401).send({ + error: "Unauthorized", + message: "Invalid Dodo Payments signature", + }); + } + } catch (err: any) { + return reply.code(401).send({ + error: "Unauthorized", + message: `Signature verification failed: ${err.message}`, + }); + } + + const payload = (typeof request.body === "object" ? request.body : JSON.parse(rawBody)) as any; + const eventType = payload.type || payload.event_type; + const data = payload.data || {}; + + // Replay attack defense + const eventId = + payload.id || + payload.event_id || + (data.payment_id ? `${eventType}_${data.payment_id}` : undefined) || + (data.subscription_id ? `${eventType}_${data.subscription_id}` : undefined); + if (eventId) { + if (processedWebhookEvents.has(eventId)) { + return reply.code(409).send({ + error: "Conflict", + message: `Duplicate webhook event detected: ${eventId} (replay rejected)`, + }); + } + processedWebhookEvents.add(eventId); + } + + // Extract workspace identifier + const meta = data.metadata || {}; + const customerMeta = data.customer?.metadata || {}; + const workspaceSlug = + meta.workspace || + meta.workspaceSlug || + meta.workspace_slug || + customerMeta.workspace || + customerMeta.workspaceSlug; + + if (!workspaceSlug) { + return reply.code(422).send({ + error: "Unprocessable Entity", + message: "Missing required 'workspace' in checkout metadata", + }); + } + + const ws = await store.getWorkspaceBySlug(workspaceSlug); + if (!ws) { + return reply.code(404).send({ + error: "Not Found", + message: `Target workspace '${workspaceSlug}' does not exist`, + }); + } + + // Handle fulfillment: upgrade workspace on payment.succeeded / subscription.active + if ( + eventType === "payment.succeeded" || + eventType === "subscription.active" || + eventType === "subscription.renewed" + ) { + const rawTier = (meta.tier || "pro").toLowerCase(); + const targetTier: WorkspaceTier = ["pro", "enterprise"].includes(rawTier) + ? (rawTier as WorkspaceTier) + : "pro"; + const targetConfig = TIER_CONFIGS[targetTier]; + + let expiresAt: string; + if (data.next_billing_date) { + expiresAt = new Date(data.next_billing_date).toISOString(); + } else { + expiresAt = new Date(Date.now() + 31 * 86400 * 1000).toISOString(); + } + + await store.updateWorkspace(ws.id, { + tier: targetTier, + quotaBytes: targetConfig.quotaBytes, + defaultTtlSeconds: targetConfig.defaultTtlSeconds, + subscriptionId: data.subscription_id || data.payment_id, + subscriptionStatus: "active", + subscriptionExpiresAt: expiresAt, + }); + + return reply.code(200).send({ + success: true, + event: eventType, + workspaceSlug, + tier: targetTier, + quotaBytes: targetConfig.quotaBytes, + message: `Successfully upgraded workspace '${workspaceSlug}' to ${targetConfig.name} (${targetConfig.quotaLabel})`, + }); + } + + // Handle cancellation / refund: downgrade back to free tier + if (eventType === "subscription.cancelled" || eventType === "payment.refunded") { + const freeConfig = TIER_CONFIGS.free; + await store.updateWorkspace(ws.id, { + tier: "free", + quotaBytes: freeConfig.quotaBytes, + defaultTtlSeconds: freeConfig.defaultTtlSeconds, + subscriptionStatus: "cancelled", + }); + + return reply.code(200).send({ + success: true, + event: eventType, + workspaceSlug, + tier: "free", + quotaBytes: freeConfig.quotaBytes, + message: `Downgraded workspace '${workspaceSlug}' to Free Tier (${freeConfig.quotaLabel})`, + }); + } + + return reply.code(200).send({ + success: true, + event: eventType, + message: `Event '${eventType}' acknowledged without state modification`, + }); + }); +} diff --git a/src/server.ts b/src/server.ts index e79cde5..e3a69f5 100644 --- a/src/server.ts +++ b/src/server.ts @@ -6,6 +6,7 @@ import type { MetadataStore } from "./metadata/types.js"; import type { GitHubOidcVerifier } from "./oidc/verifier.js"; import { StorageOptimizerDaemon } from "./optimizer/daemon.js"; import { registerArtifactRoutes } from "./routes/artifacts.js"; +import { registerBillingRoutes } from "./routes/billing.js"; import { registerDashboardRoutes } from "./routes/dashboard.js"; import { registerEventsRoutes } from "./routes/events.js"; import { registerHealthRoutes } from "./routes/health.js"; @@ -102,6 +103,7 @@ export async function createPolyCloudServer( await registerOidcRoutes(app, { store, config, verifier: overrides?.oidcVerifier }); await registerHealthRoutes(app, { storage, config, startTime }); await registerMetricsRoutes(app, { store }); + await registerBillingRoutes(app, { store, config }); const start = async (): Promise => { optimizer.start(); diff --git a/tests/billing.test.ts b/tests/billing.test.ts new file mode 100644 index 0000000..320e8d7 --- /dev/null +++ b/tests/billing.test.ts @@ -0,0 +1,198 @@ +import assert from "node:assert/strict"; +import * as crypto from "node:crypto"; +import test from "node:test"; +import { loadConfig } from "../src/config.js"; +import { MemoryMetadataStore } from "../src/metadata/store.js"; +import { createPolyCloudServer } from "../src/server.js"; +import { MemoryStorage } from "../src/storage/memory.js"; + +test("Poly Remote Cloud Cache Tiering & Billing Suite", async (t) => { + const webhookSecret = "whsec_poly_cloud_test_secret_123456"; + const config = loadConfig({ + storageBackend: "memory", + authEnabled: true, + defaultAdminToken: "test-admin-secret", + defaultWorkspace: "default", + }); + + const storage = new MemoryStorage(); + const store = new MemoryMetadataStore(); + + const server = await createPolyCloudServer(config, { storage, store }); + const app = server.app; + + // Setup workspace with a low 500-byte quota to test paywall / quota limits + const lowQuotaWs = await store.ensureWorkspace("startup-team", "Startup Team", 500, "free"); + const { rawToken: writeToken } = await store.createToken({ + workspaceId: lowQuotaWs.id, + name: "team-ci-writer", + role: "write", + }); + + await t.test("GET /api/v1/billing/tiers returns tier definitions and pricing", async () => { + const res = await app.inject({ + method: "GET", + url: "/api/v1/billing/tiers", + }); + assert.equal(res.statusCode, 200); + const body = JSON.parse(res.body); + assert.equal(body.success, true); + assert.ok(body.tiers.free); + assert.ok(body.tiers.pro); + assert.ok(body.tiers.enterprise); + assert.equal(body.tiers.pro.priceMonthlyUsd, 29); + assert.equal(body.tiers.pro.quotaLabel, "50 GB"); + }); + + await t.test("POST /api/v1/billing/checkout generates Dodo checkout link", async () => { + const res = await app.inject({ + method: "POST", + url: "/api/v1/billing/checkout", + payload: { + workspaceSlug: "startup-team", + tier: "pro", + email: "lead@startup.io", + }, + }); + assert.equal(res.statusCode, 200); + const body = JSON.parse(res.body); + assert.equal(body.success, true); + assert.equal(body.workspaceSlug, "startup-team"); + assert.equal(body.tier, "pro"); + assert.ok(body.checkoutUrl.includes("checkout.dodopayments.com")); + assert.ok(body.checkoutUrl.includes("metadata.workspace=startup-team")); + assert.ok(body.checkoutUrl.includes("metadata.tier=pro")); + assert.ok(body.checkoutUrl.includes("email=lead%40startup.io")); + }); + + await t.test("PUT /v8/artifacts/:hash returns 402 Payment Required when quota is exceeded", async () => { + // Artifact size is 600 bytes, which exceeds the 500-byte quota + const artifactPayload = Buffer.alloc(600, "x"); + const res = await app.inject({ + method: "PUT", + url: "/v8/artifacts/oversized-hash?team=startup-team", + headers: { + authorization: `Bearer ${writeToken}`, + "content-type": "application/octet-stream", + "content-length": "600", + }, + payload: artifactPayload, + }); + + assert.equal(res.statusCode, 402); + assert.ok(res.headers["x-poly-upgrade-url"]); + const body = JSON.parse(res.body); + assert.equal(body.error, "Payment Required"); + assert.equal(body.code, "QUOTA_EXCEEDED"); + assert.equal(body.tier, "free"); + assert.ok(body.upgradeUrl.includes("checkout.dodopayments.com")); + }); + + await t.test("POST /api/v1/billing/webhooks/dodo enforces signature and upgrades workspace to Pro", async () => { + process.env.DODO_WEBHOOK_SECRET = webhookSecret; + + const payload = { + event_id: "evt_sub_active_101", + type: "subscription.active", + data: { + subscription_id: "sub_dodo_live_999", + product_id: "pdt_0NpjONNytUpW7gzjoDlYW", + metadata: { + workspace: "startup-team", + tier: "pro", + }, + }, + }; + + const rawBody = JSON.stringify(payload); + const sig = crypto.createHmac("sha256", webhookSecret).update(rawBody).digest("hex"); + + const res = await app.inject({ + method: "POST", + url: "/api/v1/billing/webhooks/dodo", + headers: { + "webhook-signature": `sha256=${sig}`, + "content-type": "application/json", + }, + payload, + }); + + assert.equal(res.statusCode, 200); + const body = JSON.parse(res.body); + assert.equal(body.success, true); + assert.equal(body.tier, "pro"); + assert.equal(body.quotaBytes, 50 * 1024 * 1024 * 1024); + + // Verify workspace in store is now Pro + const ws = await store.getWorkspaceBySlug("startup-team"); + assert.equal(ws?.tier, "pro"); + assert.equal(ws?.quotaBytes, 50 * 1024 * 1024 * 1024); + assert.equal(ws?.subscriptionStatus, "active"); + + // Upload the 600-byte artifact again: now it must succeed on the 50 GB Pro tier! + const artifactPayload = Buffer.alloc(600, "x"); + const uploadRes = await app.inject({ + method: "PUT", + url: "/v8/artifacts/oversized-hash?team=startup-team", + headers: { + authorization: `Bearer ${writeToken}`, + "content-type": "application/octet-stream", + "content-length": "600", + }, + payload: artifactPayload, + }); + + assert.equal(uploadRes.statusCode, 200); + const uploadBody = JSON.parse(uploadRes.body); + assert.equal(uploadBody.status, "stored"); + }); + + await t.test("GET /api/v1/workspaces/:slug/billing reports active Pro status", async () => { + const res = await app.inject({ + method: "GET", + url: "/api/v1/workspaces/startup-team/billing", + }); + assert.equal(res.statusCode, 200); + const body = JSON.parse(res.body); + assert.equal(body.workspaceSlug, "startup-team"); + assert.equal(body.tier, "pro"); + assert.equal(body.priceMonthlyUsd, 29); + assert.equal(body.subscriptionStatus, "active"); + assert.ok(body.usedBytes >= 600); + }); + + await t.test("POST /api/v1/billing/webhooks/dodo downgrades workspace on subscription.cancelled", async () => { + const payload = { + event_id: "evt_sub_cancel_102", + type: "subscription.cancelled", + data: { + subscription_id: "sub_dodo_live_999", + metadata: { + workspace: "startup-team", + }, + }, + }; + + const rawBody = JSON.stringify(payload); + const sig = crypto.createHmac("sha256", webhookSecret).update(rawBody).digest("hex"); + + const res = await app.inject({ + method: "POST", + url: "/api/v1/billing/webhooks/dodo", + headers: { + "webhook-signature": `sha256=${sig}`, + "content-type": "application/json", + }, + payload, + }); + + assert.equal(res.statusCode, 200); + const body = JSON.parse(res.body); + assert.equal(body.tier, "free"); + assert.equal(body.quotaBytes, 1024 * 1024 * 1024); + + const ws = await store.getWorkspaceBySlug("startup-team"); + assert.equal(ws?.tier, "free"); + assert.equal(ws?.subscriptionStatus, "cancelled"); + }); +});