From 979f898880ed18ab9ed1534b7f5a3528f37506c3 Mon Sep 17 00:00:00 2001 From: Ephraim Atta-Duncan Date: Wed, 23 Oct 2024 17:42:58 +0000 Subject: [PATCH] feat: implement cors for all the routes --- apps/openpage-api/app/request-handler.ts | 55 +++++++++++++++++++----- apps/openpage-api/app/route.ts | 1 - 2 files changed, 44 insertions(+), 12 deletions(-) diff --git a/apps/openpage-api/app/request-handler.ts b/apps/openpage-api/app/request-handler.ts index 12e2193e9..9b60dd542 100644 --- a/apps/openpage-api/app/request-handler.ts +++ b/apps/openpage-api/app/request-handler.ts @@ -6,20 +6,38 @@ type RouteHandler> = ( ctx: { params: T }, ) => Promise | Response; +const ALLOWED_ORIGINS = new Set(['documenso.com']); + +const CORS_HEADERS = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type', +}; + function isAllowedOrigin(req: NextRequest): boolean { const referer = req.headers.get('referer'); const host = req.headers.get('host'); - if (referer && host) { - const refererUrl = new URL(referer); - return refererUrl.host === host; - } - if (host?.includes('localhost')) { return true; } - return false; + if (!referer || !host) { + return false; + } + + try { + const refererUrl = new URL(referer); + const hostUrl = new URL(`http://${host}`); + + const isRefererAllowed = ALLOWED_ORIGINS.has(refererUrl.host); + const isHostAllowed = ALLOWED_ORIGINS.has(hostUrl.host); + + return isRefererAllowed || isHostAllowed; + } catch (error) { + console.error('Error parsing URLs:', error); + return false; + } } export function requestHandler>( @@ -28,16 +46,31 @@ export function requestHandler>( return async (req: NextRequest, ctx: { params: T }) => { try { if (!isAllowedOrigin(req)) { - return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + return NextResponse.json( + { error: 'Forbidden' }, + { + status: 403, + headers: CORS_HEADERS, + }, + ); } - const result = await handler(req, ctx); + const response = await handler(req, ctx); - return result; + Object.entries(CORS_HEADERS).forEach(([key, value]) => { + response.headers.set(key, value); + }); + + return response; } catch (error) { console.log(error); - - return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); + return NextResponse.json( + { error: 'Internal Server Error' }, + { + status: 500, + headers: CORS_HEADERS, + }, + ); } }; } diff --git a/apps/openpage-api/app/route.ts b/apps/openpage-api/app/route.ts index d7a3e851b..691524a64 100644 --- a/apps/openpage-api/app/route.ts +++ b/apps/openpage-api/app/route.ts @@ -9,7 +9,6 @@ export function GET(request: NextRequest) { }); return NextResponse.json(apis, { - status: 200, headers: { // TODO: Update for marketing page 'Access-Control-Allow-Origin': '*',