import { and, desc, eq, isNull, type SQL } from 'drizzle-orm'; import { Hono } from 'hono'; import { z } from 'zod'; import { planIdFromPriceId, plans } from '../../../shared/pricing'; import { getBillingProvider, getProviderPriceIds, isBillingConfigured } from '../../billing'; import { adminDb } from '../../db/client'; import { customers, organizations, subscriptions } from '../../db/schema'; import { isoTimestamp } from '../../db/values'; import { env } from '../../lib/env'; import { sanitizeError } from '../../lib/errors'; import { createRateLimiter } from '../../lib/rate-limiter'; import { requireAal2 } from '../../middleware/requireAal2'; import { isBillingTargetType, requireOrgRole } from '../../middleware/requireOrgRole'; import type { HonoVariables } from '../../types'; // Organization billing actions require an owner/admin of the target org. const ORG_BILLING_ROLES = ['OWNER', 'ADMIN']; const billingRoutes = new Hono<{ Variables: HonoVariables }>(); // Strict limiters on the provider-cost routes — each creates a Stripe/Paddle/ // Polar checkout/setup/portal object, so the app-wide 100/min/IP still allows // 100 provider objects/min. Registered BEFORE the route handlers (Hono applies // middleware in registration order). Authed + org-role gated already, so a // modest 20/15min is ample for legitimate use. for (const p of ['/checkout', '/setup', '/portal']) { billingRoutes.use(p, createRateLimiter({ windowMs: 15 * 60 * 1000, max: 20 })); } // ============================================================================ // VALIDATION SCHEMAS // ============================================================================ const checkoutSchema = z.object({ priceId: z.string().min(1, 'Price ID is required'), type: z.enum(['user', 'organization']), organizationId: z.string().uuid().optional(), successUrl: z.string().url().optional(), cancelUrl: z.string().url().optional(), }); const portalSchema = z.object({ type: z.enum(['user', 'organization']), organizationId: z.string().uuid().optional(), returnUrl: z.string().url().optional(), }); // ============================================================================ // HELPER FUNCTIONS // ============================================================================ /** * Validate that a redirect URL is same-origin to prevent open redirects. * Returns the URL if valid, or null if it's external. */ function validateRedirectUrl(url: string, baseUrl: string): string | null { try { const parsed = new URL(url); const base = new URL(baseUrl); if (parsed.origin === base.origin) return url; return null; } catch { return null; } } /** * The customers-row predicate for a billing target. Each type is matched * explicitly and anything else fails closed: an unknown type, or an * organization target without an id, yields null so no caller can run an * org-scoped (or unscoped) service-role query by accident. */ function customerOwner(type: string, userId: string, organizationId?: string): SQL | null { if (type === 'user') { return and(eq(customers.userId, userId), isNull(customers.organizationId)) ?? null; } if (type === 'organization' && organizationId) { return and(eq(customers.organizationId, organizationId), isNull(customers.userId)) ?? null; } return null; } /** * Get or create a billing customer for a user or organization. * * Uses the active billing provider to create the customer in the external * system, then stores the provider's customer ID in the `stripe_customer_id` * column (which holds any provider's customer ID despite its name). */ async function getOrCreateCustomer( type: 'user' | 'organization', userId: string, email: string, organizationId?: string ): Promise<{ customerId: string; providerCustomerId: string }> { const provider = getBillingProvider(); if (type === 'organization' && !organizationId) { throw new Error('Organization ID is required for organization billing'); } // The customer row for this user (personal) or organization const owner = customerOwner(type, userId, organizationId); if (!owner) { // Unreachable via the typed signature; fail closed rather than run an // unscoped customers query with the service-role client. throw new Error('Invalid billing target type'); } let existingCustomer: { id: string; stripeCustomerId: string } | undefined; try { [existingCustomer] = await adminDb .select({ id: customers.id, stripeCustomerId: customers.stripeCustomerId }) .from(customers) .where(owner) .limit(1); } catch (fetchError) { // The cause, not its message: a Drizzle message carries the query params. throw new Error('Failed to fetch customer', { cause: fetchError }); } // Return existing customer if found if (existingCustomer) { return { customerId: existingCustomer.id, providerCustomerId: existingCustomer.stripeCustomerId, }; } // Get organization name if applicable let customerName = email; if (type === 'organization' && organizationId) { const [org] = await adminDb .select({ name: organizations.name }) .from(organizations) .where(eq(organizations.id, organizationId)) .limit(1); if (org) { customerName = org.name; } } // Create customer in the billing provider const providerCustomerId = await provider.createCustomer({ email, name: customerName, metadata: { type, user_id: userId, organization_id: organizationId || '', }, }); // Create database record // NOTE: stripe_customer_id column stores the provider's customer ID regardless // of which provider is active. The column name is kept for backward compatibility. let newCustomer: { id: string; stripeCustomerId: string }; try { [newCustomer] = await adminDb .insert(customers) .values( type === 'user' ? { userId, stripeCustomerId: providerCustomerId, email } : { organizationId, stripeCustomerId: providerCustomerId, email } ) .returning({ id: customers.id, stripeCustomerId: customers.stripeCustomerId }); } catch (insertError) { // Clean up provider customer if DB insert fails try { await provider.deleteCustomer(providerCustomerId); } catch { // Best-effort cleanup; the orphaned customer can be cleaned up manually } throw new Error('Failed to create customer record', { cause: insertError }); } return { customerId: newCustomer.id, providerCustomerId: newCustomer.stripeCustomerId, }; } // ============================================================================ // STRIPE PRICE CACHE (kept for backward compatibility with Stripe subscriptions) // ============================================================================ const priceCache = new Map(); const PRICE_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour (prices rarely change) async function getCachedPrice(priceId: string): Promise { const cached = priceCache.get(priceId); if (cached && Date.now() < cached.expiresAt) { return cached.data; } // Price caching via direct Stripe API is only available for the Stripe provider. // For other providers, the subscription endpoint uses getSubscription() instead. const provider = getBillingProvider(); if (provider.type !== 'stripe') { return null; } // Dynamic import to avoid loading stripe module when not needed const { getStripe } = await import('../../lib/stripe'); const stripe = getStripe(); const price = await stripe.prices.retrieve(priceId, { expand: ['product'] }); priceCache.set(priceId, { data: price, expiresAt: Date.now() + PRICE_CACHE_TTL_MS }); return price; } // ============================================================================ // BILLING STATUS // ============================================================================ /** * Check if billing is configured */ billingRoutes.get('/status', (c) => { return c.json({ configured: isBillingConfigured(), provider: env.BILLING_PROVIDER, }); }); // ============================================================================ // PRICES ENDPOINT // ============================================================================ /** * Get available plans and their price IDs for the active provider */ billingRoutes.get('/prices', (c) => { const configured = isBillingConfigured(); const priceIds = getProviderPriceIds(); const priceMap: Record = {}; if (configured) { if (priceIds.starter) { priceMap.starter = { monthly: priceIds.starter }; } if (priceIds.pro) { priceMap.pro = { monthly: priceIds.pro }; } } return c.json({ configured, provider: env.BILLING_PROVIDER, plans: plans.map((plan) => ({ ...plan, // Keep stripePriceIds key for backward compatibility with existing clients stripePriceIds: priceMap[plan.id] ?? null, priceIds: priceMap[plan.id] ?? null, })), }); }); // ============================================================================ // SUBSCRIPTION ENDPOINTS // ============================================================================ /** * Get current subscription for user or organization. * * SECURITY: requireOrgRole enforces org membership before this handler runs, so * a caller cannot read another organization's subscription by supplying an * arbitrary organizationId (the previous IDOR). */ billingRoutes.get('/subscription', requireOrgRole(ORG_BILLING_ROLES), async (c) => { const user = c.get('user'); if (!user) { return c.json({ error: 'Unauthorized' }, 401); } if (!isBillingConfigured()) { return c.json({ error: 'Billing is not configured' }, 503); } // Strict allowlist (defense in depth; requireOrgRole also rejects). Anything // that is not 'user' must never fall through to the org branch below. const type = c.req.query('type') || 'user'; if (!isBillingTargetType(type)) { return c.json({ error: 'Invalid type' }, 400); } const organizationId = c.req.query('organizationId'); try { if (type === 'organization' && !organizationId) { return c.json({ error: 'Organization ID is required' }, 400); } // The customer row for this user (personal) or organization. The org // branch is explicit: only type === 'organization' reaches it. const owner = customerOwner(type, user.id, organizationId); if (!owner) { return c.json({ error: 'Invalid type' }, 400); } const [customer] = await adminDb .select({ id: customers.id, stripeCustomerId: customers.stripeCustomerId }) .from(customers) .where(owner) .limit(1); if (!customer) { return c.json({ subscription: null, status: 'none', }); } // Get subscription from database (newest active one) const [subscription] = await adminDb .select() .from(subscriptions) .where(and(eq(subscriptions.customerId, customer.id), eq(subscriptions.status, 'active'))) .orderBy(desc(subscriptions.createdAt)) .limit(1); if (!subscription) { return c.json({ subscription: null, status: 'none', }); } const providerPriceIds = getProviderPriceIds(); // Try to get price details from provider or use cached Stripe price const provider = getBillingProvider(); let priceInfo: { unitAmount: number; currency: string; interval: string } | null = null; let productInfo: { id: string; name: string } | null = null; if (provider.type === 'stripe') { // Use the existing Stripe price cache for backward compatibility const price = (await getCachedPrice(subscription.stripePriceId)) as { id: string; unit_amount: number | null; currency: string; recurring: { interval: string } | null; product: unknown; } | null; if (price) { priceInfo = { unitAmount: price.unit_amount ?? 0, currency: price.currency, interval: price.recurring?.interval ?? 'month', }; const product = price.product as { id: string; name: string } | undefined; productInfo = product ? { id: product.id, name: product.name } : null; } } else { // For Paddle/Polar, fetch subscription details from the provider API try { const subInfo = await provider.getSubscription({ customerId: customer.stripeCustomerId, subscriptionId: subscription.stripeSubscriptionId, }); if (subInfo) { priceInfo = subInfo.price; productInfo = subInfo.product; } } catch { // Fall back to database data if provider API is unreachable } } const resolvedPlanId = planIdFromPriceId(subscription.stripePriceId, providerPriceIds); return c.json({ subscription: { id: subscription.id, status: subscription.status, priceId: subscription.stripePriceId, planId: resolvedPlanId, currentPeriodEnd: isoTimestamp(subscription.currentPeriodEnd), cancelAtPeriodEnd: subscription.cancelAtPeriodEnd, product: productInfo, price: priceInfo ? { id: subscription.stripePriceId, unitAmount: priceInfo.unitAmount, currency: priceInfo.currency, interval: priceInfo.interval, } : null, }, status: subscription.status, }); } catch (error) { return c.json({ error: sanitizeError(error, 'Failed to fetch subscription') }, 500); } }); // ============================================================================ // CHECKOUT // ============================================================================ /** * Create a checkout session via the active billing provider */ billingRoutes.post('/checkout', requireAal2, requireOrgRole(ORG_BILLING_ROLES), async (c) => { const user = c.get('user'); if (!user) { return c.json({ error: 'Unauthorized' }, 401); } if (!isBillingConfigured()) { return c.json({ error: 'Billing is not configured' }, 503); } // Parse and validate request body. Organization access is enforced by the // requireOrgRole middleware above (which reads the same cached body). let body: z.infer; try { const rawBody = await c.req.json(); const result = checkoutSchema.safeParse(rawBody); if (!result.success) { const errors = result.error.issues.map((e: { message: string }) => e.message).join(', '); return c.json({ error: errors }, 400); } body = result.data; } catch { return c.json({ error: 'Invalid JSON body' }, 400); } try { const provider = getBillingProvider(); // Get or create customer (user.email guaranteed for authenticated users) const { providerCustomerId } = await getOrCreateCustomer( body.type, user.id, user.email ?? '', body.organizationId ); // Default URLs - validate user-supplied URLs are same-origin to prevent open redirects const baseUrl = env.NODE_ENV === 'production' ? process.env.SITE_URL : 'http://localhost:5173'; const defaultSuccessUrl = `${baseUrl}/settings/billing?success=true`; const defaultCancelUrl = `${baseUrl}/settings/billing?canceled=true`; const successUrl = (body.successUrl && baseUrl ? validateRedirectUrl(body.successUrl, baseUrl) : null) || defaultSuccessUrl; const cancelUrl = (body.cancelUrl && baseUrl ? validateRedirectUrl(body.cancelUrl, baseUrl) : null) || defaultCancelUrl; // Create checkout session via the provider const result = await provider.createCheckout({ customerId: providerCustomerId, priceId: body.priceId, successUrl, cancelUrl, metadata: { type: body.type, user_id: user.id, organization_id: body.organizationId || '', }, }); return c.json({ sessionId: result.sessionId, url: result.url, }); } catch (error) { return c.json({ error: sanitizeError(error, 'Failed to create checkout session') }, 500); } }); // ============================================================================ // SETUP (add payment method without subscribing — Stripe-only feature) // ============================================================================ const setupSchema = z.object({ type: z.enum(['user', 'organization']), organizationId: z.string().uuid().optional(), }); /** * Create a Stripe Checkout session in setup mode to collect a payment method. * * NOTE: This endpoint is Stripe-specific. Paddle and Polar handle payment * method collection differently (during checkout or via their portal). * For non-Stripe providers, this endpoint returns 501. */ billingRoutes.post('/setup', requireAal2, requireOrgRole(ORG_BILLING_ROLES), async (c) => { const user = c.get('user'); if (!user) { return c.json({ error: 'Unauthorized' }, 401); } if (!isBillingConfigured()) { return c.json({ error: 'Billing is not configured' }, 503); } // Setup mode is only supported by Stripe const provider = getBillingProvider(); if (provider.type !== 'stripe') { return c.json( { error: 'Setup mode is only supported with Stripe. Use the customer portal instead.' }, 501 ); } // Organization access is enforced by requireOrgRole above. let body: z.infer; try { const rawBody = await c.req.json(); const result = setupSchema.safeParse(rawBody); if (!result.success) { const errors = result.error.issues.map((e: { message: string }) => e.message).join(', '); return c.json({ error: errors }, 400); } body = result.data; } catch { return c.json({ error: 'Invalid JSON body' }, 400); } try { // Import Stripe directly for setup mode (Stripe-specific feature) const { getStripe } = await import('../../lib/stripe'); const stripe = getStripe(); const { providerCustomerId } = await getOrCreateCustomer( body.type, user.id, user.email ?? '', body.organizationId ); const baseUrl = env.NODE_ENV === 'production' ? process.env.SITE_URL : 'http://localhost:5173'; const returnUrl = `${baseUrl}/settings/billing`; const session = await stripe.checkout.sessions.create({ customer: providerCustomerId, mode: 'setup', allowed_payment_method_types: ['card'], success_url: `${returnUrl}?setup=success`, cancel_url: `${returnUrl}?setup=canceled`, metadata: { type: body.type, user_id: user.id, organization_id: body.organizationId || '', }, }); return c.json({ sessionId: session.id, url: session.url, }); } catch (error) { return c.json({ error: sanitizeError(error, 'Failed to create setup session') }, 500); } }); // ============================================================================ // CUSTOMER PORTAL // ============================================================================ /** * Create a customer portal session via the active billing provider */ billingRoutes.post('/portal', requireAal2, requireOrgRole(ORG_BILLING_ROLES), async (c) => { const user = c.get('user'); if (!user) { return c.json({ error: 'Unauthorized' }, 401); } if (!isBillingConfigured()) { return c.json({ error: 'Billing is not configured' }, 503); } // Parse and validate request body. Organization access is enforced by the // requireOrgRole middleware above. let body: z.infer; try { const rawBody = await c.req.json(); const result = portalSchema.safeParse(rawBody); if (!result.success) { const errors = result.error.issues.map((e: { message: string }) => e.message).join(', '); return c.json({ error: errors }, 400); } body = result.data; } catch { return c.json({ error: 'Invalid JSON body' }, 400); } try { // Find existing customer const owner = customerOwner(body.type, user.id, body.organizationId); if (!owner) { return c.json({ error: 'Organization ID is required for organization billing' }, 400); } let customer: { stripeCustomerId: string } | undefined; try { [customer] = await adminDb .select({ stripeCustomerId: customers.stripeCustomerId }) .from(customers) .where(owner) .limit(1); } catch (fetchError) { return c.json({ error: sanitizeError(fetchError, 'Failed to fetch customer') }, 500); } if (!customer) { return c.json({ error: 'No billing account found. Please subscribe first.' }, 404); } const provider = getBillingProvider(); const baseUrl = env.NODE_ENV === 'production' ? process.env.SITE_URL : 'http://localhost:5173'; const defaultReturnUrl = `${baseUrl}/settings/billing`; const returnUrl = (body.returnUrl && baseUrl ? validateRedirectUrl(body.returnUrl, baseUrl) : null) || defaultReturnUrl; const result = await provider.createPortalSession({ customerId: customer.stripeCustomerId, returnUrl, }); return c.json({ url: result.url, }); } catch (error) { return c.json({ error: sanitizeError(error, 'Failed to create portal session') }, 500); } }); // getOrCreateCustomer is exported for its tests (billing-customer.test.ts). export { billingRoutes, getOrCreateCustomer };