Files
accounted/app/api/billing/checkout/route.ts
T
Jakob WennbergandClaude Opus 4.8 c9d9c5fe99 fix(billing): block demo/sandbox accounts from Stripe checkout (#948)
* fix(billing): block demo/sandbox accounts from Stripe checkout

An anonymous demo user on a sandbox company reached POST /api/billing/checkout
and created a live Stripe customer. Neither the checkout nor the portal route
checked is_anonymous or is_sandbox, and withRouteContext lets anonymous users
through (they are authenticated, just anonymously).

Guard both routes on both conditions before any Stripe call: refuse anonymous
users (identity truth, cheap in-memory check) and sandbox companies (matches the
existing lib/sandbox/guard.ts "never charge a token" doctrine). Surface isDemo
on GET /api/billing/status so the client hides the upgrade CTA instead of
showing a button that 403s.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(billing): redact tenant/customer IDs from incident note (CodeRabbit)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 22:16:25 +02:00

92 lines
3.3 KiB
TypeScript

import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { validateBody } from '@/lib/api/validate'
import { createServiceClient } from '@/lib/supabase/server'
import { getStripe, priceIdForPlan } from '@/lib/stripe/client'
import { guardSandbox, sandboxBlockedResponse } from '@/lib/sandbox/guard'
const CheckoutSchema = z.object({
plan: z.enum(['monthly', 'yearly']).default('monthly'),
})
/**
* Create a Stripe subscription Checkout Session and return its hosted URL.
* The client redirects to it; provisioning happens via the webhook on
* checkout.session.completed (never trust the success redirect for fulfilment).
*
* company_subscriptions is read/written via the service client on purpose —
* the row is webhook-owned and not member-readable under RLS; every query
* still filters by the membership-validated companyId.
*/
export const POST = withRouteContext('billing.checkout', async (request, ctx) => {
const { user, supabase, companyId, log } = ctx
// Demo accounts must never reach Stripe. An anonymous user has no real
// identity to bill, and a sandbox company must never charge a token (same
// doctrine as lib/sandbox/guard.ts: no real external side effects). Both
// checks run before any Stripe call: this is the gap that let an anonymous
// demo user create a live Stripe customer.
if (user.is_anonymous) return sandboxBlockedResponse()
const blocked = await guardSandbox(supabase, companyId)
if (blocked) return blocked
const validation = await validateBody(request, CheckoutSchema, {
log,
operation: 'billing.checkout',
})
if (!validation.success) return validation.response
const { plan } = validation.data
const priceId = priceIdForPlan(plan)
if (!priceId) {
return NextResponse.json(
{
error: {
code: 'STRIPE_NOT_CONFIGURED',
message: 'Betalning är inte konfigurerad. Kontakta supporten.',
message_en: 'Stripe price not configured.',
},
},
{ status: 500 },
)
}
const stripe = getStripe()
const service = createServiceClient()
// Reuse the company's Stripe customer if we already created one.
const { data: existing } = await service
.from('company_subscriptions')
.select('stripe_customer_id')
.eq('company_id', companyId)
.maybeSingle()
let customerId = (existing as { stripe_customer_id: string | null } | null)?.stripe_customer_id ?? null
if (!customerId) {
const customer = await stripe.customers.create({
email: user.email ?? undefined,
metadata: { company_id: companyId },
})
customerId = customer.id
await service
.from('company_subscriptions')
.upsert({ company_id: companyId, stripe_customer_id: customerId }, { onConflict: 'company_id' })
}
const appUrl = process.env.NEXT_PUBLIC_APP_URL ?? ''
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
customer: customerId,
line_items: [{ price: priceId, quantity: 1 }],
client_reference_id: companyId,
metadata: { company_id: companyId },
subscription_data: { metadata: { company_id: companyId } },
allow_promotion_codes: true,
success_url: `${appUrl}/settings/billing?success=1`,
cancel_url: `${appUrl}/settings/billing?canceled=1`,
})
return NextResponse.json({ url: session.url })
})