From 4ac83b6e5d847f969da93abdceed2daf3ac2464f Mon Sep 17 00:00:00 2001 From: hq1 Date: Wed, 28 Jun 2023 10:16:32 +0200 Subject: [PATCH] Reconfigure live websocket (#3087) * Dynamically set :domain for the live socket Ref: https://github.com/phoenixframework/phoenix_live_view/pull/2715 * Make runtime config raise before the user ends up in a reconnect loop * hall of shame: remove console.info remnant * Check origin on live websocket * Get rid of single pipe --- assets/js/dashboard/stats/behaviours/funnel.js | 1 - config/runtime.exs | 10 ++++++++++ lib/plausible_web/endpoint.ex | 14 +++++++++++++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/assets/js/dashboard/stats/behaviours/funnel.js b/assets/js/dashboard/stats/behaviours/funnel.js index 34105e3f1..c16ca44ad 100644 --- a/assets/js/dashboard/stats/behaviours/funnel.js +++ b/assets/js/dashboard/stats/behaviours/funnel.js @@ -13,7 +13,6 @@ import LazyLoader from '../../components/lazy-loader' export default function Funnel(props) { - console.info('funnah') const [loading, setLoading] = useState(true) const [visible, setVisible] = useState(false) const [error, setError] = useState(undefined) diff --git a/config/runtime.exs b/config/runtime.exs index e6837454d..22b649029 100644 --- a/config/runtime.exs +++ b/config/runtime.exs @@ -227,6 +227,16 @@ log_failed_login_attempts = websocket_url = get_var_from_path_or_env(config_dir, "WEBSOCKET_URL", "") +if byte_size(websocket_url) > 0 and + not String.ends_with?(URI.new!(websocket_url).host, base_url.host) do + raise """ + Cross-domain websocket authentication is not supported for this server. + + WEBSOCKET_URL=#{websocket_url} - host must be: '#{base_url.host}', + because BASE_URL=#{base_url} so the host is ``. + """ +end + config :plausible, environment: env, mailer_email: mailer_email, diff --git a/lib/plausible_web/endpoint.ex b/lib/plausible_web/endpoint.ex index bd6148b05..a0f5411e0 100644 --- a/lib/plausible_web/endpoint.ex +++ b/lib/plausible_web/endpoint.ex @@ -54,7 +54,11 @@ defmodule PlausibleWeb.Endpoint do plug Plug.Session, @session_options - socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]] + socket "/live", Phoenix.LiveView.Socket, + websocket: [ + check_origin: true, + connect_info: [session: {__MODULE__, :patch_session_opts, []}] + ] plug CORSPlug plug PlausibleWeb.Router @@ -64,4 +68,12 @@ defmodule PlausibleWeb.Endpoint do |> Application.fetch_env!(__MODULE__) |> Keyword.fetch!(:websocket_url) end + + def patch_session_opts() do + # `host()` provided by Phoenix.Endpoint's compilation hooks + # is used to inject the domain - this way we can authenticate + # websocket requests within single root domain, in case websocket_url() + # returns a ws{s}:// scheme (in which case SameSite=Lax is not applicable). + Keyword.put(@session_options, :domain, host()) + end end