1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Captcha do
6 alias Calendar.DateTime
7 alias Plug.Crypto.KeyGenerator
8 alias Plug.Crypto.MessageEncryptor
10 @cachex Pleroma.Config.get([:cachex, :provider], Cachex)
13 Ask the configured captcha service for a new captcha
19 new_captcha = method().new()
21 # This make salt a little different for two keys
22 {secret, sign_secret} = secret_pair(new_captcha[:token])
24 # Basically copy what Phoenix.Token does here, add the time to
25 # the actual data and make it a binary to then encrypt it
26 encrypted_captcha_answer =
28 at: DateTime.now_utc(),
29 answer_data: new_captcha[:answer_data]
31 |> :erlang.term_to_binary()
32 |> MessageEncryptor.encrypt(secret, sign_secret)
34 # Replace the answer with the encrypted answer
35 %{new_captcha | answer_data: encrypted_captcha_answer}
40 Ask the configured captcha service to validate the captcha
42 def validate(token, captcha, answer_data) do
43 with {:ok, %{at: at, answer_data: answer_md5}} <- validate_answer_data(token, answer_data),
44 :ok <- validate_expiration(at),
45 :ok <- validate_usage(token),
46 :ok <- method().validate(token, captcha, answer_md5),
47 {:ok, _} <- mark_captcha_as_used(token) do
52 def enabled?, do: Pleroma.Config.get([__MODULE__, :enabled], false)
54 defp seconds_valid, do: Pleroma.Config.get!([__MODULE__, :seconds_valid])
56 defp secret_pair(token) do
57 secret_key_base = Pleroma.Config.get!([Pleroma.Web.Endpoint, :secret_key_base])
58 secret = KeyGenerator.generate(secret_key_base, token <> "_encrypt")
59 sign_secret = KeyGenerator.generate(secret_key_base, token <> "_sign")
64 defp validate_answer_data(token, answer_data) do
65 {secret, sign_secret} = secret_pair(token)
67 with false <- is_nil(answer_data),
68 {:ok, data} <- MessageEncryptor.decrypt(answer_data, secret, sign_secret),
69 %{at: at, answer_data: answer_md5} <- :erlang.binary_to_term(data) do
70 {:ok, %{at: at, answer_data: answer_md5}}
72 _ -> {:error, :invalid_answer_data}
76 defp validate_expiration(created_at) do
77 # If the time found is less than (current_time-seconds_valid) then the time has already passed
78 # Later we check that the time found is more than the presumed invalidatation time, that means
79 # that the data is still valid and the captcha can be checked
81 valid_if_after = DateTime.subtract!(DateTime.now_utc(), seconds_valid())
83 if DateTime.before?(created_at, valid_if_after) do
90 defp validate_usage(token) do
91 if is_nil(@cachex.get!(:used_captcha_cache, token)) do
94 {:error, :already_used}
98 defp mark_captcha_as_used(token) do
99 ttl = seconds_valid() |> :timer.seconds()
100 @cachex.put(:used_captcha_cache, token, true, ttl: ttl)
103 defp method, do: Pleroma.Config.get!([__MODULE__, :method])