Files
MattssonandClaude Fable 5.1 d29a5bda14 fix(auth): resolve auth-link hosts from the brands table, drop NEXT_PUBLIC_WHITELABEL_DOMAINS (#2376)
* fix(auth): resolve auth-link hosts from the brands table, drop NEXT_PUBLIC_WHITELABEL_DOMAINS

Password reset, invite, email change and signup links now resolve the
request host against brands.domain server-side. The env var was a second
copy of that registry compiled into the browser; every new brand needed
the row, the env var, the GoTrue allowlist and a redeploy, and two
partners shipped with the env var stale, so their reset mails went out
canonical-branded to the canonical host.

- New POST /api/auth/password-reset: the login page no longer calls
  GoTrue directly, so the browser carries no domain list.
- lib/domains/trusted-app-origin.ts is async and registry-backed; it
  also trusts this deployment's own VERCEL_URL / VERCEL_BRANCH_URL so
  previews keep sending links to themselves.
- Signup shares the same resolver instead of following the raw host.
- Docs and .env.example describe the single registry; GoTrue keeps the
  redirect allowlist as backstop (hosted: *.accounted.se wildcard).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUNB7qjua8EUaJmZgfFscx

* fix(auth): await the async origin resolver in the billing routes merged from main

PR #2370 added resolveRequestAppOrigin callers in billing/checkout and
billing/portal after this branch made the resolver async. Await them and
move their tests from the removed env var to the brands mock; update the
login source-assert test to the server-routed reset.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUNB7qjua8EUaJmZgfFscx

* fix(auth): refuse auth links on a failed brand lookup, keep local dev hosts, correct GoTrue allowlist docs

Skeptic and CI findings on #2376, one pass:

- A failed brands lookup now throws BrandLookupFailedError (TRANSIENT_ERROR,
  503, retryable) instead of falling back to the canonical origin: a
  canonical link is the wrong-brand mail this PR removes. Password reset
  and email change answer 503 themselves; withRouteContext routes map the
  code.
- A local canonical (dev) trusts other local hosts and ports on the same
  scheme, so lane servers on 3001-3003 confirm signups on themselves.
- GoTrue matches the full redirect_to including the query and `*` stops
  at `.` and `/`: docs and decision line now prescribe
  https://*.accounted.se/auth/callback** and https://*.accounted.se/invite/**.
- The Turnstile contract test asserts the server-routed reset forwards
  the captcha token (it still asserted the removed browser call).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUNB7qjua8EUaJmZgfFscx

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 15:12:22 +02:00

155 lines
6.4 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'
import { resolveRequestAppOrigin } from '@/lib/domains/trusted-app-origin'
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, and read
// the trial expiry for the deferred-first-charge decision below. Independent
// reads, so one round-trip batch.
const [{ data: existing }, { data: trialGrant, error: trialGrantError }] = await Promise.all([
service
.from('company_subscriptions')
.select('stripe_customer_id')
.eq('company_id', companyId)
.maybeSingle(),
service
.from('capability_grants')
.select('expires_at')
.eq('company_id', companyId)
.eq('source', 'trial')
.order('expires_at', { ascending: false })
.limit(1)
.maybeSingle(),
])
// Fail closed on an uncertain trial state: proceeding on a lookup error
// would silently charge immediately after the UI promised "0 kr idag".
if (trialGrantError) {
return NextResponse.json(
{
error: {
code: 'TRIAL_LOOKUP_FAILED',
message: 'Kunde inte läsa din provperiod. Försök igen om en stund.',
message_en: 'Could not resolve the trial state. Try again shortly.',
},
},
{ status: 500 },
)
}
// Defer the first charge to the end of an active trial. The company already
// holds the paid capabilities free until then, so charging at checkout would
// bill for days it already has; instead the subscription starts as
// 'trialing' (which grants access via the webhook, see subscription-sync)
// and the first charge lands when the product trial ends. Stripe Checkout
// requires trial_end to be at least 48h in the future; closer than that, or
// with no active trial, billing starts immediately.
const trialExpiry = (trialGrant as { expires_at: string | null } | null)?.expires_at ?? null
const trialExpiryMs = trialExpiry ? new Date(trialExpiry).getTime() : null
const STRIPE_MIN_TRIAL_END_MS = 49 * 3600 * 1000 // Stripe's 48h floor + 1h clock margin
const trialEnd =
trialExpiryMs && trialExpiryMs - Date.now() > STRIPE_MIN_TRIAL_END_MS
? Math.floor(trialExpiryMs / 1000)
: undefined
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' })
}
// Return the user to the host they started on. Sessions are per domain, so
// sending a white-label user back to the canonical app would land them on a
// foreign-branded login with no session. The origin is resolved against the
// brands table; an unknown or spoofed host falls back to the
// canonical app URL. The paths stay fixed: never accept a caller-supplied
// return URL here.
const appOrigin = await resolveRequestAppOrigin(request)
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
customer: customerId,
line_items: [{ price: priceId, quantity: 1 }],
// Swedish VAT: the Price is net (tax_behavior=exclusive in Stripe), so Stripe
// Tax adds 25% moms for SE customers and applies reverse charge for EU-B2B with
// a valid VAT number. automatic_tax carries onto the created subscription, so
// renewals (and the first charge after a deferred trial) stay taxed. The rate
// can only compute with a customer address, and a compliant momsfaktura needs
// it too; customer_update persists the address + tax id onto the pre-created
// customer for future invoices.
automatic_tax: { enabled: true },
tax_id_collection: { enabled: true },
billing_address_collection: 'required',
customer_update: { name: 'auto', address: 'auto' },
client_reference_id: companyId,
metadata: { company_id: companyId },
subscription_data: {
metadata: { company_id: companyId },
...(trialEnd ? { trial_end: trialEnd } : {}),
},
allow_promotion_codes: true,
success_url: `${appOrigin}/settings/billing?success=1`,
cancel_url: `${appOrigin}/settings/billing?canceled=1`,
})
return NextResponse.json({ url: session.url })
})