11import { Hono } from 'hono' ;
2+ import type { Context } from 'hono' ;
23import { eq } from 'drizzle-orm' ;
34import { db } from '../db/index.js' ;
45import * as schema from '../db/schema.js' ;
@@ -13,6 +14,21 @@ import {
1314 runAutoTopupSweep ,
1415} from '../auth/billing.js' ;
1516
17+ function getRequestOrigin ( c : Context ) : string {
18+ const origin = c . req . header ( 'Origin' ) || c . req . header ( 'Referer' ) ;
19+ if ( origin ) {
20+ const normalized = origin . replace ( / \/ + $ / , '' ) ;
21+ try {
22+ const parsed = new URL ( normalized . startsWith ( 'http' ) ? normalized : `https://${ normalized } ` ) ;
23+ const candidate = parsed . origin ;
24+ if ( config . corsAllowedOrigins . includes ( candidate ) ) {
25+ return candidate ;
26+ }
27+ } catch { }
28+ }
29+ return config . corsAllowedOrigins [ 0 ] ;
30+ }
31+
1632export const billingRoutes = new Hono ( ) ;
1733
1834billingRoutes . post ( '/checkout' , async ( c ) => {
@@ -39,14 +55,15 @@ billingRoutes.post('/checkout', async (c) => {
3955
4056 const amountCents = amountDollars * 100 ;
4157
58+ const returnOrigin = getRequestOrigin ( c ) ;
4259 const checkoutSession = await dodoPayments . checkoutSessions . create ( {
4360 product_cart : [ { product_id : config . dodoCreditProductId , quantity : amountDollars } ] ,
4461 customer : {
4562 email : session . user . email ,
4663 name : session . user . name || session . user . email . split ( '@' ) [ 0 ] ,
4764 } ,
4865 metadata : { amount_cents : String ( amountCents ) } ,
49- return_url : `${ config . corsAllowedOrigins [ 0 ] } /billing?checkout=success` ,
66+ return_url : `${ returnOrigin } /billing?checkout=success` ,
5067 } ) ;
5168
5269 return c . json ( { checkout_url : checkoutSession . checkout_url } ) ;
@@ -181,10 +198,11 @@ autoTopupRoutes.post('/setup', async (c) => {
181198 ? { customer_id : customerId }
182199 : { email, name : session . user . name || email . split ( '@' ) [ 0 ] } ;
183200
201+ const returnOrigin = getRequestOrigin ( c ) ;
184202 const checkoutSession = await dodoPayments . checkoutSessions . create ( {
185203 product_cart : [ { product_id : config . dodoAutoTopupProductId , quantity : 1 } ] ,
186204 customer : customerRef as any ,
187- return_url : `${ config . corsAllowedOrigins [ 0 ] } /billing?auto_topup=success` ,
205+ return_url : `${ returnOrigin } /billing?auto_topup=success` ,
188206 subscription_data : {
189207 on_demand : {
190208 mandate_only : true ,
0 commit comments