import { beforeEach, describe, expect, mock, test } from "bun:test"; import Stripe from "stripe"; import { fakeD1 } from "../metering/fake-d1.test-helper"; let d1 = fakeD1(); const kv = new Map(); const SECRET = "whsec_test_secret"; const fakeEnv: Record = { get DB() { return d1.binding; }, KV: { get: async (key: string) => kv.get(key) ?? null, put: async (key: string, value: string) => void kv.set(key, value), delete: async (key: string) => void kv.delete(key), }, METERING_PLANS: "", PUBLIC_URL: "https://forge.test", STRIPE_SECRET_KEY: "sk_test_unit", STRIPE_WEBHOOK_SECRET: SECRET, STRIPE_PRICE_PRO: "price_pro", STRIPE_TOPUP_PRICES: JSON.stringify({ compute_s: { price: "price_c", meter: "compute.runner", quantity: 36_000 }, bad: { price: "nope", meter: "compute.runner", quantity: 1 }, byok: { price: "price_x", meter: "ai.byok_tokens", quantity: 1 }, }), }; mock.module("cloudflare:workers", () => ({ env: fakeEnv, waitUntil: () => undefined })); const { handleStripeWebhook, processStripeEvent } = await import("./webhook"); const { topupPacks } = await import("./config"); const { creditBalance } = await import("../metering/credits"); const signer = new Stripe("sk_test_unit"); const crypto = Stripe.createSubtleCryptoProvider(); let sequence = 0; function event(type: string, object: Record, created = 1_700_000_000 + sequence): Stripe.Event { sequence += 1; return { id: `evt_${sequence}`, object: "event", type, created, data: { object } } as unknown as Stripe.Event; } async function post(payload: Stripe.Event, secret = SECRET): Promise { const body = JSON.stringify(payload); const signature = await signer.webhooks.generateTestHeaderStringAsync({ payload: body, secret, cryptoProvider: crypto, }); return handleStripeWebhook( new Request("https://forge.test/stripe/webhook", { method: "POST", headers: { "stripe-signature": signature }, body, }), ); } function plan(accountId: string): string | null { const row = d1.db.query("SELECT plan FROM account_billing WHERE account_id = ?").get(accountId) as { plan: string; } | null; return row?.plan ?? null; } function subscription(status: string, extra: Record = {}) { return { id: "sub_1", object: "subscription", customer: "cus_1", status, cancel_at_period_end: false, metadata: { account_id: "o1" }, items: { data: [{ price: { id: "price_pro" }, current_period_end: 1_800_000_000 }] }, ...extra, }; } beforeEach(() => { d1 = fakeD1(); kv.clear(); d1.db.exec("INSERT INTO accounts VALUES ('u1', 'alice', 'user'), ('o1', 'acme', 'org');"); }); describe("stripe webhook", () => { test("rejects missing and wrong signatures", async () => { const payload = event("customer.subscription.created", subscription("active")); const unsigned = await handleStripeWebhook( new Request("https://forge.test/stripe/webhook", { method: "POST", body: JSON.stringify(payload) }), ); expect(unsigned.status).toBe(400); expect((await post(payload, "whsec_other")).status).toBe(400); expect(plan("o1")).toBeNull(); expect((await post(payload)).status).toBe(200); expect(plan("o1")).toBe("pro"); }); test("is idempotent on event id", async () => { const payload = event("customer.subscription.created", subscription("active")); expect(await processStripeEvent(payload)).toBe("processed"); expect(await processStripeEvent(payload)).toBe("duplicate"); }); test("subscription lifecycle drives the plan, ignoring stale events", async () => { await processStripeEvent(event("customer.subscription.created", subscription("active"), 100)); expect(plan("o1")).toBe("pro"); await processStripeEvent(event("customer.subscription.deleted", subscription("canceled"), 300)); expect(plan("o1")).toBe("free"); await processStripeEvent(event("customer.subscription.updated", subscription("active"), 200)); expect(plan("o1")).toBe("free"); }); test("checkout completion upgrades at once and maps the customer to the org", async () => { await processStripeEvent( event("checkout.session.completed", { id: "cs_1", object: "checkout.session", mode: "subscription", status: "complete", payment_status: "paid", customer: "cus_9", subscription: "sub_9", metadata: { account_id: "o1", kind: "pro" }, }), ); expect(plan("o1")).toBe("pro"); const row = d1.db.query("SELECT account_id FROM billing_customers WHERE stripe_customer_id = 'cus_9'").get(); expect(row).toEqual({ account_id: "o1" }); }); test("metadata can't move an already-mapped customer to another account", async () => { await processStripeEvent(event("customer.subscription.created", subscription("active"))); await processStripeEvent( event("customer.subscription.updated", subscription("active", { metadata: { account_id: "u1" } })), ); expect(plan("u1")).toBeNull(); }); test("a final failed payment drops to free; a retryable one keeps pro", async () => { await processStripeEvent(event("customer.subscription.created", subscription("active"))); await processStripeEvent( event("invoice.payment_failed", { customer: "cus_1", next_payment_attempt: 1_900_000_000 }), ); expect(plan("o1")).toBe("pro"); await processStripeEvent(event("invoice.payment_failed", { customer: "cus_1", next_payment_attempt: null })); expect(plan("o1")).toBe("free"); }); test("paid top-ups add credit once; refunds and disputes reverse unused credit", async () => { const session = { id: "cs_top", object: "checkout.session", mode: "payment", status: "complete", payment_status: "paid", customer: "cus_2", payment_intent: "pi_1", amount_total: 1000, metadata: { account_id: "u1", kind: "topup", pack: "compute_s", meter: "compute.runner", quantity: "36000" }, }; await processStripeEvent(event("checkout.session.completed", session)); await processStripeEvent(event("checkout.session.completed", session)); expect(await creditBalance("u1", "compute.runner")).toBe(36_000); await processStripeEvent( event("charge.refunded", { id: "ch_1", payment_intent: "pi_1", amount: 1000, amount_refunded: 500 }), ); expect(await creditBalance("u1", "compute.runner")).toBe(18_000); await processStripeEvent(event("charge.dispute.created", { id: "dp_1", payment_intent: "pi_1" })); expect(await creditBalance("u1", "compute.runner")).toBe(0); }); test("unpaid top-ups add nothing", async () => { await processStripeEvent( event("checkout.session.completed", { id: "cs_x", mode: "payment", payment_status: "unpaid", customer: "cus_3", metadata: { account_id: "u1", kind: "topup", meter: "compute.runner", quantity: "10" }, }), ); expect(await creditBalance("u1", "compute.runner")).toBe(0); }); test("top-up packs drop malformed entries", () => { expect(topupPacks().map((pack) => pack.id)).toEqual(["compute_s"]); }); test("without Stripe the webhook does not exist", async () => { const key = fakeEnv.STRIPE_SECRET_KEY; delete fakeEnv.STRIPE_SECRET_KEY; try { const response = await post(event("customer.subscription.created", subscription("active"))); expect(response.status).toBe(404); } finally { fakeEnv.STRIPE_SECRET_KEY = key; } }); });