Skip to content

Open source CapCut alternative.

TypeScript

fix(site): harden credit/subscription billing from code review

David Le82d1fab157d6
diff --git a/site/prisma/Auth.prisma b/site/prisma/Auth.prisma
index a7eb4ec1..a59b59c1 100644
--- a/site/prisma/Auth.prisma
+++ b/site/prisma/Auth.prisma
@@ -5,6 +5,9 @@ model User {
emailVerified Boolean @default(false)
image String?
superUser Boolean @default(false)
+ // Stripe customer id, one per user, shared across every billing product
+ // (Pro, Vision, one-time credit top-ups) so a customer is never duplicated.
+ stripeCustomerId String? @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
sessions Session[]
diff --git a/site/prisma/Credits.prisma b/site/prisma/Credits.prisma
index 6c321882..ea158282 100644
--- a/site/prisma/Credits.prisma
+++ b/site/prisma/Credits.prisma
@@ -140,6 +140,9 @@ model CreditAutoReload {
stripeCustomerId String?
stripePaymentMethodId String?
status String @default("idle")
+ // The off-session PaymentIntent that currently owns the "charging" lock, so a
+ // success/failure webhook only releases the charge it actually belongs to.
+ chargingPaymentIntentId String?
lastChargeAt DateTime?
lastError String?
createdAt DateTime @default(now())
diff --git a/site/src/app/api/billing/credits/auto-reload/route.ts b/site/src/app/api/billing/credits/auto-reload/route.ts
index bd27677f..14c6007c 100644
--- a/site/src/app/api/billing/credits/auto-reload/route.ts
+++ b/site/src/app/api/billing/credits/auto-reload/route.ts
@@ -1,11 +1,11 @@
import { NextResponse } from "next/server";
import { z } from "zod";
+import { creditMicrosPerCredit } from "@/lib/credits/amounts";
import {
creditTopUpMaxDollars,
creditTopUpMinDollars,
-} from "@/lib/billing/credit-purchases";
-import { creditMicrosPerCredit } from "@/lib/credits/amounts";
+} from "@/lib/credits/top-up";
import { withDonkeyAuth } from "@/lib/donkey-api-auth";
import { prisma } from "@/lib/prisma";
@@ -93,7 +93,7 @@ export const PUT = withDonkeyAuth(async (request) => {
const thresholdMicros =
BigInt(parsed.data.thresholdDollars) * creditMicrosPerCredit;
- const config = await prisma.creditAutoReload.upsert({
+ await prisma.creditAutoReload.upsert({
create: {
amountMicros,
enabled: parsed.data.enabled,
@@ -104,11 +104,22 @@ export const PUT = withDonkeyAuth(async (request) => {
amountMicros,
enabled: parsed.data.enabled,
thresholdMicros,
- // Re-enabling after a failure clears the stale error and lock.
- ...(parsed.data.enabled ? { lastError: null, status: "idle" } : {}),
},
where: { userId: request.donkey.userId },
});
+ // Re-enabling clears a prior failure so the saved card is retried promptly.
+ // Scoped to status "failed" so it never resets an in-flight "charging" lock —
+ // clobbering that would let the next inference fire a second off-session charge.
+ if (parsed.data.enabled) {
+ await prisma.creditAutoReload.updateMany({
+ data: { chargingPaymentIntentId: null, lastError: null, status: "idle" },
+ where: { status: "failed", userId: request.donkey.userId },
+ });
+ }
+
+ const config = await prisma.creditAutoReload.findUnique({
+ where: { userId: request.donkey.userId },
+ });
return NextResponse.json(serialize(config));
});
diff --git a/site/src/app/api/billing/credits/checkout/route.ts b/site/src/app/api/billing/credits/checkout/route.ts
index 41a3fe8e..f677d693 100644
--- a/site/src/app/api/billing/credits/checkout/route.ts
+++ b/site/src/app/api/billing/credits/checkout/route.ts
@@ -2,13 +2,13 @@ import { NextResponse } from "next/server";
import { z } from "zod";
import { auth } from "@/lib/auth";
+import { ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";
import {
creditTopUpKind,
creditTopUpMaxDollars,
creditTopUpMinDollars,
dollarsToStripeCents,
-} from "@/lib/billing/credit-purchases";
-import { ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";
+} from "@/lib/credits/top-up";
import { unauthorizedResponse, withDonkeyAuth } from "@/lib/donkey-api-auth";
export const dynamic = "force-dynamic";
diff --git a/site/src/app/api/billing/pro/route.ts b/site/src/app/api/billing/pro/route.ts
index c9706222..d6d7e43e 100644
--- a/site/src/app/api/billing/pro/route.ts
+++ b/site/src/app/api/billing/pro/route.ts
@@ -18,10 +18,9 @@ export const GET = withDonkeyAuth(async (request) => {
const [subscription, grants] = await Promise.all([
getActiveProSubscription(userId),
prisma.userCreditGrant.findMany({
- select: { remainingAmountMicros: true },
+ select: { originalAmountMicros: true, remainingAmountMicros: true },
where: {
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
- remainingAmountMicros: { gt: zeroCreditMicros },
source: "pro_subscription",
status: "active",
unit: creditGrantUnit,
@@ -34,6 +33,17 @@ export const GET = withDonkeyAuth(async (request) => {
(sum, grant) => sum + grant.remainingAmountMicros,
zeroCreditMicros,
);
+ // Denominator = what was actually granted this period, so "X of Y left" stays
+ // consistent even if the price changed mid-period (the grant is frozen per
+ // period). Fall back to the configured allowance before the first grant lands.
+ const allowanceGrantedMicros = grants.reduce(
+ (sum, grant) => sum + grant.originalAmountMicros,
+ zeroCreditMicros,
+ );
+ const monthlyAllowanceMicros =
+ allowanceGrantedMicros > zeroCreditMicros
+ ? allowanceGrantedMicros
+ : (subscription?.monthlyAllowanceMicros ?? zeroCreditMicros);
return NextResponse.json({
allowanceRemaining: creditMicrosToString(allowanceRemainingMicros),
@@ -41,7 +51,7 @@ export const GET = withDonkeyAuth(async (request) => {
currentPeriodEnd: subscription?.currentPeriodEnd?.toISOString() ?? null,
isActive: Boolean(subscription),
monthlyAllowance: subscription
- ? creditMicrosToString(subscription.monthlyAllowanceMicros)
+ ? creditMicrosToString(monthlyAllowanceMicros)
: null,
status: subscription?.status ?? null,
});
diff --git a/site/src/app/api/billing/webhook/route.ts b/site/src/app/api/billing/webhook/route.ts
index 22652f22..9c0c35a7 100644
--- a/site/src/app/api/billing/webhook/route.ts
+++ b/site/src/app/api/billing/webhook/route.ts
@@ -5,6 +5,7 @@ import {
handleAutoReloadPaymentFailed,
handleAutoReloadPaymentSucceeded,
handleCreditTopUpCheckout,
+ handleCreditTopUpPaymentSucceeded,
} from "@/lib/billing/credit-purchases";
import {
subscriptionIsPro,
@@ -74,7 +75,9 @@ export async function POST(request: Request) {
break;
}
case "payment_intent.succeeded": {
+ // Each handler no-ops unless the PaymentIntent's kind matches, so both run.
await handleAutoReloadPaymentSucceeded(event.data.object);
+ await handleCreditTopUpPaymentSucceeded(event.data.object);
break;
}
case "payment_intent.payment_failed": {
diff --git a/site/src/lib/billing/credit-auto-reload.ts b/site/src/lib/billing/credit-auto-reload.ts
index a23da288..f951a81c 100644
--- a/site/src/lib/billing/credit-auto-reload.ts
+++ b/site/src/lib/billing/credit-auto-reload.ts
@@ -1,65 +1,89 @@
-import {
- creditAutoReloadKind,
- dollarsToStripeCents,
-} from "@/lib/billing/credit-purchases";
import { getStripe } from "@/lib/billing/stripe";
-import { creditMicrosPerCredit, zeroCreditMicros } from "@/lib/credits/amounts";
+import { creditMicrosPerCent, zeroCreditMicros } from "@/lib/credits/amounts";
+import { creditAutoReloadKind } from "@/lib/credits/top-up";
import { prisma } from "@/lib/prisma";
-// Fired after an inference charge commits (best-effort, non-blocking). If the
-// balance fell below the user's auto-reload threshold, start an off-session
-// Stripe charge against the saved card. The actual credit grant happens in the
-// payment_intent.succeeded webhook, not here — this only kicks off the charge.
-export async function maybeTriggerCreditAutoReload(userId: string): Promise<void> {
+// A "charging" lock older than this is treated as stale and may be re-claimed.
+// This self-heals a lock left dangling by a dropped success/failure webhook (or a
+// PaymentIntent that ended in requires_action), so auto-reload never wedges.
+const chargingStaleMs = 10 * 60 * 1000;
+// After a failed charge, wait this long before retrying the saved card, so a
+// declined card doesn't fire a fresh charge on every subsequent inference.
+const failedRetryMs = 60 * 60 * 1000;
+
+// Fired (best-effort, off the response path) after an inference charge commits.
+// If the balance fell below the user's threshold, kick off an off-session Stripe
+// charge against the saved card. The credit grant itself lands in the
+// payment_intent.succeeded webhook — this only starts the charge. balanceMicros
+// is the post-charge balance the caller already computed, so we don't re-read it.
+export async function maybeTriggerCreditAutoReload(
+ userId: string,
+ balanceMicros: bigint,
+): Promise<void> {
const config = await prisma.creditAutoReload.findUnique({ where: { userId } });
if (
!config ||
!config.enabled ||
!config.stripeCustomerId ||
!config.stripePaymentMethodId ||
- config.status === "charging" ||
- config.amountMicros <= zeroCreditMicros
+ config.amountMicros <= zeroCreditMicros ||
+ balanceMicros > config.thresholdMicros
) {
return;
}
- const account = await prisma.userCreditAccount.findUnique({
- select: { balanceMicros: true },
- where: { userId },
- });
- if (!account || account.balanceMicros > config.thresholdMicros) {
- return;
- }
+ const now = Date.now();
+ const chargingCutoff = new Date(now - chargingStaleMs);
+ const failedCutoff = new Date(now - failedRetryMs);
- // Claim the charging lock atomically. If another concurrent run already
- // claimed it, count is 0 and we bail — never double-charge.
+ // Claim the lock atomically. A fresh "charging" lock blocks (one charge at a
+ // time); a stale one is reclaimable (dropped webhook); a "failed" one only
+ // after the backoff window. updatedAt is set to now by this write, so it
+ // doubles as the lock-claim timestamp the cutoffs above compare against.
const claimed = await prisma.creditAutoReload.updateMany({
data: { status: "charging" },
- where: { status: { not: "charging" }, userId },
+ where: {
+ enabled: true,
+ stripePaymentMethodId: { not: null },
+ userId,
+ OR: [
+ { status: "idle" },
+ { status: "charging", updatedAt: { lt: chargingCutoff } },
+ { status: "failed", updatedAt: { lt: failedCutoff } },
+ ],
+ },
});
if (claimed.count === 0) {
return;
}
- const amountDollars = Number(config.amountMicros / creditMicrosPerCredit);
+ // amountMicros is whole dollars; charge the exact cents it represents.
+ const amountCents = Number(config.amountMicros / creditMicrosPerCent);
try {
const stripe = getStripe();
- await stripe.paymentIntents.create({
- amount: dollarsToStripeCents(amountDollars),
+ const paymentIntent = await stripe.paymentIntents.create({
+ amount: amountCents,
confirm: true,
currency: "usd",
customer: config.stripeCustomerId,
metadata: {
- amountDollars: String(amountDollars),
+ amountDollars: String(amountCents / 100),
kind: creditAutoReloadKind,
userId,
},
off_session: true,
payment_method: config.stripePaymentMethodId,
});
+ // Record which PaymentIntent owns the lock so its webhook only releases
+ // its own charge (a later charge's lock is never clobbered by a stale one).
+ await prisma.creditAutoReload.updateMany({
+ data: { chargingPaymentIntentId: paymentIntent.id },
+ where: { userId, status: "charging" },
+ });
} catch (error) {
await prisma.creditAutoReload.updateMany({
data: {
+ chargingPaymentIntentId: null,
lastError:
error instanceof Error ? error.message : "Auto-reload charge failed.",
status: "failed",
diff --git a/site/src/lib/billing/credit-purchases.ts b/site/src/lib/billing/credit-purchases.ts
index d0a44023..7703bc00 100644
--- a/site/src/lib/billing/credit-purchases.ts
+++ b/site/src/lib/billing/credit-purchases.ts
@@ -2,24 +2,10 @@ import type Stripe from "stripe";
import { stripeId } from "@/lib/billing/stripe";
import { creditStringToMicros } from "@/lib/credits/amounts";
+import { creditAutoReloadKind, creditTopUpKind } from "@/lib/credits/top-up";
import { grantCredits } from "@/lib/credits/inference";
import { prisma } from "@/lib/prisma";
-// Self-serve credit top-ups. Presets drive the quick-buy buttons; the custom
-// field accepts any whole-dollar amount in [min, max]. Amounts are whole dollars
-// so they map cleanly to Stripe unit_amount cents and the grant ledger.
-export const creditTopUpPresetsDollars = [5, 25, 50, 100] as const;
-export const creditTopUpMinDollars = 5;
-export const creditTopUpMaxDollars = 2_000;
-
-// Stripe metadata "kind" tags that route a completed payment to a credit grant.
-export const creditTopUpKind = "credit_topup";
-export const creditAutoReloadKind = "credit_topup_autoreload";
-
-export function dollarsToStripeCents(amountDollars: number): number {
- return Math.round(amountDollars * 100);
-}
-
function parseAmountDollars(value: string | undefined): number | null {
if (!value) {
return null;
@@ -102,8 +88,34 @@ export async function handleCreditTopUpCheckout(
}
}
-// An off-session auto-reload charge succeeded. Grant the credits and clear the
-// charging lock so a future low balance can trigger again.
+// A one-time top-up PaymentIntent succeeded. A fallback to the
+// checkout.session.completed grant: the two share a (source, sourceId) so
+// grantCredits dedupes, but this guarantees the credits land even if the
+// Checkout event is dropped or the endpoint isn't subscribed to it.
+export async function handleCreditTopUpPaymentSucceeded(
+ paymentIntent: Stripe.PaymentIntent,
+): Promise<void> {
+ if (paymentIntent.metadata?.kind !== creditTopUpKind) {
+ return;
+ }
+ const userId = paymentIntent.metadata?.userId;
+ const amountDollars = parseAmountDollars(paymentIntent.metadata?.amountDollars);
+ if (!userId || !amountDollars) {
+ return;
+ }
+
+ await grantPurchasedCredits({
+ amountDollars,
+ description: `$${amountDollars} credit top-up`,
+ source: "stripe_topup",
+ sourceId: paymentIntent.id,
+ userId,
+ });
+}
+
+// An off-session auto-reload charge succeeded. Grant the credits and release the
+// lock — but only if this PaymentIntent still owns it, so a stale webhook can't
+// clear a newer charge's lock.
export async function handleAutoReloadPaymentSucceeded(
paymentIntent: Stripe.PaymentIntent,
): Promise<void> {
@@ -125,13 +137,18 @@ export async function handleAutoReloadPaymentSucceeded(
});
await prisma.creditAutoReload.updateMany({
- data: { lastChargeAt: new Date(), lastError: null, status: "idle" },
- where: { userId },
+ data: {
+ chargingPaymentIntentId: null,
+ lastChargeAt: new Date(),
+ lastError: null,
+ status: "idle",
+ },
+ where: { chargingPaymentIntentId: paymentIntent.id, userId },
});
}
// An off-session auto-reload charge failed (e.g. card declined). Record it and
-// release the lock; the UI surfaces lastError so the user can fix the card.
+// release the lock it owns; the UI surfaces lastError so the user can fix the card.
export async function handleAutoReloadPaymentFailed(
paymentIntent: Stripe.PaymentIntent,
): Promise<void> {
@@ -145,11 +162,12 @@ export async function handleAutoReloadPaymentFailed(
await prisma.creditAutoReload.updateMany({
data: {
+ chargingPaymentIntentId: null,
lastError:
paymentIntent.last_payment_error?.message ?? "The auto-reload charge failed.",
status: "failed",
},
- where: { userId },
+ where: { chargingPaymentIntentId: paymentIntent.id, userId },
});
}
diff --git a/site/src/lib/billing/pro-subscription.ts b/site/src/lib/billing/pro-subscription.ts
index 7b89debb..aa48672b 100644
--- a/site/src/lib/billing/pro-subscription.ts
+++ b/site/src/lib/billing/pro-subscription.ts
@@ -1,13 +1,14 @@
import type Stripe from "stripe";
-import { stripeId } from "@/lib/billing/stripe";
-import { zeroCreditMicros } from "@/lib/credits/amounts";
+import {
+ resolveSubscriptionUserId,
+ stripeId,
+ unixToDate,
+} from "@/lib/billing/stripe";
+import { creditMicrosPerCent, zeroCreditMicros } from "@/lib/credits/amounts";
import { grantCredits } from "@/lib/credits/inference";
import { prisma } from "@/lib/prisma";
-// Credit micros per Stripe cent. $1 = 100 cents = 1,000,000 micros, so 1 cent = 10,000 micros.
-const creditMicrosPerCent = BigInt(10_000);
-
// Donkey Pro: the Mac app subscription, separate from the Vision API product.
export const proPlanKey = "pro";
@@ -45,11 +46,22 @@ export async function getActiveProSubscription(userId: string) {
return subscription;
}
-// True when a Stripe subscription belongs to the Pro product (vs Vision). Used
-// to route shared subscription webhook events to the right sync.
+// The subscription's Pro line item, if any. Matches across ALL items (not just
+// the first), so a multi-item subscription is still recognized as Pro and its
+// price/period are read from the right item rather than items.data[0].
+function proItem(
+ subscription: Stripe.Subscription,
+): Stripe.SubscriptionItem | undefined {
+ const id = proPriceId();
+ return id
+ ? subscription.items.data.find((item) => item.price?.id === id)
+ : undefined;
+}
+
+// True when the subscription includes the Pro price. Used to route shared
+// subscription webhook events to the right product sync.
export function subscriptionIsPro(subscription: Stripe.Subscription): boolean {
- const priceId = subscription.items.data[0]?.price?.id;
- return Boolean(priceId && proPriceId() && priceId === proPriceId());
+ return proItem(subscription) !== undefined;
}
// Source of truth for a Pro subscription's lifecycle. Maps the Stripe object
@@ -60,7 +72,7 @@ export function subscriptionIsPro(subscription: Stripe.Subscription): boolean {
export async function syncProSubscription(
subscription: Stripe.Subscription,
): Promise<void> {
- const userId = await resolveUserIdForSubscription(subscription);
+ const userId = await resolveSubscriptionUserId(subscription);
const customerId = stripeId(subscription.customer);
if (!userId) {
console.error("[billing] could not resolve user for Pro subscription", {
@@ -70,7 +82,7 @@ export async function syncProSubscription(
return;
}
- const item = subscription.items.data[0];
+ const item = proItem(subscription) ?? subscription.items.data[0];
const price = item?.price;
const periodStart = unixToDate(item?.current_period_start ?? null);
const periodEnd = unixToDate(item?.current_period_end ?? null);
@@ -107,7 +119,7 @@ export async function syncProSubscription(
isActiveProStatus(subscription.status) &&
periodStart &&
periodEnd &&
- allowanceMicros > BigInt(0)
+ allowanceMicros > zeroCreditMicros
) {
await grantCredits({
amountMicros: allowanceMicros,
@@ -122,31 +134,3 @@ export async function syncProSubscription(
});
}
}
-
-async function resolveUserIdForSubscription(
- subscription: Stripe.Subscription,
-): Promise<string | null> {
- const metadataUserId = subscription.metadata?.userId;
- if (metadataUserId) {
- return metadataUserId;
- }
-
- const customerId = stripeId(subscription.customer);
- if (customerId) {
- const row = await prisma.proSubscription.findFirst({
- where: { stripeCustomerId: customerId },
- });
- if (row) {
- return row.userId;
- }
- }
-
- return null;
-}
-
-function unixToDate(seconds: number | null | undefined): Date | null {
- if (!seconds) {
- return null;
- }
- return new Date(seconds * 1000);
-}
diff --git a/site/src/lib/billing/stripe.ts b/site/src/lib/billing/stripe.ts
index 9901f002..37ab0428 100644
--- a/site/src/lib/billing/stripe.ts
+++ b/site/src/lib/billing/stripe.ts
@@ -58,18 +58,34 @@ export function quotaFromPrice(price: Stripe.Price | null | undefined): number {
return defaultVisionMonthlyQuota;
}
-// Reuse one Stripe customer per user. The id is stored on the user's
-// VisionApiSubscription row once known.
+// Reuse one Stripe customer per user, stored on User.stripeCustomerId so every
+// billing product (Pro, Vision, top-ups) shares it and a customer is never
+// duplicated — and a Pro-only or credit-only user gets no phantom Vision row.
export async function ensureStripeCustomer(input: {
userId: string;
email: string;
name?: string | null;
}): Promise<string> {
- const existing = await prisma.visionApiSubscription.findUnique({
+ const user = await prisma.user.findUnique({
+ select: { stripeCustomerId: true },
+ where: { id: input.userId },
+ });
+ if (user?.stripeCustomerId) {
+ return user.stripeCustomerId;
+ }
+
+ // Legacy rows stored the customer id on the Vision subscription; reuse it (and
+ // backfill the user) so an existing Vision customer is never re-created.
+ const legacyVision = await prisma.visionApiSubscription.findUnique({
+ select: { stripeCustomerId: true },
where: { userId: input.userId },
});
- if (existing?.stripeCustomerId) {
- return existing.stripeCustomerId;
+ if (legacyVision?.stripeCustomerId) {
+ await prisma.user.update({
+ data: { stripeCustomerId: legacyVision.stripeCustomerId },
+ where: { id: input.userId },
+ });
+ return legacyVision.stripeCustomerId;
}
const stripe = getStripe();
@@ -78,26 +94,42 @@ export async function ensureStripeCustomer(input: {
metadata: { userId: input.userId },
name: input.name ?? undefined,
});
-
- await prisma.visionApiSubscription.upsert({
- create: {
- planKey: visionPlanKey,
- stripeCustomerId: customer.id,
- userId: input.userId,
- },
- update: { stripeCustomerId: customer.id },
- where: { userId: input.userId },
+ await prisma.user.update({
+ data: { stripeCustomerId: customer.id },
+ where: { id: input.userId },
});
-
return customer.id;
}
+// Resolve which user a Stripe subscription belongs to: the userId stamped into
+// subscription metadata at checkout, falling back to the per-user Stripe customer
+// id. Shared by the Vision and Pro sync paths so they can't resolve differently.
+export async function resolveSubscriptionUserId(
+ subscription: Stripe.Subscription,
+): Promise<string | null> {
+ const metadataUserId = subscription.metadata?.userId;
+ if (metadataUserId) {
+ return metadataUserId;
+ }
+ const customerId = stripeId(subscription.customer);
+ if (customerId) {
+ const user = await prisma.user.findUnique({
+ select: { id: true },
+ where: { stripeCustomerId: customerId },
+ });
+ if (user) {
+ return user.id;
+ }
+ }
+ return null;
+}
+
// Source of truth for a subscription's lifecycle. Called from webhook handlers
// with a fully-expanded Stripe subscription; maps it onto our row.
export async function syncVisionSubscription(
subscription: Stripe.Subscription,
): Promise<void> {
- const userId = await resolveUserIdForSubscription(subscription);
+ const userId = await resolveSubscriptionUserId(subscription);
const customerId = stripeId(subscription.customer);
if (!userId || !customerId) {
console.error("[billing] could not resolve user/customer for subscription", {
@@ -149,27 +181,6 @@ export async function syncVisionSubscription(
});
}
-async function resolveUserIdForSubscription(
- subscription: Stripe.Subscription,
-): Promise<string | null> {
- const metadataUserId = subscription.metadata?.userId;
- if (metadataUserId) {
- return metadataUserId;
- }
-
- const customerId = stripeId(subscription.customer);
- if (customerId) {
- const row = await prisma.visionApiSubscription.findFirst({
- where: { stripeCustomerId: customerId },
- });
- if (row) {
- return row.userId;
- }
- }
-
- return null;
-}
-
// Normalize a Stripe field that may be an id string or an expanded object (or
// absent) to its id. Shared by the webhook handlers.
export function stripeId(
@@ -182,7 +193,9 @@ export function stripeId(
return typeof value === "string" ? value : value.id;
}
-function unixToDate(seconds: number | null | undefined): Date | null {
+// Epoch seconds (Stripe's unit) to Date, or null when absent. Shared by the
+// Vision and Pro subscription sync paths.
+export function unixToDate(seconds: number | null | undefined): Date | null {
if (!seconds) {
return null;
}
diff --git a/site/src/lib/credits/amounts.ts b/site/src/lib/credits/amounts.ts
index 8b17aadc..cce1573b 100644
--- a/site/src/lib/credits/amounts.ts
+++ b/site/src/lib/credits/amounts.ts
@@ -1,5 +1,8 @@
export const zeroCreditMicros = BigInt(0);
export const creditMicrosPerCredit = BigInt("1000000");
+// $1 = 100 cents = 1,000,000 micros, so 1 cent = 10,000 micros. Single source for
+// the Stripe-cents conversion used by subscription allowances and off-session charges.
+export const creditMicrosPerCent = creditMicrosPerCredit / BigInt(100);
export function creditStringToMicros(value: string | undefined) {
const trimmed = value?.trim();
diff --git a/site/src/lib/credits/inference.ts b/site/src/lib/credits/inference.ts
index be8fac4a..baa38693 100644
--- a/site/src/lib/credits/inference.ts
+++ b/site/src/lib/credits/inference.ts
@@ -1,4 +1,4 @@
-import { NextResponse } from "next/server";
+import { NextResponse, after } from "next/server";
import { Prisma, type PrismaClient } from "@/generated/prisma/client";
import { prisma } from "@/lib/prisma";
@@ -421,13 +421,29 @@ export async function recordInferenceUsage(input: InferenceUsageInput) {
);
// After a real charge commits, top up the balance via auto-reload if it fell
- // below the user's threshold. Best-effort and non-blocking: a dynamic import
- // breaks the module cycle (billing -> credits -> billing), and failures never
- // affect the inference response. The grant lands later via the Stripe webhook.
+ // below the user's threshold. Scheduled with next/server `after` so it runs
+ // off the response path AND the serverless runtime keeps the function alive
+ // until it finishes (an un-awaited promise can be dropped after the response).
+ // The dynamic import breaks the module cycle (billing -> credits -> billing);
+ // the post-charge balance is passed in so the trigger needn't re-read it.
if (input.billingMode !== "included" && recorded.creditCostMicros > zeroCreditMicros) {
- void import("@/lib/billing/credit-auto-reload")
- .then((module) => module.maybeTriggerCreditAutoReload(input.userId))
- .catch(() => {});
+ const balanceMicros = recorded.remainingBalanceMicros;
+ try {
+ after(async () => {
+ try {
+ const { maybeTriggerCreditAutoReload } = await import(
+ "@/lib/billing/credit-auto-reload"
+ );
+ await maybeTriggerCreditAutoReload(input.userId, balanceMicros);
+ } catch (error) {
+ console.error("[credit-auto-reload] trigger failed", error);
+ }
+ });
+ } catch (error) {
+ // `after` throws outside a request scope (e.g. a script/test). Don't let
+ // that break usage recording — auto-reload is best-effort.
+ console.error("[credit-auto-reload] could not schedule trigger", error);
+ }
}
return recorded;
diff --git a/site/src/lib/credits/top-up.ts b/site/src/lib/credits/top-up.ts
new file mode 100644
index 00000000..4ec58201
--- /dev/null
+++ b/site/src/lib/credits/top-up.ts
@@ -0,0 +1,19 @@
+// Client-safe credit top-up constants and pure helpers (no server-only imports),
+// shared by the purchase logic, the auto-reload validation, and the settings UI
+// so the presets and bounds can never drift between the buttons and the server
+// checks. Keep this file free of prisma / Stripe imports.
+
+// Presets drive the quick-buy buttons; the custom field accepts any whole-dollar
+// amount in [min, max]. Amounts are whole dollars so they map cleanly to Stripe
+// unit_amount cents and the grant ledger.
+export const creditTopUpPresetsDollars = [5, 25, 50, 100] as const;
+export const creditTopUpMinDollars = 5;
+export const creditTopUpMaxDollars = 2_000;
+
+// Stripe metadata "kind" tags that route a completed payment to a credit grant.
+export const creditTopUpKind = "credit_topup";
+export const creditAutoReloadKind = "credit_topup_autoreload";
+
+export function dollarsToStripeCents(amountDollars: number): number {
+ return Math.round(amountDollars * 100);
+}