Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions telemetry-worker/src/stripe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ type Obj = Record<string, any>;

const STRIPE_ID_RE = /^[a-z]{2,8}_[A-Za-z0-9]{6,255}$/;
const SESSION_ID_RE = /^cs_[A-Za-z0-9_]{6,255}$/;
/** A product id: Stripe's (prod_...) or one scripts/stripe-setup.mjs named (genclass_team). */
const PRODUCT_ID_RE = /^[A-Za-z0-9_]{1,128}$/;

/** Subscriptions that exist and bill, or can bill again: an account may hold one. */
export const HOLDING_STATUSES = new Set([...LIVE_STATUSES, "unpaid", "paused"]);
Expand Down Expand Up @@ -287,8 +289,23 @@ export async function ensureCustomer(env: Env, f: Fetch, db: D1Like, a: BillingA
* only ensureCustomer writes.
*/
export async function customerSubscriptions(env: Env, f: Fetch, customer: string): Promise<Obj[]> {
const r = await stripe(env, f, "GET", "/v1/subscriptions", { customer, status: "all", limit: 100, expand: ["data.items.data.price.product", "data.latest_invoice"] });
return (Array.isArray(r?.data) ? r.data : []).filter((s: Obj) => idOf(s?.id));
// Stripe expands at most 4 levels: a list reaches data.items.data.price, not the price's product (asking for
// data.items.data.price.product is a 400, which broke Checkout for every account with a customer until 2026-11-12),
// so each product the prices name is fetched once and put back in its place, as a single subscription expands it
const r = await stripe(env, f, "GET", "/v1/subscriptions", { customer, status: "all", limit: 100, expand: ["data.items.data.price", "data.latest_invoice"] });
const subs: Obj[] = (Array.isArray(r?.data) ? r.data : []).filter((s: Obj) => idOf(s?.id));
const prices: Obj[] = subs.flatMap((s) => (Array.isArray(s?.items?.data) ? (s.items.data as Obj[]) : []).map((i) => i?.price).filter((p): p is Obj => !!p && typeof p === "object"));
const products = new Map<string, Obj>();
for (const id of new Set(prices.map((p) => p.product).filter((x): x is string => typeof x === "string" && PRODUCT_ID_RE.test(x)))) {
try {
products.set(id, await stripe(env, f, "GET", `/v1/products/${encodeURIComponent(id)}`));
} catch (e) {
// a product deleted in Stripe: its price stays unexpanded, so it is provably no one's (src/plans.ts planForPrice)
if (!(e instanceof StripeError && e.status === 404)) throw e;
}
}
for (const p of prices) if (typeof p.product === "string" && products.has(p.product)) p.product = products.get(p.product);
return subs;
}

/**
Expand Down
17 changes: 16 additions & 1 deletion telemetry-worker/test/account-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,9 @@ export function fakeStripe(o: { answer?: (url: URL, init: RequestInit) => Respon
calls.push({ method, url, form, headers });
const custom = o.answer?.(url, init);
if (custom) return custom;
// Stripe refuses an expand deeper than 4 levels, whatever the endpoint (a list's data. counts as one)
const deep = expands(url).find((e) => e.split(".").length > 4);
if (deep) return ok({ error: { type: "invalid_request_error", message: `You cannot expand more than 4 levels of a property. Property: ${deep}.` } }, 400);
const p = url.pathname;
if (method === "GET" && p === "/v1/prices") {
// GenClass's two prices, with their products expanded (the worker asks for data.product)
Expand Down Expand Up @@ -276,7 +279,19 @@ export function fakeStripe(o: { answer?: (url: URL, init: RequestInit) => Respon
if (method === "GET" && p === "/v1/subscriptions") {
const customer = url.searchParams.get("customer");
const withInvoice = expands(url).includes("data.latest_invoice");
return ok({ data: [...subs.values()].filter((s) => s.customer === customer).map((s) => (withInvoice ? { ...s, latest_invoice: latest(s) } : s)) });
// as Stripe lists them: a price's product is its id (a list cannot expand it: 4 levels at most, checked above)
const listed = (s: any) => ({
...s,
items: s.items && Array.isArray(s.items.data) ? { ...s.items, data: s.items.data.map((i: any) => (i?.price?.product?.id ? { ...i, price: { ...i.price, product: i.price.product.id } } : i)) } : s.items,
});
return ok({ data: [...subs.values()].filter((s) => s.customer === customer).map((s) => (withInvoice ? { ...listed(s), latest_invoice: latest(s) } : listed(s))) });
}
const prod = /^\/v1\/products\/([^/]+)$/.exec(p);
if (method === "GET" && prod) {
// the products the stored subscriptions' prices carry
const id = decodeURIComponent(prod[1]!);
for (const s of subs.values()) for (const i of (s as any).items?.data ?? []) if (i?.price?.product?.id === id) return ok(i.price.product);
return ok({ error: { code: "resource_missing", message: `No such product: '${id}'` } }, 404);
}
if (method === "GET" && p === "/v1/billing_portal/configurations") {
const d = url.searchParams.get("is_default");
Expand Down
24 changes: 14 additions & 10 deletions telemetry-worker/test/billing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ describe("POST /api/billing/checkout and /api/billing/portal", () => {
expect(s.calls.map((c) => `${c.method} ${c.url.pathname}`)).toEqual([
"GET /v1/customers/cus_known0001",
"GET /v1/subscriptions",
"GET /v1/products/genclass_pro",
"GET /v1/invoices",
`GET /v1/billing_portal/configurations/${GENCLASS_PORTAL}`,
"POST /v1/billing_portal/sessions",
Expand Down Expand Up @@ -337,18 +338,19 @@ describe("POST /api/billing/webhook: the plan follows the subscription", () => {
expect(t.plan()).toEqual({ plan: "pro", subscription_id: "sub_ada0000001", subscription_status: "active", current_period_end: new Date(1_792_000_000_000).toISOString(), cancel_at_period_end: 0 });
// the subscription (with its prices' products, its customer and its latest invoice), then the customer's
// subscriptions (one subscription per account)
expect(t.s.calls.map((c) => `${c.method} ${c.url.pathname}`)).toEqual(["GET /v1/subscriptions/sub_ada0000001", "GET /v1/subscriptions"]);
expect(t.s.calls.map((c) => `${c.method} ${c.url.pathname}`)).toEqual(["GET /v1/subscriptions/sub_ada0000001", "GET /v1/subscriptions", "GET /v1/products/genclass_pro"]);
expect(t.s.calls[0]!.url.searchParams.get("expand[0]")).toBe("items.data.price.product");
expect(t.s.calls[0]!.url.searchParams.get("expand[1]")).toBe("customer");
expect(t.s.calls[0]!.url.searchParams.get("expand[2]")).toBe("latest_invoice");
expect(t.s.calls[1]!.url.searchParams.get("expand[0]")).toBe("data.items.data.price.product");
// a list expands 4 levels at most (Stripe refuses more): the prices, then each product on its own
expect(t.s.calls[1]!.url.searchParams.get("expand[0]")).toBe("data.items.data.price");
expect(t.sql.rows("SELECT stripe_mode FROM accounts")).toEqual([{ stripe_mode: "live" }]);
expect(t.sql.rows("SELECT id, type FROM billing_events")).toEqual([{ id: ev.id, type: "customer.subscription.created" }]);
// a redelivery is recognised by its id: no second fetch, no change
t.s.subs.get("sub_ada0000001")!.status = "canceled";
const again = await deliver(t.env, ev, t.s.fetch);
expect(await again.json()).toEqual({ received: true, duplicate: true });
expect(t.s.calls).toHaveLength(2);
expect(t.s.calls).toHaveLength(3);
expect(t.plan().plan).toBe("pro");
});

Expand Down Expand Up @@ -552,7 +554,7 @@ describe("POST /api/billing/webhook: the plan follows the subscription", () => {
const ev = stripeEvent("invoice.paid", { ...paid, customer_email: "ada@example.com", customer_name: "Ada Lovelace", customer_address: { line1: "1 Main St" } });
expect(await (await deliver(t.env, ev, t.s.fetch)).json()).toEqual({ received: true, result: "applied" });
log.mockRestore();
expect(t.s.calls.map((c) => `${c.method} ${c.url.pathname}`)).toEqual(["GET /v1/subscriptions/sub_ada0000001", "GET /v1/subscriptions"]);
expect(t.s.calls.map((c) => `${c.method} ${c.url.pathname}`)).toEqual(["GET /v1/subscriptions/sub_ada0000001", "GET /v1/subscriptions", "GET /v1/products/genclass_custom"]);
expect(t.plan().plan).toBe("custom");
expect(t.sql.rows("SELECT subscription_id FROM custom_requests")).toEqual([{ subscription_id: "sub_ada0000001" }]);
// nothing of the buyer's from the invoice is stored or sent
Expand Down Expand Up @@ -1141,7 +1143,7 @@ describe("Managed Payments for Pro, flexible billing mode, switching between Pro
expect(r.status).toBe(200);
expect(await r.json()).toEqual({ url: "https://checkout.stripe.com/c/pay/cs_test_000001", switch: true });
// the customer and everything on it are checked, the invoices too
expect(calls(t.s)).toEqual(["GET /v1/customers/cus_sw00000001", "GET /v1/subscriptions", "GET /v1/invoices", "GET /v1/checkout/sessions", "GET /v1/prices", "POST /v1/checkout/sessions"]);
expect(calls(t.s)).toEqual(["GET /v1/customers/cus_sw00000001", "GET /v1/subscriptions", "GET /v1/products/genclass_pro", "GET /v1/invoices", "GET /v1/checkout/sessions", "GET /v1/prices", "POST /v1/checkout/sessions"]);
const form = sessionForm(t.s);
expect(form).toMatchObject({
customer: "cus_sw00000001",
Expand Down Expand Up @@ -1178,16 +1180,18 @@ describe("Managed Payments for Pro, flexible billing mode, switching between Pro
expect(calls(t.s)).toEqual([
"GET /v1/subscriptions/sub_cus0000001",
"GET /v1/subscriptions",
"GET /v1/products/genclass_pro",
"GET /v1/products/genclass_custom",
"GET /v1/invoices",
"GET /v1/invoice_payments",
"GET /v1/refunds",
"POST /v1/refunds",
"DELETE /v1/subscriptions/sub_pro0000001",
]);
expect(t.atCancel).toEqual([{ plan: "custom", subscription_id: "sub_cus0000001" }]);
expect(t.s.calls[2]!.url.searchParams.get("subscription")).toBe("sub_pro0000001");
expect(t.s.calls[2]!.url.searchParams.get("status")).toBe("paid");
const refund = t.s.calls[5]!;
expect(t.s.calls[4]!.url.searchParams.get("subscription")).toBe("sub_pro0000001");
expect(t.s.calls[4]!.url.searchParams.get("status")).toBe("paid");
const refund = t.s.calls[7]!;
expect(Object.fromEntries(refund.form!)).toEqual({
payment_intent: paymentIntentFor("in_pro0000001"),
amount: String(PRO_UNUSED),
Expand All @@ -1199,7 +1203,7 @@ describe("Managed Payments for Pro, flexible billing mode, switching between Pro
});
expect(refund.headers["idempotency-key"]).toBe(`genclass-refund-switch:sub_pro0000001-in_pro0000001-${PRO_UNUSED}`);
// no proration, no final invoice: nothing goes to the customer's balance
expect(t.s.calls[6]!.url.search).toBe("");
expect(t.s.calls[8]!.url.search).toBe("");
expect(t.s.subs.get("sub_pro0000001")!.status).toBe("canceled");
expect(t.row()).toEqual({ plan: "custom", subscription_id: "sub_cus0000001", subscription_status: "active" });
// the Custom purchase is recorded; the owner always hears of the switch, with the refund
Expand Down Expand Up @@ -1653,7 +1657,7 @@ describe("deleting an account with a paid plan", () => {
expect(sql.rows("SELECT COUNT(*) AS n FROM accounts")[0]!.n).toBe(1);
const del = await call(env, "DELETE", "/api/account", { body: { confirm: "delete" }, cookie: a.cookie, fetch: s.fetch });
expect(del.status).toBe(204);
expect(s.calls.map((c) => `${c.method} ${c.url.pathname}`)).toEqual(["GET /v1/customers/cus_del0000001", "GET /v1/subscriptions", "GET /v1/checkout/sessions", "DELETE /v1/subscriptions/sub_del0000001"]);
expect(s.calls.map((c) => `${c.method} ${c.url.pathname}`)).toEqual(["GET /v1/customers/cus_del0000001", "GET /v1/subscriptions", "GET /v1/products/genclass_pro", "GET /v1/checkout/sessions", "DELETE /v1/subscriptions/sub_del0000001"]);
expect(s.subs.get("sub_del0000001")!.status).toBe("canceled");
expect(sql.rows("SELECT COUNT(*) AS n FROM accounts")[0]!.n).toBe(0);
});
Expand Down
Loading