Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Friendly captcha (#6546)

Uku Taht7007a3f9563e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 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
### Fixed
diff --git a/assets/package-lock.json b/assets/package-lock.json
index 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.json
index 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.test
index 42a1e85526..354c0bffdb 100644
--- a/config/.env.test
+++ b/config/.env.test
@@ -9,8 +9,8 @@ ENVIRONMENT=test
MAILER_ADAPTER=Bamboo.TestAdapter
ENABLE_EMAIL_VERIFICATION=true
SELFHOST=false
-HCAPTCHA_SITEKEY=test
-HCAPTCHA_SECRET=scottiger
+FRIENDLY_CAPTCHA_SITEKEY=test
+FRIENDLY_CAPTCHA_API_KEY=scottiger
IP_GEOLOCATION_DB=test/priv/GeoLite2-City-Test.mmdb
SITE_DEFAULT_INGEST_THRESHOLD=1000000
GOOGLE_CLIENT_ID=fake_client_id
diff --git a/config/config.exs b/config/config.exs
index 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.exs
index 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.exs
index c78ed517e9..abc25e0f31 100644
--- a/config/runtime.exs
+++ b/config/runtime.exs
@@ -312,8 +312,8 @@ if disable_registration not in [true, false, :invite_only] do
raise "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 @@ else
queues: queues
end
-config :plausible, :hcaptcha,
- sitekey: hcaptcha_sitekey,
- secret: hcaptcha_secret
+config :plausible, :friendly_captcha,
+ sitekey: friendly_captcha_sitekey,
+ api_key: friendly_captcha_api_key
nolt_sso_secret = get_var_from_path_or_env(config_dir, "NOLT_SSO_SECRET")
config :joken, default_signer: nolt_sso_secret
diff --git a/lib/plausible_web/captcha.ex b/lib/plausible_web/captcha.ex
index 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? do
is_binary(sitekey())
end
def sitekey() do
- Application.get_env(:plausible, :hcaptcha, [])[:sitekey]
+ Application.get_env(:plausible, :friendly_captcha, [])[:sitekey]
end
def verify(token) do
@@ -16,10 +20,10 @@ defmodule PlausibleWeb.Captcha do
res =
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 do
end
end
- defp secret() do
- Application.get_env(:plausible, :hcaptcha, [])[:secret]
+ defp api_key() do
+ Application.get_env(:plausible, :friendly_captcha, [])[:api_key]
end
end
diff --git a/lib/plausible_web/components/captcha.ex b/lib/plausible_web/components/captcha.ex
new file mode 100644
index 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
+end
diff --git a/lib/plausible_web/components/layout.ex b/lib/plausible_web/components/layout.ex
index 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 do
function 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.ex
index 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 do
end
def 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"]) do
case 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.ex
index 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 do
else
"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"]) do
user =
params["user"]
|> Map.put("email", invitation.email)
@@ -269,21 +253,26 @@ defmodule PlausibleWeb.Live.RegisterForm do
add_user(socket, user, with_team?: with_team?)
else
- {:noreply, assign(socket, :captcha_error, "Please complete the captcha to register")}
+ {:noreply, captcha_failed(socket)}
end
end
def 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"]) do
user = 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)}
end
end
+ 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 \\ []) do
result =
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}
end
end
diff --git a/lib/plausible_web/templates/auth/password_reset_request_form.html.heex b/lib/plausible_web/templates/auth/password_reset_request_form.html.heex
index 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.exs
index 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.exs
index 7308283bf3..141e7510dd 100644
--- a/test/plausible_web/captcha_test.exs
+++ b/test/plausible_web/captcha_test.exs
@@ -7,16 +7,18 @@ defmodule PlausibleWeb.CaptchaTest do
alias PlausibleWeb.Captcha
describe "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" do
expect(
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 do
expect(
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 do
end
describe "with patched application env" do
- setup_patch_env(:hcaptcha, sitekey: nil)
+ setup_patch_env(:friendly_captcha, sitekey: nil)
test "returns true when disabled" do
assert Captcha.verify("disabled")
diff --git a/test/plausible_web/live/register_form_test.exs b/test/plausible_web/live/register_form_test.exs
index 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 do
html = 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", %{})
+ end
end
describe "/register/invitation/:invitation_id" do
@@ -242,6 +260,7 @@ defmodule PlausibleWeb.Live.RegisterFormTest do
html = 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