diff --git a/lib/gc_index_relay_web/endpoint.ex b/lib/gc_index_relay_web/endpoint.ex index 8609722..d2c1668 100644 --- a/lib/gc_index_relay_web/endpoint.ex +++ b/lib/gc_index_relay_web/endpoint.ex @@ -51,5 +51,6 @@ defmodule GcIndexRelayWeb.Endpoint do plug Plug.MethodOverride plug Plug.Head plug Plug.Session, @session_options + plug GcIndexRelayWeb.Plugs.CORS plug GcIndexRelayWeb.Router end diff --git a/lib/gc_index_relay_web/plugs/cors.ex b/lib/gc_index_relay_web/plugs/cors.ex new file mode 100644 index 0000000..af131da --- /dev/null +++ b/lib/gc_index_relay_web/plugs/cors.ex @@ -0,0 +1,29 @@ +defmodule GcIndexRelayWeb.Plugs.CORS do + @moduledoc """ + CORS plug for the Nostr relay REST API. + + Nostr clients can be hosted on any origin, so this plug allows all origins + on all API routes. Preflight OPTIONS requests are halted here and returned + a 200 before they reach the router. + """ + + import Plug.Conn + + def init(opts), do: opts + + def call(conn, _opts) do + conn + |> put_resp_header("access-control-allow-origin", "*") + |> put_resp_header("access-control-allow-methods", "GET, POST, DELETE, OPTIONS") + |> put_resp_header("access-control-allow-headers", "content-type, authorization") + |> handle_preflight() + end + + defp handle_preflight(%Plug.Conn{method: "OPTIONS"} = conn) do + conn + |> send_resp(200, "") + |> halt() + end + + defp handle_preflight(conn), do: conn +end