earthstar-project / replica-server

An always-online Earthstar peer for your shares.
GNU Lesser General Public License v3.0
5 stars 2 forks source link

ExtentionSyncHttp blocked due to CORS issues #8

Open basham opened 2 years ago

basham commented 2 years ago

I'm syncing a local Deno replica server (v3.0.0) with a local browser app (Earthstar v9.3.2), using the ExtentionSyncHttp extension. However, when the browser starts to sync, it immediately fails due to CORS.

Access to fetch at 'http://localhost:8080/earthstar-api/v2/from/peer:0.32274012864160450.07687314859790972' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Chrome Dev Tools elaborates on this issue:

A cross-origin resource sharing (CORS) request was blocked because the response to the associated preflight request failed, had an unsuccessful HTTP status code, and/or was a redirect.

To fix this issue, ensure all CORS preflight OPTIONS requests are answered with a successful HTTP status code (2xx) and do not redirect.

I solved this by using a modified version of ExtentionSyncHttp. Before getting the response object from the syncer, I added this conditional:

if (req.method === 'OPTIONS') {
  return new Response(null, {
    status: 200,
    headers: {
      'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST'
    }
  })
}

There is likely a cleaner way to implement it. I don't know if there are other side cases to consider. But this worked for me.

sgwilym commented 2 years ago

Oh, right. This is something ExtensionServeContent lets you configure, we should just do that for the other extensions too.

Maybe this should be something you configure on the server, and the server modifies the response's CORS headers before sending it out.

johanbove commented 1 year ago

Dealing with the "OPTIONS" request could be added to the extensions/sync_http.ts code as this will also fix the, unfortunately, still existing CORS issue when running a replica server on Glitch. See screenshot:

image

johanbove commented 1 year ago

One good way to solve this too is that - if you can - to run your web app within a docker image which uses nginx as proxy web server and then you can do a proxy_pass to the Glitch domain from a "local" folder, like "/api"; You will avoid CORS issues because to the browser the requests will look like it's the same domain.