@@ -181,11 +181,34 @@ const processAndGetOrCreateSpace = async (
181181 return result ;
182182} ;
183183
184+ // The following lines are duplicated from apps/website/app/utils/llm/cors.ts
185+ const allowedOrigins = [ "https://roamresearch.com" , "http://localhost:3000" ] ;
186+
187+ const isVercelPreviewUrl = ( origin : string ) : boolean =>
188+ / ^ h t t p s : \/ \/ .* - d i s c o u r s e - g r a p h - [ a - z 0 - 9 ] + \. v e r c e l \. a p p $ / . test ( origin )
189+
190+ const isAllowedOrigin = ( origin : string ) : boolean =>
191+ allowedOrigins . some ( ( allowed ) => origin . startsWith ( allowed ) ) ||
192+ isVercelPreviewUrl ( origin ) ;
193+
184194// @ts -ignore Deno is not visible to the IDE
185195Deno . serve ( async ( req ) => {
196+ const origin = req . headers . get ( "origin" ) ;
197+ const originIsAllowed = origin && isAllowedOrigin ( origin ) ;
198+ if ( req . method === "OPTIONS" ) {
199+ return new Response ( null , {
200+ status : 204 ,
201+ headers : {
202+ ...( originIsAllowed ? { "Access-Control-Allow-Origin" : origin } : { } ) ,
203+ "Access-Control-Allow-Methods" : "GET, POST, OPTIONS" ,
204+ "Access-Control-Allow-Headers" :
205+ "Content-Type, Authorization, x-vercel-protection-bypass, x-client-info, apikey" ,
206+ "Access-Control-Max-Age" : "86400" ,
207+ } ,
208+ } ) ;
209+ }
210+
186211 const input = await req . json ( ) ;
187- // TODO: We should check whether the request comes from a vetted source, like
188- // the roam or obsidian plugin. A combination of CSRF, headers, etc.
189212 // @ts -ignore Deno is not visible to the IDE
190213 const url = Deno . env . get ( "SUPABASE_URL" ) ;
191214 // @ts -ignore Deno is not visible to the IDE
@@ -207,9 +230,20 @@ Deno.serve(async (req) => {
207230 } ) ;
208231 }
209232
210- return new Response ( JSON . stringify ( data ) , {
233+ const res = new Response ( JSON . stringify ( data ) , {
211234 headers : { "Content-Type" : "application/json" } ,
212235 } ) ;
236+
237+ if ( originIsAllowed ) {
238+ res . headers . set ( "Access-Control-Allow-Origin" , origin as string ) ;
239+ res . headers . set ( "Access-Control-Allow-Methods" , "GET, POST, OPTIONS" ) ;
240+ res . headers . set (
241+ "Access-Control-Allow-Headers" ,
242+ "Content-Type, Authorization, x-vercel-protection-bypass, x-client-info, apikey" ,
243+ ) ;
244+ }
245+
246+ return res ;
213247} ) ;
214248
215249/* To invoke locally:
0 commit comments