authoravatarclover caruso<git@paperclover.net>2026-10-13 19:57:38-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-21 02:52:29-07:00
log0c140d8732c4b3e915908e6d5c3b033031b8c087
treea63373661ade89330d6dd382f27c9836df4b35b7
parent907a0c3cbb0d2f4d6ad1fbbd59dca3ba8c1a8600
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Self-host Plausible with Snow SSO for paperclover.net

Run Plausible CE with private ClickHouse storage, managed Postgres, disabled outbound email, and an owner session bridge behind Snow forward authentication. Keep anonymous tracker delivery and ingestion available independently of dashboard sign-in. Stage-tested native sessions, role enforcement, CSRF, encoded paths, logout, bootstrap, tracker pageviews and outbound clicks, and parity for all ten supported Cloud import tables. Assisted-by: gpt-6.1-sol

7 files changed, 753 insertions(+), 0 deletions(-)

service/plausible/bootstrap.exs created+54
......@@ -0,0 +1,54 @@
1alias Plausible.{Auth.User, Repo, Sites}
2
3# Provision the first owner before the public registration page can be served.
4endpoint = Application.fetch_env!(:plausible, PlausibleWeb.Endpoint)
5Application.put_env(:plausible, PlausibleWeb.Endpoint, Keyword.put(endpoint, :server, false))
6oban = Application.fetch_env!(:plausible, Oban)
7Application.put_env(:plausible, Oban, Keyword.merge(oban, queues: [], plugins: [], peer: false))
8{:ok, _} = Application.ensure_all_started(:plausible)
9
10{:ok, _} =
11 Repo.transaction(fn ->
12 email = System.fetch_env!("ADMIN_EMAIL")
13
14 user =
15 Repo.get_by(User, email: email) ||
16 if Repo.exists?(User) do
17 raise "Owner email does not match the existing installation"
18 else
19 password = System.fetch_env!("INITIAL_ADMIN_PASSWORD")
20
21 case Repo.insert(
22 User.new(%{
23 email: email,
24 name: "Clover",
25 password: password,
26 password_confirmation: password
27 })
28 ) do
29 {:ok, user} -> user
30 {:error, _} -> raise "Could not create the Plausible owner"
31 end
32 end
33
34 domain = System.fetch_env!("SITE_DOMAIN")
35
36 site =
37 if site = Sites.get_by_domain(domain) do
38 unless Sites.get_for_user(user, domain, roles: [:owner]) do
39 raise "The configured owner does not own this site"
40 end
41
42 site
43 else
44 {:ok, %{site: site}} =
45 Sites.create(user, %{domain: domain, timezone: System.fetch_env!("SITE_TIMEZONE")})
46
47 site
48 end
49
50 PlausibleWeb.Tracker.get_or_create_tracker_script_configuration!(site, %{
51 installation_type: :manual,
52 outbound_links: true
53 })
54 end)
service/plausible/clickhouse-users.xml created+20
......@@ -0,0 +1,20 @@
1<clickhouse>
2 <users>
3 <default remove="remove" />
4 <plausible>
5 <password from_env="PLAUSIBLE_CLICKHOUSE_PASSWORD" hide_in_preprocessed="true" />
6 <networks><ip>::/0</ip></networks>
7 <profile>default</profile>
8 <quota>default</quota>
9 </plausible>
10 </users>
11 <profiles>
12 <default>
13 <max_threads>1</max_threads>
14 <max_block_size>8192</max_block_size>
15 <max_download_threads>1</max_download_threads>
16 <input_format_parallel_parsing>0</input_format_parallel_parsing>
17 <output_format_parallel_formatting>0</output_format_parallel_formatting>
18 </default>
19 </profiles>
20</clickhouse>
service/plausible/clickhouse.xml created+24
......@@ -0,0 +1,24 @@
1<clickhouse>
2 <listen_host replace="replace">0.0.0.0</listen_host>
3 <logger>
4 <level>warning</level>
5 <console>true</console>
6 <log remove="remove" />
7 <errorlog remove="remove" />
8 </logger>
9 <mark_cache_size>134217728</mark_cache_size>
10 <max_server_memory_usage>3221225472</max_server_memory_usage>
11 <background_schedule_pool_size>8</background_schedule_pool_size>
12 <background_buffer_flush_schedule_pool_size>4</background_buffer_flush_schedule_pool_size>
13 <background_message_broker_schedule_pool_size>4</background_message_broker_schedule_pool_size>
14 <background_distributed_schedule_pool_size>4</background_distributed_schedule_pool_size>
15 <query_log remove="remove" />
16 <query_thread_log remove="remove" />
17 <query_views_log remove="remove" />
18 <part_log remove="remove" />
19 <metric_log remove="remove" />
20 <asynchronous_metric_log remove="remove" />
21 <trace_log remove="remove" />
22 <text_log remove="remove" />
23 <processors_profile_log remove="remove" />
24</clickhouse>
service/plausible/service.pkl created+115
......@@ -0,0 +1,115 @@
1amends "../../config/Service.pkl"
2
3import "../../config/site.pkl" as site
4import "../../config/OpenID.pkl" as sso
5import "../forward-auth/service.pkl" as forwardAuth
6import "../postgres/service.pkl" as postgres
7
8name = "Plausible"
9tagline = "Website analytics"
10access = "infra-admin"
11stageIsolation = "fresh"
12healthyDeadline = "10m"
13
14requirements {
15 new postgres.Database { name = "plausible" }
16 new sso.Client {
17 clientId = module.id
18 name = module.name
19 redirectUris { "https://\(module.containers["app"].http.hostname)/snow.oauth2/callback" }
20 }
21}
22
23secrets {
24 ["secret_key_base"] { bytes = 64 }
25 ["clickhouse_password"] {}
26 ["initial_admin_password"] {}
27 ["cookie"] = forwardAuth.secrets["cookie"]
28}
29
30containers {
31 ["auth"] = (forwardAuth.container!!) {
32 lifecycle = "prestartSidecar"
33 http = null
34 tcp {
35 new { name = "oauth"; containerPort = 4180; loopback = false }
36 }
37 env {
38 ["OAUTH2_PROXY_COOKIE_NAME"] = "_snow_\(module.id)"
39 ["OAUTH2_PROXY_COOKIE_DOMAINS"] = module.containers["app"].http.hostname!!
40 ["OAUTH2_PROXY_WHITELIST_DOMAINS"] = "\(module.containers["app"].http.hostname),\(sso.hostname)"
41 ["OAUTH2_PROXY_REDIRECT_URL"] = "https://\(module.containers["app"].http.hostname)/snow.oauth2/callback"
42 ["OAUTH2_PROXY_AUTH_LOGGING"] = "false"
43 ["OAUTH2_PROXY_REQUEST_LOGGING"] = "false"
44 }
45 }
46
47 ["clickhouse"] {
48 image = "docker.io/clickhouse/clickhouse-server@sha256:cd450891db46cc6ffe313ca2b0fb7dbfb897a6873ca74a724cbe050a2cf62621"
49 lifecycle = "prestartSidecar"
50 cpu = 400
51 memory = 4096
52 tcp {
53 new {
54 name = "db"
55 containerPort = 8123
56 loopback = false
57 }
58 }
59 volumes {
60 ["/var/lib/clickhouse"] {}
61 ["/etc/clickhouse-server/config.d/studio.xml"] { config = "clickhouse.xml" }
62 ["/etc/clickhouse-server/users.d/studio.xml"] { config = "clickhouse-users.xml" }
63 }
64 env {
65 ["CLICKHOUSE_SKIP_USER_SETUP"] = "1"
66 ["PLAUSIBLE_CLICKHOUSE_PASSWORD"] = "${secret.own.clickhouse_password}"
67 }
68 }
69
70 ["app"] {
71 image = "ghcr.io/plausible/community-edition@sha256:33e60bfb40f2df5da00f8753b76fad04f67dba3abe6d73eb516e440e3fb62985"
72 entrypoint = "/bin/sh"
73 args {
74 "-ec"
75 """
76 timeout 90 /bin/sh -c 'until /entrypoint.sh db createdb; do sleep 2; done'
77 /entrypoint.sh db migrate
78 /app/bin/plausible eval 'Code.eval_file("/bootstrap.exs")'
79 exec /app/bin/plausible eval 'Code.eval_file("/sso.exs")'
80 """
81 }
82 cpu = 500
83 memory = 2048
84 http {
85 containerPort = 8000
86 subdomain = "plausible"
87 checkPath = "/api/health"
88 forwardRealIp = true
89 }
90 volumes {
91 ["/var/lib/plausible"] {}
92 ["/bootstrap.exs"] { config = "bootstrap.exs" }
93 ["/sso.exs"] { config = "sso.exs" }
94 }
95 env {
96 ["BASE_URL"] = "https://\(module.containers["app"].http.hostname)"
97 ["SECRET_KEY_BASE"] = "${secret.own.secret_key_base}"
98 ["ADMIN_EMAIL"] = site.ownerEmail
99 ["INITIAL_ADMIN_PASSWORD"] = "${secret.own.initial_admin_password}"
100 ["SITE_DOMAIN"] = site.domain
101 ["SITE_TIMEZONE"] = "America/Detroit"
102 ["SSO_HOME_URL"] = "\(sso.issuer)/"
103 ["DISABLE_REGISTRATION"] = "true"
104 ["ENABLE_EMAIL_VERIFICATION"] = "false"
105 ["MAILER_ADAPTER"] = "Bamboo.LocalAdapter"
106 ["TMPDIR"] = "/var/lib/plausible/tmp"
107 ["ERL_FLAGS"] = "+S 4:4"
108 }
109 envTemplate = """
110 {{ with $db := nomadVar "nomad/jobs/\(module.id)/inputs/database" }}{{ range nomadService 1 (env "NOMAD_ALLOC_ID") "postgres" }}DATABASE_URL=postgres://{{ index $db "username" }}:{{ index $db "password" }}@\(module.nomadHostPort)/{{ index $db "name" }}{{ end }}{{ end }}
111 {{ with $own := nomadVar "nomad/jobs/\(module.id)" }}{{ range nomadService 1 (env "NOMAD_ALLOC_ID") "\(module.id)-clickhouse" }}CLICKHOUSE_DATABASE_URL=http://plausible:{{ index $own "clickhouse_password" }}@\(module.nomadHostPort)/plausible_events_db{{ end }}{{ end }}
112 {{ range nomadService 1 (env "NOMAD_ALLOC_ID") "\(module.id)-auth" }}SSO_AUTH_URL=http://\(module.nomadHostPort){{ end }}
113 """
114 }
115}
service/plausible/sso-test.exs created+251
......@@ -0,0 +1,251 @@
1endpoint = Application.fetch_env!(:plausible, PlausibleWeb.Endpoint)
2Application.put_env(:plausible, PlausibleWeb.Endpoint, Keyword.put(endpoint, :server, false))
3oban = Application.fetch_env!(:plausible, Oban)
4Application.put_env(:plausible, Oban, Keyword.merge(oban, queues: [], plugins: [], peer: false))
5{:ok, _} = Application.ensure_all_started(:plausible)
6{:__block__, _, [bridge | _]} = Code.string_to_quoted!(File.read!("/sso.exs"))
7Code.eval_quoted(bridge)
8
9defmodule Snowglobe.PlausibleAuthFixture do
10 import Plug.Conn
11 def init(opts), do: opts
12
13 def call(conn, _opts) do
14 conn = fetch_cookies(conn)
15
16 case {conn.request_path, conn.req_cookies["fixture"]} do
17 {_, "down"} ->
18 send_resp(conn, 503, "Unavailable")
19
20 {"/ping", _} ->
21 send_resp(conn, 200, "OK")
22
23 {"/snow.oauth2/auth", "admin"} ->
24 conn
25 |> put_resp_header("x-auth-request-groups", "role:media,role:infra-admin")
26 |> send_resp(204, "")
27
28 {"/snow.oauth2/auth", "similar-role"} ->
29 conn
30 |> put_resp_header("x-auth-request-groups", "role:infra-admin-extra")
31 |> send_resp(204, "")
32
33 {"/snow.oauth2/auth", _} ->
34 send_resp(conn, 401, "Unauthorized")
35
36 _ ->
37 conn
38 |> prepend_resp_headers([
39 {"set-cookie", "one=; Max-Age=0"},
40 {"set-cookie", "two=; Max-Age=0"}
41 ])
42 |> put_resp_header("location", System.fetch_env!("SSO_HOME_URL"))
43 |> send_resp(302, "")
44 end
45 end
46end
47
48{:ok, _} = Plug.Cowboy.http(Snowglobe.PlausibleAuthFixture, [], ip: {127, 0, 0, 1}, port: 0)
49port = :ranch.get_port(Snowglobe.PlausibleAuthFixture.HTTP)
50System.put_env("SSO_AUTH_URL", "http://127.0.0.1:#{port}")
51
52import Plug.Conn
53alias PlausibleWeb.{Endpoint, UserAuth}
54
55request = fn method, path, cookie, headers ->
56 conn =
57 Plug.Test.conn(method, System.fetch_env!("BASE_URL") <> path)
58 |> put_req_header("cookie", cookie)
59
60 conn =
61 Enum.reduce(headers, conn, fn {name, value}, conn -> put_req_header(conn, name, value) end)
62
63 Snowglobe.Plausible.call(conn, [])
64end
65
66check = fn condition, name ->
67 unless condition, do: raise("Failed: " <> name)
68 IO.puts("PASS " <> name)
69end
70
71owner_cookie = fn ->
72 conn = request.(:get, "/sites", "fixture=admin", [])
73 value = conn.resp_cookies["_plausible_key"].value
74 config = Plug.Session.init(Endpoint.runtime_session_opts())
75
76 {_, session} =
77 Plug.Session.COOKIE.get(
78 %{conn | secret_key_base: Endpoint.config(:secret_key_base)},
79 value,
80 config.store_config
81 )
82
83 token = Map.fetch!(session, "user_token")
84 Process.put(:created_tokens, [token | Process.get(:created_tokens, [])])
85 {"_plausible_key=" <> value, token, conn}
86end
87
88try do
89 conn =
90 request.(:get, "/sites?period=all", "", [
91 {"x-auth-request-groups", "role:infra-admin"},
92 {"authorization", "Basic ZmFrZTpmYWtl"}
93 ])
94
95 destination =
96 "/snow.oauth2/start?" <>
97 URI.encode_query(%{"rd" => System.fetch_env!("BASE_URL") <> "/sites?period=all"})
98
99 check.(
100 conn.status == 302 and get_resp_header(conn, "location") == [destination] and
101 not Map.has_key?(conn.resp_cookies, "_plausible_key"),
102 "forged headers cannot bypass SSO"
103 )
104
105 conn = request.(:get, "/sites", "fixture=similar-role", [])
106
107 check.(
108 conn.status == 403 and not Map.has_key?(conn.resp_cookies, "_plausible_key"),
109 "exact role match"
110 )
111
112 {cookie, token, login} = owner_cookie.()
113
114 owner =
115 case Plausible.Auth.UserSessions.get_by_token(token) do
116 {:ok, %{user: user}} -> user.email == System.fetch_env!("ADMIN_EMAIL")
117 _ -> false
118 end
119
120 secure_cookie =
121 Enum.any?(get_resp_header(login, "set-cookie"), fn value ->
122 String.starts_with?(value, "_plausible_key=") and
123 Enum.all?(
124 ["secure", "httponly", "samesite=lax"],
125 &String.contains?(String.downcase(value), &1)
126 )
127 end)
128
129 check.(owner and secure_cookie, "secure normal owner session")
130
131 conn = request.(:get, "/sites", "fixture=admin; " <> cookie, [])
132
133 check.(
134 conn.status == 200 and not Map.has_key?(conn.resp_cookies, "logged_in"),
135 "reuse the existing owner session"
136 )
137
138 conn = request.(:get, "/sites", cookie, [])
139 check.(conn.status == 302, "Plausible cookie alone cannot enter the dashboard")
140 conn = request.(:get, "/api/stats/paperclover.net/top-stats", cookie, [])
141 check.(conn.status == 401, "Plausible cookie alone cannot read statistics")
142
143 Plausible.Auth.UserSessions.remove_by_token(token)
144 conn = request.(:get, "/sites?period=all", "fixture=admin; " <> cookie, [])
145 value = conn.resp_cookies["_plausible_key"].value
146 config = Plug.Session.init(Endpoint.runtime_session_opts())
147
148 {_, session} =
149 Plug.Session.COOKIE.get(
150 %{conn | secret_key_base: Endpoint.config(:secret_key_base)},
151 value,
152 config.store_config
153 )
154
155 Process.put(:created_tokens, [session["user_token"] | Process.get(:created_tokens, [])])
156 valid = match?({:ok, _}, UserAuth.get_user_session(session))
157
158 check.(
159 conn.status == 302 and get_resp_header(conn, "location") == ["/sites?period=all"] and valid,
160 "replace expired sessions and preserve the destination"
161 )
162
163 {cookie, token, _} = owner_cookie.()
164 conn = request.(:get, "/logout", "fixture=admin; " <> cookie, [])
165 revoked = match?({:error, :not_found}, Plausible.Auth.UserSessions.get_by_token(token))
166
167 destination =
168 "/snow.oauth2/sign_out?" <> URI.encode_query(%{"rd" => System.fetch_env!("SSO_HOME_URL")})
169
170 check.(
171 conn.status == 302 and get_resp_header(conn, "location") == [destination] and revoked,
172 "logout revokes the owner session"
173 )
174
175 conn = request.(:get, "/snow.oauth2/sign_out", "", [])
176 check.(length(get_resp_header(conn, "set-cookie")) == 2, "forward every SSO logout cookie")
177
178 for {method, path, cookie} <- [
179 {:post, "/settings/security/password", ""},
180 {:get, "/live/websocket", ""},
181 {:post, "/settings/security/password", "fixture=admin"},
182 {:get, "/live/websocket", "fixture=admin"}
183 ] do
184 conn = request.(method, path, cookie, [])
185
186 check.(
187 conn.status == 401 and not Map.has_key?(conn.resp_cookies, "_plausible_key"),
188 "private writes and WebSockets require both sessions"
189 )
190 end
191
192 {cookie, _, _} = owner_cookie.()
193
194 rejected =
195 try do
196 request.(:post, "/settings/security/password", "fixture=admin; " <> cookie, []).status ==
197 403
198 rescue
199 e ->
200 is_struct(e, Plug.CSRFProtection.InvalidCSRFTokenError) or
201 (is_struct(e, Plug.Conn.WrapperError) and
202 is_struct(e.reason, Plug.CSRFProtection.InvalidCSRFTokenError))
203 end
204
205 check.(rejected, "native CSRF protection remains active")
206
207 for path <- ["/settings/security/email", "/settings/security/%65mail", "/me"] do
208 conn = request.(:post, path, "fixture=admin; " <> cookie, [])
209 check.(conn.status == 403, "the configured owner identity cannot be changed through the app")
210 end
211
212 conn = request.(:get, "/sites", "fixture=down", [])
213 check.(conn.status == 503, "SSO failure closes private pages")
214 conn = request.(:get, "/api/health", "fixture=down", [])
215 check.(conn.status == 503, "health includes the auth sidecar")
216 conn = request.(:get, "/js/script.js", "fixture=down", [])
217 check.(conn.status == 200, "scripts remain public during SSO failure")
218
219 conn =
220 request.(:options, "/api/event", "", [
221 {"origin", "https://paperclover.net"},
222 {"access-control-request-method", "POST"}
223 ])
224
225 check.(conn.status in [200, 204], "tracking preflight remains public")
226
227 for path <- ["/js/../sites", "/js/%2e%2e/sites", "/js/%2f..%2fsites", "/api/event/../stats"] do
228 conn = request.(:get, path, cookie, [])
229
230 check.(
231 conn.status in [302, 401] and not Map.has_key?(conn.resp_cookies, "_plausible_key"),
232 "public paths cannot traverse into private pages"
233 )
234 end
235
236 original_domain = System.fetch_env!("SITE_DOMAIN")
237 fixture_domain = "plausible-sso-bootstrap.invalid"
238 System.put_env("SITE_DOMAIN", fixture_domain)
239
240 try do
241 Code.eval_file("/bootstrap.exs")
242 check.(Plausible.Sites.get_by_domain(fixture_domain) != nil, "fresh site bootstrap")
243 after
244 System.put_env("SITE_DOMAIN", original_domain)
245 if site = Plausible.Sites.get_by_domain(fixture_domain), do: Plausible.Site.Removal.run(site)
246 end
247
248 IO.puts("SSO boundary checks passed")
249after
250 Enum.each(Process.get(:created_tokens, []), &Plausible.Auth.UserSessions.remove_by_token/1)
251end
service/plausible/sso.exs created+176
......@@ -0,0 +1,176 @@
1defmodule Snowglobe.Plausible do
2 import Plug.Conn
3 alias PlausibleWeb.{Endpoint, UserAuth}
4
5 @unavailable "Sign-in is unavailable. Try again."
6 @sign_in "Open Plausible to sign in, then try again."
7
8 def init(opts), do: opts
9
10 def call(conn, _opts) do
11 public =
12 (conn.method in ["GET", "HEAD"] and
13 Regex.match?(~r{\A/js/[A-Za-z0-9._-]+\.js\z}, conn.request_path)) or
14 (conn.method in ["POST", "OPTIONS"] and conn.request_path == "/api/event")
15
16 cond do
17 conn.method in ["GET", "HEAD"] and conn.request_path == "/api/health" ->
18 case auth_request(conn, "/ping") do
19 {:ok, %{status: 200}} -> Endpoint.call(conn, Endpoint.init([]))
20 _ -> send_resp(conn, 503, @unavailable)
21 end
22
23 public ->
24 Endpoint.call(conn, Endpoint.init([]))
25
26 conn.method == "GET" and
27 conn.request_path in ~w(/snow.oauth2/start /snow.oauth2/callback /snow.oauth2/sign_in /snow.oauth2/sign_out) ->
28 case auth_request(conn, conn.request_path <> query(conn)) do
29 {:ok, response} ->
30 conn
31 |> prepend_resp_headers(
32 Enum.reject(response.headers, fn {name, _} ->
33 name in ~w(connection content-length transfer-encoding)
34 end)
35 )
36 |> send_resp(response.status, response.body)
37
38 {:error, _} ->
39 send_resp(conn, 503, @unavailable)
40 end
41
42 true ->
43 authenticate(conn)
44 end
45 end
46
47 defp authenticate(conn) do
48 case auth_request(conn, "/snow.oauth2/auth") do
49 {:ok, %{status: status, headers: headers}} when status in 200..299 ->
50 groups =
51 for {"x-auth-request-groups", value} <- headers,
52 group <- String.split(value, ~r/[,\s]+/, trim: true),
53 do: group
54
55 conn =
56 prepend_resp_headers(
57 conn,
58 Enum.filter(headers, fn {name, _} -> name == "set-cookie" end)
59 )
60
61 if "role:infra-admin" in groups do
62 owner_session(conn)
63 else
64 send_resp(
65 conn,
66 403,
67 "Your account cannot access Plausible. Ask an administrator for access."
68 )
69 end
70
71 {:ok, %{status: status}} when status in [401, 403] ->
72 if conn.method in ["GET", "HEAD"] and
73 not String.starts_with?(conn.request_path, ["/api/", "/live/"]) do
74 destination = System.fetch_env!("BASE_URL") <> conn.request_path <> query(conn)
75
76 Phoenix.Controller.redirect(conn,
77 to: "/snow.oauth2/start?" <> URI.encode_query(%{"rd" => destination})
78 )
79 else
80 send_resp(conn, 401, @sign_in)
81 end
82
83 _ ->
84 send_resp(conn, 503, @unavailable)
85 end
86 end
87
88 defp owner_session(conn) do
89 conn = %{conn | secret_key_base: Endpoint.config(:secret_key_base)} |> fetch_cookies()
90 config = Plug.Session.init(Endpoint.runtime_session_opts())
91
92 # Leave the endpoint responsible for installing its session hook.
93 session =
94 if cookie = conn.req_cookies[config.key] do
95 {_, session} = Plug.Session.COOKIE.get(conn, cookie, config.store_config)
96 UserAuth.get_user_session(session)
97 end
98
99 owner_email = System.fetch_env!("ADMIN_EMAIL")
100
101 cond do
102 conn.method in ["POST", "DELETE"] and
103 Enum.map(conn.path_info, &URI.decode/1) in [["settings", "security", "email"], ["me"]] ->
104 send_resp(
105 conn,
106 403,
107 "This shared owner account uses the configured email address. Ask the server administrator to change or remove it."
108 )
109
110 conn.method == "GET" and conn.request_path == "/logout" ->
111 conn = conn |> Plug.Session.call(config) |> fetch_session() |> UserAuth.log_out_user()
112
113 Phoenix.Controller.redirect(conn,
114 to:
115 "/snow.oauth2/sign_out?" <>
116 URI.encode_query(%{"rd" => System.fetch_env!("SSO_HOME_URL")})
117 )
118
119 conn.method == "GET" and conn.request_path == "/login" ->
120 Phoenix.Controller.redirect(conn, to: "/sites")
121
122 match?({:ok, %{user: %{email: ^owner_email}}}, session) ->
123 {:ok, user_session} = session
124 Endpoint.call(assign(conn, :current_user_session, user_session), Endpoint.init([]))
125
126 conn.method == "GET" and not String.starts_with?(conn.request_path, ["/api/", "/live/"]) ->
127 user = Plausible.Repo.get_by!(Plausible.Auth.User, email: owner_email)
128
129 conn
130 |> put_private(:phoenix_endpoint, Endpoint)
131 |> Plug.Session.call(config)
132 |> fetch_session()
133 |> put_resp_header("cache-control", "no-store")
134 |> UserAuth.log_in_user(user, conn.request_path <> query(conn))
135
136 true ->
137 send_resp(conn, 401, @sign_in)
138 end
139 end
140
141 defp query(%{query_string: ""}), do: ""
142 defp query(conn), do: "?" <> conn.query_string
143
144 defp auth_request(conn, path) do
145 host = URI.parse(System.fetch_env!("BASE_URL")).host
146
147 headers =
148 Enum.filter(conn.req_headers, fn {name, _} -> name in ~w(cookie user-agent accept) end) ++
149 [
150 {"x-forwarded-proto", "https"},
151 {"x-forwarded-host", host},
152 {"x-forwarded-uri", conn.request_path <> query(conn)},
153 {"x-forwarded-method", conn.method}
154 ]
155
156 Finch.build(:get, System.fetch_env!("SSO_AUTH_URL") <> path, headers)
157 |> Finch.request(Plausible.Finch, pool_timeout: 1_000, receive_timeout: 3_000)
158 end
159end
160
161# Keep a single listener so no route can bypass forward authentication.
162endpoint = Application.fetch_env!(:plausible, PlausibleWeb.Endpoint)
163Application.put_env(:plausible, PlausibleWeb.Endpoint, Keyword.put(endpoint, :server, false))
164Application.put_env(:plug_cowboy, :conn_in_exception_metadata, false)
165{:ok, _} = Application.ensure_all_started(:plausible)
166
167{:ok, _} =
168 Supervisor.start_child(
169 Plausible.Supervisor,
170 {Plug.Cowboy,
171 scheme: :http,
172 plug: Snowglobe.Plausible,
173 options: [port: Application.fetch_env!(:plausible, PlausibleWeb.Endpoint)[:http][:port]]}
174 )
175
176Process.sleep(:infinity)
tools/plausible.md created+113
......@@ -0,0 +1,113 @@
1# Plausible for paperclover.net
2
3[The service definition](../service/plausible/service.pkl) runs Plausible CE
43.2.1 with a private ClickHouse instance and a database allocated by the shared
5Postgres provider. The application and ClickHouse data live in the service's
6managed dataset. Previews start with fresh storage and separate secrets.
7
8The production address is `https://plausible.paperclover.net`. Bootstrap creates
9the owner from `config/site.pkl`, a private site for the base domain, and a
10tracker with outbound-link tracking. The reporting timezone matches the existing
11Cloud site. Bootstrap preserves existing passwords and site settings.
12
13## Sign in
14
15Open Plausible and sign in through Snowglobe. Accounts with `infra-admin` access
16receive separate browser sessions for the same Plausible owner account. The
17service's forward-auth sidecar has its own OIDC client and host-specific cookie;
18previews do not reuse production SSO credentials or cookies. Logout revokes the
19Plausible session, clears that app's SSO cookie, and returns to Snowglobe.
20
21The [session bridge](../service/plausible/sso.exs) wraps the existing Phoenix
22endpoint inside the official CE image. It checks forward auth before private
23HTTP requests and WebSocket handshakes, then uses Plausible's normal session API.
24Only tracker JavaScript, event ingestion, and health checks bypass sign-in.
25Tracking continues if SSO fails; private routes fail closed. Existing WebSockets
26follow the usual forward-auth behavior: access is checked when they connect.
27
28Native password prompts for sensitive account settings use the owner password.
29The `initial_admin_password` secret in Snowglobe's service **Secrets** tab is an
30initial credential, not a password-reset control. Password changes do not affect
31SSO. The app cannot change the configured owner email or delete this shared
32account; those operations require coordinated server administration.
33
34Email is disabled at Clover's request. Password-reset messages, invitations, and
35scheduled reports are captured locally rather than delivered.
36
37When upgrading CE, rerun [the bridge checks](../service/plausible/sso-test.exs)
38and the browser login/logout checks: the bridge uses CE's session APIs. Run the
39script in a disposable preview container, using stdin with
40`/app/bin/plausible eval 'Code.eval_string(IO.read(:stdio, :eof))'`. It starts a
41separate BEAM with a loopback-only mock SSO server, creates temporary owner
42sessions, and removes them afterward. It does not replace the running preview's
43SSO configuration.
44
45## Cloud import and tracking cutover
46
47The [supported migration](https://plausible.io/docs/csv-import) uses a full export
48from Cloud's **Site settings → Imports & exports → Prepare download**. A dashboard
49report ZIP is a different export and cannot substitute for it.
50
511. Deploy the described, conflict-free `main` with `python3 tools/deploy.py prod`
52 after production is requested. Preview data is disposable and is not promoted.
532. Sign in to production and open **paperclover.net → Settings → General →
54 Review installation**. Copy its complete native snippet. Its script ID belongs
55 to the self-hosted installation; the existing Cloud script ID cannot be reused.
563. Plan the website switch at midnight in the site's reporting timezone. Imports
57 end before the first native tracking date, so a switch during a reporting day
58 would exclude that day's earlier Cloud visits from the combined dashboard.
59 Keep Cloud tracking active until the switch, then replace its loader and init
60 block with the self-hosted snippet. Keep existing `plausible(...)` event calls.
614. Export Cloud again after its final reporting day completes. Preserve the
62 complete ZIP in the restricted import store, outside preview storage. The
63 rehearsal export is an earlier snapshot, not a final cutover export.
645. Unzip the export and select the ten supported CSVs together in the destination's
65 **Settings → Imports & exports → Import from CSV**. Wait for the completed
66 import, then compare its dates and metrics with the export. Replace an earlier
67 Cloud import instead of adding overlapping snapshots. Preserve matching
68 custom goals from Cloud's Goals settings; CSV import does not recreate them.
696. Verify pageviews and outbound clicks through the real website, then check the
70 dashboard. Keep the Cloud account and export until the history and cutover have
71 been checked. Remove the temporary preview through the deployment tool when
72 review is finished.
73
74CE 3.2.1 does not import `imported_custom_props_*.csv`. Preserve that file in the
75original ZIP: arbitrary historical custom-property breakdowns cannot be viewed
76in CE. Imported reports are aggregates with fewer filter combinations than
77native events. Cloud exports also exclude earlier third-party imports.
78
79## Rehearsal evidence
80
81On 2026-10-19 UTC, release `12a2725e1a1372ce` passed on Zenith at
82`https://plausible-preview-3234cb91.paperclover.net`. Owner login, disabled
83registration, private dashboards, the CSV upload, keyboard filters, mobile,
84both themes, and installation instructions were checked in a real browser.
85
86All supported metrics matched the source across ten imported tables before and
87after reallocation. A separate disposable site accepted and persisted browser
88pageviews and outbound clicks, then was removed. The real site's native event
89table stayed empty, preserving the full import interval. Both application tasks
90were healthy with zero restarts after the final reallocation; the Nomad job
91validated. ClickHouse rejected anonymous queries.
92
93The original Cloud ZIP and detailed comparison report are owner-readable under
94`/var/lib/snowglobe/imports/plausible/`, outside the preview dataset. No live
95website tracker or production release was changed.
96
97The SSO rehearsal used release `aa77dda7f64c3c86` at the same preview address.
98The auth sidecar, application, and ClickHouse were healthy with zero restarts;
99the deployed Nomad job validated. An authenticated browser reached the shared
100owner's sites, historical reports, and settings without a Plausible password,
101and its native LiveView WebSocket connected.
102
103The bridge checks passed signed-session creation/reuse, exact admin roles,
104forged-header rejection, native-cookie-only rejection, session expiry, logout,
105CSRF, encoded paths, auth failure, and fresh-site bootstrap. An anonymous browser
106loaded the generated tracker and persisted a pageview and outbound click in a
107disposable site. That site was removed afterward. All ten imported tables still
108matched the Cloud export, and the real site's native events remained empty.
109Detailed checks and tracking evidence remain in the restricted import store.
110
111The initial rehearsal used the installed Snowglobe staging manager and OIDC
112provisioner against sources from an older working change. Production uses current
113`main`'s service schema and deployment tooling.