Skip to content

Commit

Permalink
fix: handle options req for cors preflight (#137)
Browse files Browse the repository at this point in the history
When we use the Console App to create a space, it will send an OPTIONS,
and then a POST request to the UCAN Invocation Server, which is behind
the CORS handler, and that CORS Handler doesn't support OPTIONS requests
for CORS preflight. I've added a new handler to process that OPTIONS
request.
  • Loading branch information
fforbeck authored Jan 7, 2025
1 parent c60037d commit 79de5b1
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ import {
withLocator,
withUcanInvocationHandler,
withDelegationsStorage,
withDelegationStubs
withDelegationStubs,
withOptionsRequest
} from './middleware/index.js'
import { instrument } from '@microlabs/otel-cf-workers'
import { NoopSpanProcessor } from '@opentelemetry/sdk-trace-base'
Expand All @@ -53,6 +54,7 @@ const middleware = composeMiddleware(
// Prepare the Context for all types of requests
withCdnCache,
withContext,
withOptionsRequest,
withCorsHeaders,
withVersionHeader,
withErrorHandler,
Expand Down
1 change: 1 addition & 0 deletions src/middleware/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export { withDelegationStubs } from './withDelegationStubs.js'
export { withGatewayIdentity } from './withGatewayIdentity.js'
export { withUcanInvocationHandler } from './withUcanInvocationHandler.js'
export { withDelegationsStorage } from './withDelegationsStorage.js'
export { withOptionsRequest } from './withOptionsRequest.js'
20 changes: 20 additions & 0 deletions src/middleware/withOptionsRequest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @import { Middleware, Context } from '@web3-storage/gateway-lib'
*/

/**
* Handles OPTIONS requests for CORS preflight.
* @type {Middleware<Context, Context, {}>}
*/
export function withOptionsRequest (handler) {
return async (request, env, ctx) => {
if (request.method === 'OPTIONS') {
const headers = new Headers()
headers.set('Access-Control-Allow-Origin', '*')
headers.set('Access-Control-Allow-Methods', 'GET, HEAD, POST, OPTIONS')
headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')
return new Response(null, { headers, status: 204 })
}
return handler(request, env, ctx)
}
}

0 comments on commit 79de5b1

Please sign in to comment.