Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Friendly captcha (#6546)
Uku Taht7007a3f9563e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cf2c9a54d9..58aef1482b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -41,6 +41,7 @@ All notable changes to this project will be documented in this file.- Redesigned authentication pages (register, sign in, 2FA, password reset, account activation)- Removed limitation that blocked users without owned sites from starting a subscription- Redesigned onboarding pages (add site, installation)+- Replaced HCaptcha with Friendly Captcha### Fixeddiff --git a/assets/package-lock.json b/assets/package-lock.jsonindex d735d5b544..3e62b33100 100644--- a/assets/package-lock.json+++ b/assets/package-lock.json@@ -9,6 +9,7 @@"version": "1.4.0","license": "AGPL-3.0-or-later","dependencies": {+ "@friendlycaptcha/sdk": "1.0.2","@headlessui/react": "^1.7.19","@heroicons/react": "^2.2.0","@jsonurl/jsonurl": "^1.1.7",@@ -810,6 +811,12 @@"node": "^18.18.0 || ^20.9.0 || >=21.1.0"}},+ "node_modules/@friendlycaptcha/sdk": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/@friendlycaptcha/sdk/-/sdk-1.0.2.tgz",+ "integrity": "sha512-NW1mXrqRjQdg53fWKz369PqkxoNPqNIgBRW5vYIMvPHjIqHieinya1Nr9TjSVD5yoLzZ5AoWx2MfryWMm+dGOg==",+ "license": "MPL-2.0"+ },"node_modules/@headlessui/react": {"version": "1.7.19","resolved": "https://registry.npmjs.org/@headlessui/react/-/react-1.7.19.tgz",diff --git a/assets/package.json b/assets/package.jsonindex c7fce70b07..f5789913cd 100644--- a/assets/package.json+++ b/assets/package.json@@ -13,6 +13,7 @@"generate-types": "json2ts ../priv/json-schemas/query-api-schema.json ../assets/js/types/query-api.d.ts --bannerComment '/* Autogenerated, recreate with `npm run --prefix assets generate-types` */'"},"dependencies": {+ "@friendlycaptcha/sdk": "1.0.2","@headlessui/react": "^1.7.19","@heroicons/react": "^2.2.0","@jsonurl/jsonurl": "^1.1.7",diff --git a/config/.env.test b/config/.env.testindex 42a1e85526..354c0bffdb 100644--- a/config/.env.test+++ b/config/.env.test@@ -9,8 +9,8 @@ ENVIRONMENT=testMAILER_ADAPTER=Bamboo.TestAdapterENABLE_EMAIL_VERIFICATION=trueSELFHOST=false-HCAPTCHA_SITEKEY=test-HCAPTCHA_SECRET=scottiger+FRIENDLY_CAPTCHA_SITEKEY=test+FRIENDLY_CAPTCHA_API_KEY=scottigerIP_GEOLOCATION_DB=test/priv/GeoLite2-City-Test.mmdbSITE_DEFAULT_INGEST_THRESHOLD=1000000GOOGLE_CLIENT_ID=fake_client_iddiff --git a/config/config.exs b/config/config.exsindex 1c2199c0c1..cb0490676b 100644--- a/config/config.exs+++ b/config/config.exs@@ -23,6 +23,12 @@ config :esbuild,~w(js/app.js js/dashboard.tsx js/embed.host.js js/embed.content.js --bundle --target=es2017 --loader:.js=jsx --outdir=../priv/static/js --define:BUILD_EXTRA=true),cd: Path.expand("../assets", __DIR__),env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}+ ],+ # https://developer.friendlycaptcha.com/docs/v2/getting-started/install#using-the-scripts-without-a-cdn-ie-self-hosting+ friendly_captcha: [+ args:+ ~w(node_modules/@friendlycaptcha/sdk/site.min.js node_modules/@friendlycaptcha/sdk/site.compat.min.js --loader:.js=copy --outbase=node_modules/@friendlycaptcha/sdk --outdir=../priv/static/js/friendly-captcha),+ cd: Path.expand("../assets", __DIR__)]config :tailwind,diff --git a/config/dev.exs b/config/dev.exsindex f0851f421c..ebeca6945c 100644--- a/config/dev.exs+++ b/config/dev.exs@@ -7,6 +7,8 @@ config :plausible, PlausibleWeb.Endpoint,check_origin: false,watchers: [esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]},+ # Not watched: these are vendored files that only change on npm install.+ esbuild: {Esbuild, :install_and_run, [:friendly_captcha, []]},tailwind: {Tailwind, :install_and_run, [:default, ~w(--watch)]},npm: ["--prefix", "assets", "run", "typecheck", "--", "--watch", "--preserveWatchOutput"],npm: [diff --git a/config/runtime.exs b/config/runtime.exsindex c78ed517e9..abc25e0f31 100644--- a/config/runtime.exs+++ b/config/runtime.exs@@ -312,8 +312,8 @@ if disable_registration not in [true, false, :invite_only] doraise "DISABLE_REGISTRATION must be one of `true`, `false`, or `invite_only`. See https://github.com/plausible/community-edition/wiki/configuration#disable_registration"end-hcaptcha_sitekey = get_var_from_path_or_env(config_dir, "HCAPTCHA_SITEKEY")-hcaptcha_secret = get_var_from_path_or_env(config_dir, "HCAPTCHA_SECRET")+friendly_captcha_sitekey = get_var_from_path_or_env(config_dir, "FRIENDLY_CAPTCHA_SITEKEY")+friendly_captcha_api_key = get_var_from_path_or_env(config_dir, "FRIENDLY_CAPTCHA_API_KEY")custom_script_name =config_dir@@ -912,9 +912,9 @@ elsequeues: queuesend-config :plausible, :hcaptcha,- sitekey: hcaptcha_sitekey,- secret: hcaptcha_secret+config :plausible, :friendly_captcha,+ sitekey: friendly_captcha_sitekey,+ api_key: friendly_captcha_api_keynolt_sso_secret = get_var_from_path_or_env(config_dir, "NOLT_SSO_SECRET")config :joken, default_signer: nolt_sso_secretdiff --git a/lib/plausible_web/captcha.ex b/lib/plausible_web/captcha.exindex aff593d88e..10567db8b6 100644--- a/lib/plausible_web/captcha.ex+++ b/lib/plausible_web/captcha.ex@@ -1,14 +1,18 @@defmodule PlausibleWeb.Captcha do+ @moduledoc """+ Integration with Friendly Captcha+ """+alias Plausible.HTTPClient- @verify_endpoint "https://hcaptcha.com/siteverify"+ @verify_endpoint "https://global.frcapi.com/api/v2/captcha/siteverify"def enabled? dois_binary(sitekey())enddef sitekey() do- Application.get_env(:plausible, :hcaptcha, [])[:sitekey]+ Application.get_env(:plausible, :friendly_captcha, [])[:sitekey]enddef verify(token) do@@ -16,10 +20,10 @@ defmodule PlausibleWeb.Captcha dores =HTTPClient.impl().post(@verify_endpoint,- [{"content-type", "application/x-www-form-urlencoded"}],+ [{"content-type", "application/json"}, {"x-api-key", api_key()}],%{response: token,- secret: secret()+ sitekey: sitekey()})@@ -35,7 +39,7 @@ defmodule PlausibleWeb.Captcha doendend- defp secret() do- Application.get_env(:plausible, :hcaptcha, [])[:secret]+ defp api_key() do+ Application.get_env(:plausible, :friendly_captcha, [])[:api_key]endenddiff --git a/lib/plausible_web/components/captcha.ex b/lib/plausible_web/components/captcha.exnew file mode 100644index 0000000000..5c4e99b590--- /dev/null+++ b/lib/plausible_web/components/captcha.ex@@ -0,0 +1,117 @@+defmodule PlausibleWeb.Components.Captcha do+ @moduledoc """+ Friendly Captcha widget shared between the registration and password-reset forms.+ """+ use Phoenix.Component, global_prefixes: ~w(x-)++ @reset_event "reset-frc-captcha"++ @doc """+ Tells the client to discard the current captcha solution and solve a new one.+ """+ def reset(socket) do+ if PlausibleWeb.Captcha.enabled?() do+ Phoenix.LiveView.push_event(socket, @reset_event, %{})+ else+ socket+ end+ end++ attr :error, :string, default: nil++ def widget(assigns) do+ assigns = assign(assigns, :reset_event, @reset_event)++ ~H"""+ <div>+ <div+ phx-update="ignore"+ id="frc-captcha-placeholder"+ class="frc-captcha hidden mb-2"+ data-sitekey={PlausibleWeb.Captcha.sitekey()}+ data-start="auto"+ style="width: 100%"+ >+ </div>+ <p :if={@error} class="text-xs text-red-500 mt-2">+ {@error}+ </p>+ <script+ id="frc-captcha-script"+ type="module"+ src={+ PlausibleWeb.Router.Helpers.static_path(+ PlausibleWeb.Endpoint,+ "/js/friendly-captcha/site.min.js"+ )+ }+ async+ defer+ >+ </script>+ <script+ id="frc-captcha-script-compat"+ nomodule+ src={+ PlausibleWeb.Router.Helpers.static_path(+ PlausibleWeb.Endpoint,+ "/js/friendly-captcha/site.compat.min.js"+ )+ }+ async+ defer+ >+ </script>+ <script id="frc-captcha-reveal">+ (function () {+ var SHOW_AFTER_LONG_WAIT_MS = 5000;+ var el = document.getElementById("frc-captcha-placeholder");+ if (!el) return;++ // Match the widget to the app's resolved light/dark theme. This runs+ // before the (deferred) SDK initializes, so the widget picks up the+ // right theme from the start, and the observer keeps it in sync.+ function applyTheme() {+ el.dataset.theme =+ document.documentElement.classList.contains("dark") ? "dark" : "light";+ }+ applyTheme();+ new MutationObserver(applyTheme).observe(document.documentElement, {+ attributes: true,+ attributeFilter: ["class"]+ });++ function show() { el.classList.remove("hidden"); }+ var timeout;+ // Friendly Captcha carries the event payload on `e.detail` (not `e`).+ el.addEventListener("frc:widget.statechange", function (e) {+ var d = e.detail || {};+ // Interactive mode means the user must click to solve: reveal the widget.+ if (d.mode === "interactive") { show(); }+ // Reveal if solving takes unusually long, then stop waiting once done.+ if (d.state === "requesting") {+ clearTimeout(timeout);+ timeout = setTimeout(show, SHOW_AFTER_LONG_WAIT_MS);+ } else if (d.state === "completed") {+ clearTimeout(timeout);+ }+ // Reveal on error or expiry so the user can recover.+ if (d.state === "error" || d.state === "expired") { show(); }+ // Enable the submit button only once we hold a valid solution.+ window.dispatchEvent(new Event(+ d.state === "completed" ? "frc-captcha-ready" : "frc-captcha-reset"+ ));+ });++ window.addEventListener("phx:<%= @reset_event %>", function () {+ if (!window.frcaptcha) return;+ window.frcaptcha.getAllWidgets().forEach(function (widget) {+ if (!widget.isDestroyed) widget.reset();+ });+ });+ })();+ </script>+ </div>+ """+ end+enddiff --git a/lib/plausible_web/components/layout.ex b/lib/plausible_web/components/layout.exindex 9fc63ab11c..068433cb2c 100644--- a/lib/plausible_web/components/layout.ex+++ b/lib/plausible_web/components/layout.ex@@ -55,16 +55,13 @@ defmodule PlausibleWeb.Components.Layout dofunction reapplyTheme() {var darkMediaPref = window.matchMedia('(prefers-color-scheme: dark)').matches;var htmlRef = document.querySelector('html');- var hcaptchaRefs = Array.from(document.getElementsByClassName('h-captcha'));var isDark = themePref === 'dark' || (themePref === 'system' && darkMediaPref);if (isDark) {htmlRef.classList.add('dark')- hcaptchaRefs.forEach(function(ref) { ref.dataset.theme = "dark"; });} else {htmlRef.classList.remove('dark');- hcaptchaRefs.forEach(function(ref) { ref.dataset.theme = "light"; });}}diff --git a/lib/plausible_web/controllers/auth_controller.ex b/lib/plausible_web/controllers/auth_controller.exindex ffddf23a86..c8bf9f7061 100644--- a/lib/plausible_web/controllers/auth_controller.ex+++ b/lib/plausible_web/controllers/auth_controller.ex@@ -173,7 +173,7 @@ defmodule PlausibleWeb.AuthController doenddef password_reset_request(conn, %{"email" => email} = params) do- if PlausibleWeb.Captcha.verify(params["h-captcha-response"]) do+ if PlausibleWeb.Captcha.verify(params["frc-captcha-response"]) docase Auth.lookup(email) do{:ok, _user} ->token = Auth.Token.sign_password_reset(email)diff --git a/lib/plausible_web/live/register_form.ex b/lib/plausible_web/live/register_form.exindex 3ee6c13334..b4d3385188 100644--- a/lib/plausible_web/live/register_form.ex+++ b/lib/plausible_web/live/register_form.ex@@ -131,31 +131,7 @@ defmodule PlausibleWeb.Live.RegisterForm do</div><%= if PlausibleWeb.Captcha.enabled?() do %>- <div>- <div- phx-update="ignore"- id="hcaptcha-placeholder"- class="h-captcha"- data-sitekey={PlausibleWeb.Captcha.sitekey()}- >- </div>- <p- :if={@captcha_error}- class="text-xs text-red-500 mt-2"- x-data- x-init="hcaptcha.reset()"- >- {@captcha_error}- </p>- <script- phx-update="ignore"- id="hcaptcha-script"- src="https://hcaptcha.com/1/api.js"- async- defer- >- </script>- </div>+ <PlausibleWeb.Components.Captcha.widget error={@captcha_error} /><% end %><div class="flex flex-col gap-y-4">@@ -165,7 +141,16 @@ defmodule PlausibleWeb.Live.RegisterForm doelse"Start my free trial"end %>- <.button id="register" disabled={@disable_submit} type="submit" class="w-full" mt?={false}>+ <.button+ id="register"+ type="submit"+ class="w-full"+ mt?={false}+ x-data={"{ captchaReady: #{not PlausibleWeb.Captcha.enabled?()} }"}+ x-on:frc-captcha-ready.window="captchaReady = true"+ x-on:frc-captcha-reset.window="captchaReady = false"+ x-bind:disabled={"!captchaReady || #{@disable_submit}"}+ >{submit_text}</.button>@@ -258,8 +243,7 @@ defmodule PlausibleWeb.Live.RegisterForm do%{"user" => _} = params,%{assigns: %{invitation: %{} = invitation}} = socket) do- if not PlausibleWeb.Captcha.enabled?() or- PlausibleWeb.Captcha.verify(params["h-captcha-response"]) do+ if PlausibleWeb.Captcha.verify(params["frc-captcha-response"]) douser =params["user"]|> Map.put("email", invitation.email)@@ -269,21 +253,26 @@ defmodule PlausibleWeb.Live.RegisterForm doadd_user(socket, user, with_team?: with_team?)else- {:noreply, assign(socket, :captcha_error, "Please complete the captcha to register")}+ {:noreply, captcha_failed(socket)}endenddef handle_event("register", %{"user" => _} = params, socket) do- if not PlausibleWeb.Captcha.enabled?() or- PlausibleWeb.Captcha.verify(params["h-captcha-response"]) do+ if PlausibleWeb.Captcha.verify(params["frc-captcha-response"]) douser = Auth.User.new(params["user"])add_user(socket, user)else- {:noreply, assign(socket, :captcha_error, "Please complete the captcha to register")}+ {:noreply, captcha_failed(socket)}endend+ defp captcha_failed(socket) do+ socket+ |> assign(:captcha_error, "Please complete the captcha to register")+ |> PlausibleWeb.Components.Captcha.reset()+ end+defp add_user(socket, user, opts \\ []) doresult =Repo.transaction(fn ->@@ -297,10 +286,12 @@ defmodule PlausibleWeb.Live.RegisterForm do{:noreply, assign(socket, trigger_submit: true)}{:error, changeset} ->- {:noreply,- assign(socket,- form: to_form(Map.put(changeset, :action, :validate))- )}+ socket =+ socket+ |> assign(form: to_form(Map.put(changeset, :action, :validate)))+ |> PlausibleWeb.Components.Captcha.reset()++ {:noreply, socket}endenddiff --git a/lib/plausible_web/templates/auth/password_reset_request_form.html.heex b/lib/plausible_web/templates/auth/password_reset_request_form.html.heexindex 806bfebdb6..14d7d22b09 100644--- a/lib/plausible_web/templates/auth/password_reset_request_form.html.heex+++ b/lib/plausible_web/templates/auth/password_reset_request_form.html.heex@@ -25,18 +25,21 @@</div><%= if PlausibleWeb.Captcha.enabled?() do %>- <div>- <div class="h-captcha" data-sitekey={PlausibleWeb.Captcha.sitekey()}></div>- <p :if={assigns[:captcha_error]} class="text-xs text-red-500 mt-2">- {@captcha_error}- </p>- <script src="https://hcaptcha.com/1/api.js" async defer>- </script>- </div>+ <PlausibleWeb.Components.Captcha.widget error={assigns[:captcha_error]} /><% end %><div class="flex flex-col gap-y-4">- <.button class="w-full" type="submit" mt?={false}>Send reset link</.button>+ <.button+ class="w-full"+ type="submit"+ mt?={false}+ x-data={"{ captchaReady: #{not PlausibleWeb.Captcha.enabled?()} }"}+ x-on:frc-captcha-ready.window="captchaReady = true"+ x-on:frc-captcha-reset.window="captchaReady = false"+ x-bind:disabled="!captchaReady"+ >+ Send reset link+ </.button><p class="text-sm text-center text-gray-500 dark:text-gray-400"><.styled_link href="/login">Back to sign in</.styled_link>diff --git a/mix.exs b/mix.exsindex 63aa67da35..bc757995dd 100644--- a/mix.exs+++ b/mix.exs@@ -199,6 +199,7 @@ defmodule Plausible.MixProject do# mix test.e2e --debug segments.spec.ts"test.e2e": ["esbuild default",+ "esbuild friendly_captcha","ecto.create --quiet","ecto.migrate","clean_postgres",@@ -209,11 +210,14 @@ defmodule Plausible.MixProject do"assets.typecheck": ["cmd npm --prefix assets run typecheck"],"assets.build": ["tailwind default",- "esbuild default"+ "esbuild default",+ "esbuild friendly_captcha"],"assets.deploy": ["tailwind default --minify","esbuild default --minify",+ # already minified upstream, so no --minify here+ "esbuild friendly_captcha","phx.digest"]]diff --git a/test/plausible_web/captcha_test.exs b/test/plausible_web/captcha_test.exsindex 7308283bf3..141e7510dd 100644--- a/test/plausible_web/captcha_test.exs+++ b/test/plausible_web/captcha_test.exs@@ -7,16 +7,18 @@ defmodule PlausibleWeb.CaptchaTest doalias PlausibleWeb.Captchadescribe "mocked payloads" do- @failure Jason.decode!(~s/{"success":false,"error-codes":["invalid-input-response"]}/)+ @failure Jason.decode!(+ ~s/{"success":false,"error":{"error_code":"response_invalid","detail":"the response was invalid"}}/+ )@success Jason.decode!(~s/{"success":true}/)test "returns false for non-success response" doexpect(Plausible.HTTPClient.Mock,:post,- fn "https://hcaptcha.com/siteverify",- [{"content-type", "application/x-www-form-urlencoded"}],- %{response: "bad", secret: "scottiger"} ->+ fn "https://global.frcapi.com/api/v2/captcha/siteverify",+ [{"content-type", "application/json"}, {"x-api-key", "scottiger"}],+ %{response: "bad", sitekey: "test"} ->{:ok,%Finch.Response{status: 200,@@ -33,9 +35,9 @@ defmodule PlausibleWeb.CaptchaTest doexpect(Plausible.HTTPClient.Mock,:post,- fn "https://hcaptcha.com/siteverify",- [{"content-type", "application/x-www-form-urlencoded"}],- %{response: "good", secret: "scottiger"} ->+ fn "https://global.frcapi.com/api/v2/captcha/siteverify",+ [{"content-type", "application/json"}, {"x-api-key", "scottiger"}],+ %{response: "good", sitekey: "test"} ->{:ok,%Finch.Response{status: 200,@@ -50,7 +52,7 @@ defmodule PlausibleWeb.CaptchaTest doenddescribe "with patched application env" do- setup_patch_env(:hcaptcha, sitekey: nil)+ setup_patch_env(:friendly_captcha, sitekey: nil)test "returns true when disabled" doassert Captcha.verify("disabled")diff --git a/test/plausible_web/live/register_form_test.exs b/test/plausible_web/live/register_form_test.exsindex 7563b9ab76..eab969c08b 100644--- a/test/plausible_web/live/register_form_test.exs+++ b/test/plausible_web/live/register_form_test.exs@@ -91,9 +91,27 @@ defmodule PlausibleWeb.Live.RegisterFormTest dohtml = lv |> element("form") |> render_submit()assert html =~ "Please complete the captcha to register"+ assert_push_event(lv, "reset-frc-captcha", %{})refute Repo.one(User)end++ test "resets the captcha when registration fails", %{conn: conn} do+ mock_captcha_success()++ new_user(email: "[email protected]")++ lv = get_liveview(conn, "/register")++ type_into_input(lv, "user[name]", "Mary Sue")+ type_into_input(lv, "user[email]", "[email protected]")+ type_into_input(lv, "user[password]", "very-long-and-very-secret-123")++ html = lv |> element("form") |> render_submit()++ assert html =~ "has already been taken"+ assert_push_event(lv, "reset-frc-captcha", %{})+ endenddescribe "/register/invitation/:invitation_id" do@@ -242,6 +260,7 @@ defmodule PlausibleWeb.Live.RegisterFormTest dohtml = lv |> element("form") |> render_submit()assert html =~ "Please complete the captcha to register"+ assert_push_event(lv, "reset-frc-captcha", %{})refute Repo.get_by(User, email: "[email protected]")end