diff --git a/lib/philomena_web/plugs/content_security_policy_plug.ex b/lib/philomena_web/plugs/content_security_policy_plug.ex index 854cb613..2ef5b819 100644 --- a/lib/philomena_web/plugs/content_security_policy_plug.ex +++ b/lib/philomena_web/plugs/content_security_policy_plug.ex @@ -25,8 +25,8 @@ defmodule PhilomenaWeb.ContentSecurityPolicyPlug do csp_config = [ {:default_src, ["'self'"]}, - {:script_src, [default_script_src() | script_src]}, - {:connect_src, [default_connect_src()]}, + {:script_src, [default_script_src(conn.host) | script_src]}, + {:connect_src, [default_connect_src(conn.host)]}, {:style_src, [default_style_src() | style_src]}, {:object_src, ["'none'"]}, {:frame_ancestors, ["'none'"]}, @@ -66,10 +66,31 @@ defmodule PhilomenaWeb.ContentSecurityPolicyPlug do defp cdn_uri, do: Application.get_env(:philomena, :cdn_host) |> to_uri() defp camo_uri, do: Application.get_env(:philomena, :camo_host) |> to_uri() - defp default_script_src, do: vite_hmr?(do: "'self' localhost:5173", else: "'self'") + # Use the "current host" in vite HMR mode for whatever the "current host" is. + # Usually it's `localhost`, but it may be some other private IP address, that + # you use to test the frontend on a mobile device connected via a local Wi-Fi. + defp default_script_src(host) do + # Workaround for a compile warning where `host` variable is unused if we + # inline the if branches into the `vite_hmr?` macro. + is_vite_hmr = vite_hmr?(do: true, else: false) - defp default_connect_src, - do: vite_hmr?(do: "'self' localhost:5173 ws://localhost:5173", else: "'self'") + if is_vite_hmr do + "'self' #{host}:5173" + else + "'self'" + end + end + + defp default_connect_src(host) do + # Same workaround as in `default_script_src/1` + is_vite_hmr = vite_hmr?(do: true, else: false) + + if is_vite_hmr do + "'self' #{host}:5173 ws://#{host}:5173" + else + "'self'" + end + end defp default_style_src, do: vite_hmr?(do: "'self' 'unsafe-inline'", else: "'self'")