@@ -71,6 +71,12 @@ import { createOtelAuthEndpoint } from './otel-auth-endpoint';
7171import { createPublicGraphQLHandler } from './public-graphql-handler' ;
7272import { initSupertokens , oidcIdLookup } from './supertokens' ;
7373
74+ class CorsError extends Error {
75+ constructor ( ) {
76+ super ( 'CORS origin not allowed.' ) ;
77+ }
78+ }
79+
7480export async function main ( ) {
7581 let tracing : TracingInstance | undefined ;
7682
@@ -146,28 +152,41 @@ export async function main() {
146152 } ,
147153 ) ;
148154
149- server . setErrorHandler ( supertokensErrorHandler ( ) ) ;
155+ server . setErrorHandler ( ( err , req , res ) => {
156+ if ( err instanceof CorsError ) {
157+ return res . status ( 403 ) . send ( err . message ) ;
158+ }
159+
160+ return supertokensErrorHandler ( ) ( err , req , res ) ;
161+ } ) ;
150162 await server . register ( cors , ( _ : unknown ) : FastifyCorsOptionsDelegateCallback => {
151163 return ( req , callback ) => {
152- if ( req . headers . origin ?. startsWith ( env . hiveServices . webApp . url ) ) {
153- // We need to treat requests from the web app a bit differently than others.
154- // The web app requires to define the `Access-Control-Allow-Origin` header (not *).
155- callback ( null , {
156- origin : env . hiveServices . webApp . url ,
157- credentials : true ,
158- methods : [ 'GET' , 'POST' , 'PUT' , 'DELETE' , 'OPTIONS' ] ,
159- allowedHeaders : [
160- 'Content-Type' ,
161- 'graphql-client-version' ,
162- 'graphql-client-name' ,
163- 'x-request-id' ,
164- ...supertokens . getAllCORSHeaders ( ) ,
165- ] ,
164+ // For CLI user we do not have a origin
165+ if ( req . headers . origin == null ) {
166+ // this is the easiest way to omit all cors headers for our version of the cors plugin.
167+ return callback ( null , {
168+ origin : [ ] ,
166169 } ) ;
167- return ;
168170 }
169171
170- callback ( null , { } ) ;
172+ if ( req . headers . origin !== env . hiveServices . webApp . url ) {
173+ return callback ( new CorsError ( ) ) ;
174+ }
175+
176+ // We need to treat requests from the web app a bit differently than others.
177+ // The web app requires to define the `Access-Control-Allow-Origin` header (not *).
178+ callback ( null , {
179+ origin : env . hiveServices . webApp . url ,
180+ credentials : true ,
181+ methods : [ 'GET' , 'POST' , 'PUT' , 'DELETE' , 'OPTIONS' ] ,
182+ allowedHeaders : [
183+ 'Content-Type' ,
184+ 'graphql-client-version' ,
185+ 'graphql-client-name' ,
186+ 'x-request-id' ,
187+ ...supertokens . getAllCORSHeaders ( ) ,
188+ ] ,
189+ } ) ;
171190 } ;
172191 } ) ;
173192
0 commit comments