Viewing latest docs.
Switch version: v3

Upgrade guide

How to upgrade your PetalPro project to the latest versions

Version updates can be a bit of a manual process. A boilerplate is meant to be a starting point for you to build from - rather than a framework like Phoenix. However, it is possible.

4.5.1 -> 4.5.2

Petal Pro 4.5.2 is a security patch for sign-in. The browser sign-in form had no limit at all, and now an account gets ten tries per ten minutes. Every limit that protects an account is now counted on the account, not on the email as typed, which closes a way round the 4.5.1 pin limit. Confirmation emails can’t be resent without limit, and an admin can no longer impersonate a user before finishing two-factor. There are no migrations, no dependency changes and no new settings. Users see one new cookie, and “Too many attempts” where a limit refuses.

If you never customised the files below, the work is: take the ten changed lib/ files, replace test/petal_pro_web/controllers/user_passkey_controller_test.exs, add the new cookie to your cookie policy, and run the checks in step 6. On 4.5.0 or older, start at step 8.

⚠️ Warning: 4.5.2 needs 4.5.1 underneath. On 4.5.0 with every file below, mix compile warns that UserPin.check_pin/3 is undefined (it arrived in 4.5.1), and entering a passwordless pin crashes. The new controllers call PetalProWeb.ClientIp.rate_limit_key/2, also from 4.5.1: take one without the new client_ip.ex and API sign-in and registration fail with a 500 on every request, and browser password and passkey sign-in do once CLIENT_IP_HEADER or TRUSTED_PROXY_HOPS is set. Either way you would be without 4.5.1's own fixes. And if you merge user_session_controller.ex by hand, check the three steps marked "don't skip" in step 3. Skip one and nothing raises an error, but the limit doesn't do its job. Comparing the password before counting gives no sign at all. Leaving out the clear or the remember call only leaves an "unused function" warning from mix compile, which --warnings-as-errors turns into a failure.

1. Take the changed files

Every file the release changes, grouped by fix. Each changed file works next to the 4.5.1 version of every other file, so you can take them one at a time. A file you leave behind leaves its own fix out, with one catch: the API half of the reset fix in user_reset_password_live.ex only works with the new API session_controller.ex.

The test/ files are optional but worth having: they prove each limit holds. A test needs the lib/ files of its group, and the few that need a file from another group say so. The one test you must replace is test/petal_pro_web/controllers/user_passkey_controller_test.exs. Its 4.5.1 copy has a test, “the eleventh attempt from one address within a minute goes back to sign-in with a message”, that fails against the new passkey controller, because with no client address set that limit no longer applies. The 4.5.2 copy moves that test into client_ip_test.exs, which sets an address first. The tests use test/support/rate_limit_helpers.ex from 4.5.1, unchanged.

Browser password sign-in limit (the two lib/ files run without each other):

  • lib/petal_pro_web/controllers/user_session_controller.ex (the limits, the trusted-browser cookie, and a malformed post answered as a failed sign-in instead of a 500)
  • lib/petal_pro_web/live/auth/user_reset_password_live.ex (a password reset starts the account’s browser and API sign-in counts again; the API half needs the new API session_controller.ex from the next group, because the 4.5.1 one counts on the email text, not the account)
  • test/petal_pro_web/controllers/user_session_controller_test.exs
  • test/petal_pro_web/controllers/user_session_address_limit_test.exs (new; its IPv6 test needs the new client_ip.ex)
  • test/petal_pro_web/live/auth/user_reset_password_live_test.exs (needs the new user_session_controller.ex and the new API session_controller.ex too)

Account limits counted on the account (each file works on its own):

  • lib/petal_pro_web/live/auth/passwordless_auth_live.ex
  • lib/petal_pro_api/controllers/session_controller.ex
  • lib/petal_pro_web/live/auth/user_forgot_password_live.ex
  • test/petal_pro_web/live/passwordless_auth_live_test.exs
  • test/petal_pro_api/session_controller_test.exs
  • test/petal_pro_web/live/auth/user_forgot_password_live_test.exs

Impersonation with a second factor pending:

  • lib/petal_pro_web/controllers/user_impersonation_controller.ex
  • test/petal_pro_web/controllers/pending_two_factor_test.exs (new)

Confirmation email resends (one count, shared by the two doors):

  • lib/petal_pro_web/live/auth/user_confirmation_instructions_live.ex
  • lib/petal_pro_api/controllers/registration_controller.ex
  • test/petal_pro_web/live/auth/user_confirmation_instructions_live_test.exs (one test resends through the API, so it needs the new registration_controller.ex too)
  • test/petal_pro_api/registration_controller_test.exs

IPv6 counted by /64, and the passkey limit only with a client address:

  • lib/petal_pro_web/client_ip.ex
  • lib/petal_pro_web/controllers/user_passkey_controller.ex
  • test/petal_pro_web/client_ip_test.exs (its passkey tests need the new passkey controller)
  • test/petal_pro_web/controllers/user_passkey_controller_test.exs (replace your 4.5.1 copy, see above)

Comments, docs and recipes: config/runtime.exs (the comment above the client IP settings), DEPLOYMENT.md, CHANGELOG.md, CLAUDE.md, AGENTS.md, .claude/commands/recipes/add-saml-sso.md (where the SSO check goes now), .claude/commands/recipes/remove-2fa.md (what to keep in the new impersonation check) and mix.exs (@version only). Nothing in them changes behaviour.

2. Tell the app which address is the client’s

The account limits need no setting. Four limits count per address. Two of them, browser sign-in (100 failed tries per ten minutes from one address, across every account) and passkey sign-in (10 a minute), only apply since 4.5.2 once the app knows the client’s address. That means CLIENT_IP_HEADER or TRUSTED_PROXY_HOPS is set, and the request’s address came from it rather than falling back to the peer. Without either, every visitor behind your proxy has the proxy’s address, and one caller could use the count up for all of them, so the app leaves those two limits off. The other two, API sign-in (5 a minute) and API registration (3 an hour), count per address as they did in 4.5.1, so without a setting each is one budget for your whole app.

If you set one of these for 4.5.0 or 4.5.1, you’re done here. If you didn’t, step 2 of the 4.5.0 -> 4.5.1 upgrade shows the setting for Fly, Cloudflare and nginx. Until you do, each machine logs one warning per boot, at the first password sign-in that arrives with proxy headers (step 4 has the text), and a script trying one password against many accounts is only limited per account.

3. If you customised these files

  • user_session_controller.ex - its code was the same in every 4.x release up to 4.5.1, so anything different in yours is your own change. The simplest way is to take the new file and put your change back in the right place:

    • A check that has to run before the password is compared, like the SSO rule from the SAML recipe (check_sso_enforcement/1), goes in sign_in/6, inside the {:ok, counted} branch and before check_password/6. A comment marks the place. There the attempt has already been counted, and a malformed post never gets that far. Don’t put it in create/3 or before count_sign_in/4, where it would run for attempts nobody counts.
    • Something for a successful sign-in, like an extra log line, goes in the success branch of check_password/6, after clear_sign_in_limits(counted) and before the conn pipeline. Don’t set session data there: UserAuth.log_in_user/3 renews the session, which clears it, and the response has been sent by the time it returns. Session data that should survive sign-in belongs in UserAuth.put_user_into_session/2, after renew_session/1. Every sign-in goes through it, and so does impersonation.
    • Something for a failed sign-in goes in the else branch of check_password/6.

    If you’d rather merge into your own copy, bring over the PetalPro.RateLimiter and PetalProWeb.ClientIp aliases and require Logger, the seven module attributes from @window to @device_entries, the two private create/3 clauses (they replace the old one, whose password check moves into check_password/6), and every private function from sign_in/6 to the end of the module. create/2, delete/2 and create_from_token/2 don’t change. Then check these three. Don’t skip them. None raises an error when it’s missing. The first gives no warning at all, and the other two only an “unused function” warning, so also run mix compile --warnings-as-errors.

    1. Count before you compare. count_sign_in/4 runs before Accounts.get_user_by_email_and_password/2. Compare first and the limit stops nothing, because the right password gets in however many wrong ones came before it.
    2. Clear the counts on success. Keep clear_sign_in_limits(counted) in the success branch, with the @dialyzer {:nowarn_function, clear_sign_in_limits: 1} line above the function. Skip it and a user who signs in ten times in ten minutes is refused for their own successes, and the address count counts successes as well as failures.
    3. Remember the browser on success. Keep remember_device/2 in the success branch. Skip it and no browser is ever trusted, so anyone who knows an email can lock its owner out of password sign-in on every browser.
  • user_reset_password_live.ex - in handle_event("reset_password", ...), keep the user from the {:ok, _} branch and clear its counts:

lib/petal_pro_web/live/auth/user_reset_password_live.ex
- {:ok, _} ->
+ {:ok, user} ->
+ clear_sign_in_limit(user)
+

Then add the helper. The keys are the ones the browser and API sign-in count on, and the window has to match theirs:

@dialyzer {:nowarn_function, clear_sign_in_limit: 1}
defp clear_sign_in_limit(user) do
PetalPro.RateLimiter.set("web_sign_in_account:" <> user.id, to_timeout(minute: 10), 0)
PetalPro.RateLimiter.set("api_sign_in_account:" <> user.id, to_timeout(minute: 10), 0)
end
  • passwordless_auth_live.ex - the pin limit is now counted on the account, so send_pin/2 finds or creates the account first. Move Accounts.get_or_create_user/2 to the top of the with, hit the limit on the user, and move the {:deny, _retry_after} clause (with its “Too many attempts” message) into the else. Then key on the id. This replaces the lower-casing from step 3 of the 4.5.1 upgrade:
lib/petal_pro_web/live/auth/passwordless_auth_live.ex
with {:ok, user} <- Accounts.get_or_create_user(%{email: email}, "passwordless"),
{:allow, _count} <- PetalPro.RateLimiter.hit(pin_limit_key(user), to_timeout(minute: 10), 3),
pin when not is_nil(pin) <- UserPin.create_pin(user),
{:ok, email} <- UserMailer.deliver_passwordless_pin(user, pin) do
# ...
defp pin_limit_key(%User{id: id}), do: "passwordless_pin:" <> id
  • Every file that counts an email with no account (user_session_controller.ex, the API session_controller.ex, user_forgot_password_live.ex, user_confirmation_instructions_live.ex and the API registration_controller.ex) - each has its own copy of this helper, on purpose, so no file needs another. It lets the database fold the text the way the email column compares it, and hashes anything longer than an email can be:
defp limit_email(email) do
%{rows: [[folded]]} = PetalPro.Repo.query!("SELECT lower($1::text)", [String.trim(email)])
if byte_size(folded) <= 320 do
folded
else
"sha256:" <> Base.url_encode64(:crypto.hash(:sha256, folded), padding: false)
end
end
  • The API session_controller.ex - look the account up in hit_account_limit/1 and key on it, and clear by user. In create/2, clear_account_limit(email) becomes clear_account_limit(user). Keep the @dialyzer line above clear_account_limit/1:
lib/petal_pro_api/controllers/session_controller.ex
defp hit_account_limit(email) when is_binary(email) do
text = limit_email(email)
key =
case Accounts.get_user_by_email(String.trim(email)) do
%User{} = user -> account_limit_key(user)
nil -> "api_sign_in_unknown:" <> text
end
PetalPro.RateLimiter.hit(key, @account_window, 10)
end
defp clear_account_limit(user), do: PetalPro.RateLimiter.set(account_limit_key(user), @account_window, 0)
defp account_limit_key(%User{id: id}), do: "api_sign_in_account:" <> id
  • user_forgot_password_live.ex - look the user up before the hit, with String.trim/1, and use that user in the {:allow, _} branch instead of looking it up again. Add alias PetalPro.Accounts.User, add when is_binary(email) to the send_email handler, and a catch-all after it: def handle_event("send_email", _params, socket), do: {:noreply, socket}. The key:
lib/petal_pro_web/live/auth/user_forgot_password_live.ex
user = Accounts.get_user_by_email(String.trim(email))
case PetalPro.RateLimiter.hit(reset_limit_key(user, email), to_timeout(minute: 10), 3) do
# ...
defp reset_limit_key(user, email) do
text = limit_email(email)
case user do
%User{id: id} -> "password_reset:" <> id
nil -> "password_reset_unknown:" <> text
end
end
  • user_confirmation_instructions_live.ex and the API registration_controller.ex - both get the same new limit, and they must use the same key strings or the two doors get a count each. In the LiveView, look the user up with String.trim/1, wrap the send and its flash in PetalPro.RateLimiter.hit(confirm_limit_key(user, email), to_timeout(minute: 10), 3), and on {:deny, _} put the error flash “Too many attempts. Please try again later.” and redirect to ~p"/", the same page as a send. Add the is_binary(email) guard and a catch-all clause as above. Add alias PetalPro.Accounts.User to both files, because the key below matches on it. In the API controller, add plug :rate_limit_send_instructions when action in [:send_instructions] and copy rate_limit_send_instructions/2 from the 4.5.2 file: it answers a refusal with a 429 and leaves a request with no email to the action. Both use this key:
defp confirm_limit_key(user, email) do
text = limit_email(email)
case user do
%User{id: id} -> "confirm_instructions:" <> id
nil -> "confirm_instructions_unknown:" <> text
end
end
  • user_impersonation_controller.ex - add the plug and its function:
lib/petal_pro_web/controllers/user_impersonation_controller.ex
plug :require_completed_sign_in when action in [:create]
# ...
defp require_completed_sign_in(conn, _opts) do
cond do
get_session(conn, :user_passkey_pending) ->
conn |> redirect(to: ~p"/app/users/passkey-verify") |> halt()
get_session(conn, :user_totp_pending) ->
conn |> redirect(to: ~p"/app/users/totp") |> halt()
true ->
conn
end
end

If you removed 2FA with the recipe, delete only the :user_totp_pending clause (its route is gone) and keep the passkey one. If you have routes of your own piped through :require_admin_user without :require_authenticated_user (or the :authenticated pipeline), add it: :require_admin_user doesn’t look at a pending second factor, so those routes have the same hole.

  • user_passkey_controller.ex - wrap the passkey_auth hit in rate_limit/2 in if address_limited?(conn) do ... else conn end, and copy address_limited?/1 and peer/1 from the 4.5.2 file. They are the same two functions as in user_session_controller.ex.
  • client_ip.ex - bring over the private resolve/2, group/1 and ipv4/2 and the new body of rate_limit_key/2. get/2 returns exactly what it did, so last_signed_in_ip and the audit log still hold the full address.
  • A limit of your own on an email - if you added one (on a form that sends mail, say), look the account up and key on user.id, the way the stock files do now. A key built from the typed text, even lower-cased, gets a fresh count for every spelling the database treats as the same email. See Rate Limiting.

4. What your users will notice

  • Browser sign-in: ten tries per ten minutes per account, from any browser that hasn’t signed in to it before. The eleventh is refused even with the right password: the user lands back on the sign-in page with “Too many attempts. Please try again later.” and waits for the window to end, ten minutes at most (the windows line up with the clock). A correct password counted on the account starts the count again. A sign-in from a trusted browser (next point) doesn’t touch the account’s count, so other browsers stay refused until the window ends or the password is reset. An email with no account gets exactly the same answer, so a refusal doesn’t show which emails have accounts.
  • A new cookie. A successful password sign-in sets _petal_pro_web_sign_in_device: encrypted, HttpOnly, SameSite=Lax, kept for one year, and Secure over https. A browser that holds it for an account gets ten tries of its own first and then the account’s ten, so a stranger who uses up the account’s count can’t lock the owner out of the browser they normally use. It grants no access, remembers up to five accounts on a shared computer, and stops counting for an account once that account’s password changes. List it in your cookie policy as a security cookie. See Trusted Browsers.
  • Password reset gets a locked-out user back in. A successful reset starts the account’s browser and API sign-in counts again, on the machine that serves the reset. It also ends the trust of every browser that signed in under the old password.
  • Confirmation emails: the fourth resend for one account within ten minutes is refused. The form goes to the home page with “Too many attempts. Please try again later.” and POST /api/send-instructions gets a 429 with {"errors": {"detail": "Too many requests"}}. The two share one count. An email with no account, and one already confirmed, spend it the same way.
  • Password reset requests: still three per ten minutes, now per account, so every capitalisation of one email shares a count. In 4.5.1 the count was on the text exactly as typed.
  • Passkey sign-in: with neither CLIENT_IP_HEADER nor TRUSTED_PROXY_HOPS set, it’s no longer limited per address. With one set, it’s 10 a minute per address as before.
  • Admins with two-factor: an admin who has typed their password but not their code is sent to the code step (/app/users/totp or /app/users/passkey-verify) if they try to impersonate. After the code, impersonation works as before.
  • A malformed sign-in post (no email, or a list where text should be) gets “Invalid email or password” instead of a 500, and isn’t counted.
  • Your logs: with neither address setting made, the first sign-in after each boot that arrives with a proxy header (x-forwarded-for, fly-client-ip or cf-connecting-ip) logs Browser sign-in has no per-address limit: proxy headers are present but neither CLIENT_IP_HEADER nor TRUSTED_PROXY_HOPS is set. See DEPLOYMENT.md. Fly adds fly-client-ip to every request, so on Fly each machine logs it once after every boot until you set the header. A refused count also logs Browser sign-in refused: too many attempts ... once per count per window. It names the account id, or says the email has no account, or gives the address key. It never logs the email.
  • Your test suite: a test that posts more than ten wrong passwords for one account within ten minutes now gets the refusal. Give each test its own user, as the fixtures do. A test that drives a count right up to its limit can call PetalPro.RateLimitHelpers.stay_in_window/1 first, so the window doesn’t end halfway through.

5. Clear a locked account by hand

The counts live in memory on each machine, so a restart or a deploy clears them all. To clear one account without that, open a remote IEx shell on each machine. On Fly, pick each machine in turn:

fly ssh console --app your-app-name --select
/app/bin/your_app remote

Then:

user = PetalPro.Accounts.get_user_by_email("someone@example.com")
PetalPro.RateLimiter.set("web_sign_in_account:" <> user.id, to_timeout(minute: 10), 0)
PetalPro.RateLimiter.set("api_sign_in_account:" <> user.id, to_timeout(minute: 10), 0)

The window has to be the one the limit uses, ten minutes here, or you set a different count. Asking the user to reset their password does the same on the machine that serves the reset.

6. Check it worked

  1. If you took the test files, run them, for example mix test test/petal_pro_web/controllers/user_session_controller_test.exs test/petal_pro_web/controllers/pending_two_factor_test.exs test/petal_pro_web/controllers/user_passkey_controller_test.exs. Name only files you have: mix test skips a path that doesn’t exist without saying so, and a 4.5.1 copy of a test tests none of the new limits. If you took only the lib/ files and the passkey test, run the whole suite with mix test. It should pass, but it doesn’t test the new limits, so checks 3 to 7 are your proof
  2. Run the next checks locally, or on one machine. With several, the count is per machine and a refusal can take more tries
  3. In your normal browser, sign in with a password once, then sign out. Your browser’s dev tools should show the _petal_pro_web_sign_in_device cookie, HttpOnly, SameSite Lax, expiring in a year
  4. Open a private window and sign in to the same account with a wrong password ten times. Each should say “Invalid email or password”. Then try the right password: it should say “Too many attempts. Please try again later.” If the right password signs you in instead, the tries crossed a ten-minute boundary on the clock, so try again
  5. Back in your normal browser, the right password should sign you in. That’s the cookie doing its job. It doesn’t clear the account’s count, so the private window is still refused
  6. Clear the count from check 4 with the snippet in step 5 (“Clear a locked account by hand”). Locally, if you started the server with iex -S mix phx.server, paste it into that shell; otherwise restarting the server clears every count. Or wait ten minutes
  7. On /auth/confirm, ask for the confirmation email four times for the same address. The fourth should say “Too many attempts”. Locally, the ones that were sent land in /dev/mailbox
  8. In production, after the deploy and once someone has signed in with a password, look for the “Browser sign-in has no per-address limit” warning in your logs. It’s logged at the first such sign-in on each machine, not at boot. If it’s there, do step 2. No warning doesn’t prove the per-address limit is on: with a header set that your proxy doesn’t send, every request falls back to the peer and the limit stays off without a warning. Check last_signed_in_ip on your own user shows your public address

7. What still isn’t limited

4.5.2 doesn’t limit these. Put a limit in front of them yourself if your app is a target, or use your proxy’s rate limiting:

  • Browser registration (/auth/register), and the account passwordless sign-in creates for a new email. Each one sends an email to the address it was given. Resends are limited now; the first email isn’t.
  • Email a signed-in user can send by changing their email address or inviting people to an org.
  • The current-password check on the settings pages, for someone who already has a signed-in session.

And with no client address setting, a script trying one password against many accounts is only limited per account. Step 2 adds a per-address limit on top, which slows one source down but doesn’t stop a caller with many addresses.

8. On an older 4.x version

4.5.2 is built on 4.5.1. On 4.5.0, do the 4.5.0 -> 4.5.1 upgrade first, then this one. On 4.4.0 or older, work up through each section below.

If you can’t do that yet, some of the fixes don’t need 4.5.x. The first three files below have the same code in every 4.x release up to 4.5.1, and their new code only calls functions every 4.x has. The fourth needs one 4.5.1 file beside it:

  • lib/petal_pro_web/controllers/user_impersonation_controller.ex - the impersonation fix. On 4.0.x, which has no passkeys, delete the :user_passkey_pending clause from require_completed_sign_in/2, or mix compile warns that no route matches /app/users/passkey-verify.
  • lib/petal_pro_web/live/auth/user_forgot_password_live.ex - the reset request limit, per account.
  • lib/petal_pro_web/live/auth/user_confirmation_instructions_live.ex - the resend limit on the browser form. The API side is in registration_controller.ex, which needs 4.5.1.
  • lib/petal_pro_web/live/auth/passwordless_auth_live.ex - the pin limit on the account, together with lib/petal_pro/accounts/user_pin.ex from 4.5.1. Step 6 of the 4.5.1 upgrade covers that pair.

The browser sign-in limit waits for 4.5.1. user_session_controller.ex calls PetalProWeb.ClientIp, new in 4.5.0, and its rate_limit_key/2, new in 4.5.1. Before 4.5.0 it compiles with two warnings (PetalProWeb.ClientIp.get/1 and rate_limit_key/2 are undefined), which fail mix compile --warnings-as-errors. Your tests can still pass, so don’t read that as safe: the warning it logs on Fly tells you to set CLIENT_IP_HEADER, which does nothing before 4.5.0. On 4.5.0 without the new client_ip.ex beside it, it compiles with one warning (rate_limit_key/2 is undefined), and once a client address setting is made it is the 500 in the warning above. user_reset_password_live.ex is safe on any 4.x, but without the new sign-in controller it clears a browser count nothing reads, and without the new API session_controller.ex it clears an API count nothing reads. The API controllers, client_ip.ex and the passkey controller build on 4.5.1 too.

The tests were written against 4.5.1, and all but pending_two_factor_test.exs need test/support/rate_limit_helpers.ex from it. Before 4.5.0, also change every [role=alert] in passwordless_auth_live_test.exs to [role=dialog] (there are six in the 4.5.2 copy), or five of its tests fail even though the fix works. And expect one test in user_confirmation_instructions_live_test.exs, the one that resends through the API, to fail until you have the 4.5.2 registration_controller.ex, which needs 4.5.1.


4.5.0 -> 4.5.1

Petal Pro 4.5.1 is a security patch. It closes four ways round the sign-in rate limits: a passwordless pin could be guessed without limit, two-factor codes had no limit at all, API sign-in was only limited per address, and the API and passkey limits counted your proxy instead of the visitor. There are no migrations and no dependency changes. The only UI change is a “Too many attempts” message where a limit refuses.

If you never customised the files below, the work is: take the seven changed lib/ files and test/petal_pro/user_pin_test.exs, set CLIENT_IP_HEADER or TRUSTED_PROXY_HOPS if you haven’t since 4.5.0, and run the check in step 5. On 4.4.0 or older, start at step 6.

⚠️ Warning: take user_pin.ex and passwordless_auth_live.ex together. The new LiveView calls UserPin.check_pin/3, which only exists in the new user_pin.ex. With only the new LiveView, mix compile prints a warning and every pin submit crashes, so passwordless sign-in stops working. Likewise take client_ip.ex with any of the session, registration or passkey controllers: they call PetalProWeb.ClientIp.rate_limit_key/2, and without it every API sign-in, API registration and passkey sign-in attempt is a 500.

1. Take the changed files

Every file the release changes, grouped by fix. The test/ files are optional but worth having: they prove each limit holds. The one exception is test/petal_pro/user_pin_test.exs: take it with the new user_pin.ex, because the 4.5.0 version fails against it.

Passwordless pin limit (take both lib/ files together):

  • lib/petal_pro/accounts/user_pin.ex
  • lib/petal_pro_web/live/auth/passwordless_auth_live.ex
  • test/petal_pro/user_pin_test.exs (not optional, see above)
  • test/petal_pro_web/live/passwordless_auth_live_test.exs

Two-factor limit:

  • lib/petal_pro_web/controllers/user_totp_controller.ex
  • test/petal_pro_web/controllers/user_totp_controller_test.exs

API sign-in per-account limit, and the API and passkey limits keyed on the client:

  • lib/petal_pro_web/client_ip.ex (adds PetalProWeb.ClientIp.rate_limit_key/2, which the three controllers below call, so take it with any of them)
  • lib/petal_pro_api/controllers/session_controller.ex (both the client key and the per-account limit)
  • lib/petal_pro_api/controllers/registration_controller.ex
  • lib/petal_pro_web/controllers/user_passkey_controller.ex (also stops counting the challenge request and answers a refusal with a redirect)
  • test/petal_pro_web/client_ip_test.exs
  • test/petal_pro_api/session_controller_test.exs
  • test/petal_pro_api/registration_controller_test.exs
  • test/petal_pro_web/controllers/user_passkey_controller_test.exs

Shared by the tests above: test/support/rate_limit_helpers.ex (new). Take it if you take any of the tests that use it.

Comments, docs and the version number: config/runtime.exs (the comment above the client IP settings), DEPLOYMENT.md, CHANGELOG.md and mix.exs (@version only). Nothing in runtime.exs changes behaviour.

2. Tell the app which address is the client’s

The API sign-in, API registration and passkey limits now count the address PetalProWeb.ClientIp resolves, the same one last_signed_in_ip records since 4.5.0. Until you set CLIENT_IP_HEADER or TRUSTED_PROXY_HOPS that is still the peer, so behind a proxy every visitor keeps sharing one budget. If you did step 5 of the 4.5.0 upgrade, you’re done here.

On Fly:

fly.toml
[env]
CLIENT_IP_HEADER = "fly-client-ip"

Behind Cloudflare use CLIENT_IP_HEADER=cf-connecting-ip. Behind one nginx or Caddy use TRUSTED_PROXY_HOPS=1. Only name a header your proxy overwrites on every request, and make sure the app’s port can’t be reached around the proxy, or a caller can pick their own address and dodge the limits.

3. If you customised these files

  • passwordless_auth_live.ex - if you’d rather keep your own LiveView, make these six changes to it:

    1. Swap the UserPin.validate_pin/3 call for UserPin.check_pin/3.
    2. Delete the UserPin.failed_attempt/1 call after it. check_pin/3 counts the attempt itself.
    3. Route your “Resend” handler through send_pin/2, so a resend hits the same limit as the first request.
    4. Add enable_resend?: false to the assigns send_pin/2 sets when it sends. The resend handler no longer does it.
    5. Lower-case the email in the limit key.
    6. Add when is_binary(email) to your submit_email handler, and a catch-all after it: def handle_event("submit_email", _params, socket), do: {:noreply, socket}. Without it an email that isn’t text crashes the LiveView, and the 4.5.1 passwordless_auth_live_test.exs has one failing test.

    If you only take user_pin.ex for now, your old calls keep working: validate_pin/3 now counts the attempt and failed_attempt/1 does nothing, so each pin keeps its three guesses. That’s a stopgap, not the fix: until the LiveView changes too, “Resend” still skips the request limit and each capitalisation still gets its own count. The deprecation warnings also fail mix compile --warnings-as-errors, which Pro’s CI runs. UserPin.increment_changeset/1 is gone.

  • A copied rate_limit plug - if you copied one of the stock plugs into your own controllers, swap its conn.remote_ip line for the new key:

- ip = conn.remote_ip |> :inet.ntoa() |> to_string()
-
- case PetalPro.RateLimiter.hit("my_action:#{ip}", to_timeout(minute: 1), 10) do
+ case PetalPro.RateLimiter.hit(PetalProWeb.ClientIp.rate_limit_key(conn, "my_action"), to_timeout(minute: 1), 10) do
  • session_controller.ex, user_totp_controller.ex, user_passkey_controller.ex, registration_controller.ex - if you edited these, merge the rate_limit plug and its helpers by hand. Both reset helpers call PetalPro.RateLimiter.set/3 with a count of zero. Bring the @dialyzer {:nowarn_function, ...} line above each one too: Hammer’s spec says the count is positive, so dialyzer flags a zero. Then add the reset calls: clear_account_limit(email) on a successful API sign-in in SessionController.create/2, and clear_rate_limit(current_user) in both the :valid_totp and :valid_backup_code branches of UserTOTPController.create/2. Skip them and nothing errors, legitimate users just get refused. In the passkey controller the plug guard is now when action in [:create], without :challenge. registration_controller.ex only needs the key swap shown above.

4. What your users will notice

  • Two-factor: five codes per five minutes per user, backup codes included. Every submit counts and a correct code resets the count. The sixth try in the window gets a 429 and the code form with “Too many attempts. Please try again later.”
  • API sign-in: on top of 5 a minute per address, ten tries per ten minutes per email, whatever address they come from. A successful sign-in resets that count. A refused request gets a 429 with {"errors": {"detail": "Too many requests"}}, same as before. 4.5.2 closes a way round this: on some databases the same account could be reached under another spelling of its email, each with a count of its own. On 4.5.2 the count is kept on the account.
  • Passkey sign-in: loading the sign-in page no longer uses up the budget. Past 10 attempts a minute, the user lands back on the sign-in page with “Too many attempts. Please try again later.” where they used to get a 500.
  • Passwordless: “Resend” counts toward the three pin requests per ten minutes, so after the first pin and two resends a user waits for the window to end. Each pin still allows three guesses, so that’s nine guesses per account per ten-minute window. The same email in different capitals now shares one count. 4.5.2 closes a way round this: on some databases the same account could be reached under another spelling of its email, each with a count of its own. On 4.5.2 the count is kept on the account.

5. Check it worked

  1. Run the test files you took, for example mix test test/petal_pro/user_pin_test.exs test/petal_pro_web/controllers/user_totp_controller_test.exs
  2. In production, sign in and check last_signed_in_ip on your user is your own public address, not your proxy’s. That’s the address the API sign-in, API registration and passkey limits count
  3. Sign in with a 2FA user and enter six wrong codes. The first five are refused as wrong codes and the sixth should show “Too many attempts”. Don’t mix a correct code in, because it starts the count again. Wait five minutes before you try again. Run this and the next check locally or on one machine: with several, the count is per machine and the refusal can take more tries
  4. On a passwordless sign-in, ask for a pin, then enter a wrong pin and hit “Resend” (it only shows after a wrong pin). Do that twice more. The third resend should show “Too many attempts”

The limits live in memory on each machine, so with two machines a caller gets twice the number.

6. On an older 4.x version

The pin and two-factor fixes don’t need 4.5.0. They are in three files whose code hasn’t changed since 4.0.0:

  • lib/petal_pro/accounts/user_pin.ex
  • lib/petal_pro_web/live/auth/passwordless_auth_live.ex
  • lib/petal_pro_web/controllers/user_totp_controller.ex

Take those from 4.5.1 together with test/petal_pro/user_pin_test.exs, because every older copy of that test fails against the new user_pin.ex. They need no other file, setting or migration. We ran this on 4.0.0, 4.1.0, 4.2.0, 4.3.0 and 4.4.0, and the whole test suite passes on each.

  • The other two tests are optional, with one catch. test/petal_pro_web/live/passwordless_auth_live_test.exs and test/petal_pro_web/controllers/user_totp_controller_test.exs both need test/support/rate_limit_helpers.ex. The passwordless test also looks for [role=alert], and before 4.5.0 the petal_components alert renders role="dialog". Change every [role=alert] in your copy to [role=dialog] (there are five), or four of its tests fail even though the fix works.
  • The API and passkey fixes need 4.5.0 first. They build on PetalProWeb.ClientIp, which arrived in 4.5.0, so upgrade to 4.5.0 before you take those controllers. Before 4.5.0, CLIENT_IP_HEADER and TRUSTED_PROXY_HOPS do nothing.

4.4.0 -> 4.5.0

Petal Pro 4.5.0 is mostly a UI release. The settings, billing, two-factor and account deletion screens are rebuilt on petal_components, flash messages become toasts, empty states and status pills each use one shared component, and Tom Select is gone. petal_components moves from 4.6.0 to 4.18.0. Two changes are on the server side: sign-ins record the real client IP behind a proxy you trust, and production forces https with Secure cookies.

If you take 4.5.0 the normal way and never customised the files named below, the work is: update petal_components, add one line to fly.toml if you deploy on Fly, fix any HTTP health check you added yourself, and click through the screens at the end. The steps are in the order to do them.

⚠️ Warning: if you deploy on Fly, add CLIENT_IP_HEADER = "fly-client-ip" to the [env] block of fly.toml. Without it, every sign-in records Fly's proxy address. If you added an HTTP health check, give it an X-Forwarded-Proto: https header or exclude its path, or it gets a 301. Default TCP checks are unaffected. Both are covered in step 5.

1. Take Pro 4.5.0, then update petal_components

Pro 4.5.0 requires petal_components ~> 4.18. Merge the release into your project first, then run:

mix deps.update petal_components

Expect petal_components 4.18.0 or later. Check with mix deps | grep petal_components.

Do it in that order. petal_components now ships free versions of several names Pro used to define itself (combo_box from 4.12, data_table from 4.13, and the four components in step 3), so 4.4.0 code on the new library fails with a “call is ambiguous” error. Pro 4.5.0 deletes its own copies where the free one replaces it, and keeps its own Flop-driven data_table by importing the free module with except:. If you edited PetalProComponents, make sure its imports match 4.5.0:

lib/petal_pro_web/components/pro_components.ex
import PetalComponents.ColorSchemeSwitch
import PetalComponents.ComboBox
import PetalComponents.DataTable, except: [data_table: 1]
import PetalComponents.LanguageSelect
import PetalComponents.LocalTime
import PetalComponents.SocialButton
import PetalProWeb.AuthLayout
import PetalProWeb.ContentEditor
import PetalProWeb.DataTable, only: [data_table: 1]
import PetalProWeb.Flash
import PetalProWeb.Markdown
import PetalProWeb.Navbar
import PetalProWeb.PageComponents
import PetalProWeb.RouteTree
import PetalProWeb.SidebarLayout
import PetalProWeb.StackedLayout
import PetalProWeb.StatusBadge

Compared with 4.4.0 that drops PetalProWeb.ColorSchemeSwitch, PetalProWeb.ComboBox, PetalProWeb.LanguageSelect, PetalProWeb.LocalTime and PetalProWeb.SocialButton, and adds the six PetalComponents.* lines and PetalProWeb.StatusBadge.

The release also moves Flop from 0.26.3 to 0.27.0. mix.exs still says {:flop, "~> 0.20"}, so the bump comes from the release’s mix.lock. If you keep your own lock, run mix deps.update flop. Two things change in 0.27:

  • Every join field and custom field needs :ecto_type. Any Flop.Schema derivation of yours with join_fields or custom_fields fails until you add an ecto_type: to each of them. Pro’s two data table settings modules are already fixed.
  • Filters per request are capped at 20 by default (max_filters). Raise it if one of your screens sends more.

2. Layouts.empty is now Layouts.blank

The library now ships <.empty>, so Pro’s Layouts.empty/1 is renamed to Layouts.blank/1. Any call of yours to Layouts.empty breaks. Point it at blank instead:

-{PetalProWeb.Layouts, :empty}
+{PetalProWeb.Layouts, :blank}

The template file moves from lib/petal_pro_web/components/layouts/empty.html.heex to blank.html.heex in the same folder. If you customised it, carry your changes over.

3. Four Pro components are now the free ones

color_scheme_switch, language_select, local_time and social_button graduated to petal_components, so Pro deletes its copies. PetalProComponents imports the free modules, so use PetalProComponents still provides every name. Pro’s own call sites are updated in the release. You only need to change calls in your own code. A fully qualified call to an old module, such as PetalProWeb.ColorSchemeSwitch.color_scheme_switch or PetalProWeb.LanguageSelect.language_select, breaks because the module is gone. Use the plain <.color_scheme_switch> / <.language_select> tag instead.

If you customised the old Pro copies, keep your fork of those files and skip this step.

color_scheme_switch

Old (Pro) New (free) Notes
<.color_scheme_switch /> <.color_scheme_switch id="theme-switch" /> id is now required
<PetalProWeb.ColorSchemeSwitch.color_scheme_switch_js /> <.color_scheme_script /> goes in the same place in the head
lib/petal_pro_web/components/layouts/head.html.heex
- <PetalProWeb.ColorSchemeSwitch.color_scheme_switch_js />
+ <.color_scheme_script />

Saved preferences survive because the localStorage.scheme key is the same. The free switch also tracks the system preference live and stays in sync across tabs.

local_time

Old (Pro) New (free) Notes
no id id="joined-at" id is now required (the old one generated a UUID)
for= at= at is required
preset="DATETIME_MED" (the old default) format="datetime" (the new default)
other preset= values format="date", "time" or a map of Intl.DateTimeFormat options luxon preset names are not accepted
format="relative" format="relative" unchanged
format="yyyy mm dd" (luxon tokens) a map of Intl.DateTimeFormat options e.g. format={%{dateStyle: "full"}}
locale defaulted to "en" locale defaults to the browser’s own pass locale="en" to keep the old output

social_button

Old (Pro) New (free) Notes
logo= provider=
link_type="a" to= href= link_type="live_redirect" becomes navigate=, "live_patch" becomes patch=
logo="twitter" provider="x" the bird is now the X logo
variant defaulted to "solid" variant defaults to "outline" pass variant="solid" on any call that relied on the old default

language_select is a straight swap. It takes the same current_locale, language_options and current_path attrs.

Then delete the old component files, the two old JS hooks and the hooks’ entries in assets/js/hooks/index.js (ColorSchemeHook and LocalTimeHook):

lib/petal_pro_web/components/pro_components/color_scheme_switch.ex
lib/petal_pro_web/components/pro_components/language_select.ex
lib/petal_pro_web/components/pro_components/local_time.ex
lib/petal_pro_web/components/pro_components/social_button.ex
assets/js/hooks/color-scheme-hook.js
assets/js/hooks/local-time-hook.js

That leaves luxon orphaned in package.json. Unless your own code uses it, you can drop it:

npm uninstall luxon --prefix assets

4. Tom Select is gone

Pro’s Tom Select wrapper (PetalProWeb.ComboBox, the ComboBoxHook, assets/css/combo-box.css and the tom-select npm package) is deleted. The two admin membership pickers and the petal.gen.live / petal.gen.html generators now render <.field type="combobox"> from petal_components. It carries its value in a hidden native <select>, so a selection now survives a LiveSocket reconnect through LiveView’s own form recovery.

If your own code uses the old combo box:

Old (Tom Select) New (free) Notes
<.combo_box label="Members" help_text="Pick one or more" /> <.field type="combobox" label="Members" help_text="Pick one or more" /> label, errors and help text come from <.field>. A bare <.combo_box> is just the control
tom_select_plugins (its remove_button plugin) clearable the old remove button was on unless you passed remove_button: false. The new clear button is off unless you pass clearable (single select only)
remove_button_title remove_label the aria-label prefix on each chip’s remove button in a multiple combo box
tom_select_options (removed) no equivalent
tom_select_options_global_variable (removed) no equivalent

multiple, create, max_items, placeholder, disabled, required, remote_options_event_name and remote_options_target keep their names.

One behaviour change: a disabled single-select combo box posts nothing for its field, because there is no hidden "" input any more. (A multiple one rendered through <.field> still sends an empty name[].)

Then delete the remnants:

  1. Delete these files:
assets/js/hooks/combo-box-hook.js
assets/css/combo-box.css
lib/petal_pro_web/components/pro_components/combo_box.ex
  1. Remove the ComboBoxHook line from assets/js/hooks/index.js, and the @import of combo-box.css from assets/css/app.css.

  2. In PetalProComponents, replace the Pro combo box import with the free one (the full 4.5.0 import list is in step 1):

lib/petal_pro_web/components/pro_components.ex
- import PetalProWeb.ComboBox
+ import PetalComponents.ComboBox
  1. Remove the npm package:
npm uninstall tom-select --prefix assets

test/petal_pro_web/components/tom_select_retired_test.exs ships with the release and fails if any remnant is left. If you forked the old wrapper, keep your fork and skip this step.

5. New env vars for production

CLIENT_IP_HEADER and TRUSTED_PROXY_HOPS. UserAuth.get_ip/1 no longer takes the first x-forwarded-for entry, because the client writes that. A new PetalProWeb.ClientIp returns the connection’s peer unless you name a proxy to trust. config/runtime.exs reads both variables into config :petal_pro, :client_ip, in every environment. Set one of these:

Variable Example Description
CLIENT_IP_HEADER fly-client-ip A header your proxy overwrites on every request. Fly: fly-client-ip. Cloudflare: cf-connecting-ip. Unset by default.
TRUSTED_PROXY_HOPS 1 How many trailing x-forwarded-for entries your proxies append. 1 behind a single nginx or Caddy, 2 on Fly. Defaults to 0 (ignore the header). Must be a whole number, or the release fails to boot.

If both are set, CLIENT_IP_HEADER is tried first.

On Fly, add this to your fly.toml, or every sign-in records Fly’s proxy address:

fly.toml
[env]
CLIENT_IP_HEADER = "fly-client-ip"

The address it picks is parsed strictly, and a missing header or malformed entry falls back to the peer. Two related changes: get_ip/1 now returns nil for a peer that isn’t an IP address, where it used to raise, and a new PetalProWeb.SentryContextPlug in the endpoint adds request context to Sentry events with the same IP, with sign-in secrets (TOTP codes, PINs, sign-in tokens, passkey assertions, OAuth code and state, confirm and reset tokens) masked. It does nothing until SENTRY_DSN is set.

FORCE_SSL. Production now forces https. The new PetalProWeb.ForceSSLPlug runs first in the endpoint and wraps Plug.SSL. In prod, config/runtime.exs gives it rewrite_on: [:x_forwarded_proto, {:scheme, "fly-forwarded-proto"}] and hsts: true, so a request that reached your proxy over https counts as https. Anything else is redirected to https (301 for GET and HEAD, 307 for other methods), and https responses get a one-year HSTS header.

The HSTS header doesn’t set any cookie flags. Cookies get Secure because Plug adds it to every cookie written during an https request, and the plug’s rewrite_on is what makes a proxied request https. That covers the session and remember-me cookies. There is no secure: true in the cookie config, so plain-http dev and test keep working. Separately, the session cookie options in endpoint.ex now set same_site: "Lax" and http_only: true.

FORCE_SSL is on when it is unset, true or 1. Any other value, such as false, turns it off.

  • Leave it on behind Fly, Render, Railway and similar hosts.
  • Leave it on if you terminate TLS in the app.
  • Behind a proxy that sends no forwarded-proto header, every request redirects to itself unless you set FORCE_SSL=false. Turning it off also drops HSTS and the Secure flag.

HTTP health checks. An HTTP health check (for example one you added in fly.toml) gets a 301 unless it carries an X-Forwarded-Proto: https header or its path is excluded. Default TCP checks are unaffected. Petal Pro ships no health route, so /healthz in the snippets below stands in for whatever path your own check hits. Either give the check the header:

fly.toml
[[http_service.checks]]
path = "/healthz"
[http_service.checks.headers]
X-Forwarded-Proto = "https"

or exclude the path in the config :petal_pro, :force_ssl block of config/runtime.exs:

config/runtime.exs
config :petal_pro, :force_ssl,
rewrite_on: [:x_forwarded_proto, {:scheme, "fly-forwarded-proto"}],
hsts: true,
exclude: [hosts: ["localhost", "127.0.0.1"], paths: ["/healthz"]]

Keep the hosts entry. Passing any exclude replaces Plug.SSL‘s default [hosts: ["localhost", "127.0.0.1"]], so without it a prod release run locally redirects too. The options are validated once at boot (PetalProWeb.ForceSSLPlug.boot/0, called from PetalPro.Application), so a bad value stops the release from starting. The HTTPS section of DEPLOYMENT.md has the full details, and the Deploy to Fly.io guide has the Fly side.

6. Changed ids, labels and markup

Mostly relevant to custom JS, CSS and your own tests.

Colour-scheme switch ids. In 4.4.0 every colour-scheme switch got a random UUID id on each render, so nothing could target one by id. In 4.5.0 each stock switch has a fixed id: sidebar-user-profile-color-scheme in the sidebar user dropdown, navbar-color-scheme and navbar-color-scheme-mobile in the stacked layout’s top bar, and public-navbar-color-scheme on the public pages. The sidebar one is built from the new id attr on sidebar_user_profile (default sidebar-user-profile, which is also the root id, with -menu and -trigger ids inside), so passing a different id changes it. If your JS, CSS or tests found the switch by its color-scheme class or its icon classes, those are gone with the old component.

Sidebar menu ids now come from the item’s :name (falling back to a slug of the label), so two items with the same label no longer produce duplicate ids. This applies to menu_item_<name>_anchor, dropdown_<name> and dropdown_<name>_button. Stock ids change wherever a name differs from its label: menu_item_organizations_anchor is now menu_item_orgs_anchor, and in the admin sidebar menu_item_users_anchor is now menu_item_admin_users_anchor and menu_item_live_dashboard_anchor is now menu_item_server_anchor. Update anything that targeted the old label-based ids.

Active menu items are decided by one shared matcher, PetalProWeb.SidebarMenu.menu_item_active?/2, in the sidebar, stacked and navbar layouts. An item is active when its :name is the current page or the current page is in its new related_pages list (stock :subscribe relates :subscribed and :billing). There is no prefix matching, so add related_pages for nested pages that should light an item. The active sidebar link now carries aria-current="page".

Settings nav labels become nouns:

Old New
Edit profile Profile
Change email Email
Edit password Password
Edit notifications Notifications
Edit (org) General

Every settings screen also gets its own settings_header and page_title. Tests that assert the old labels or headings need updating. All strings go through gettext, so if you ship translations, add the new msgids.

Confirmations move from data-confirm to destructive alert_dialogs: cancelling a subscription, disabling 2FA and regenerating backup codes. Tests that relied on data-confirm selectors need updating. Billing event names, routes and params are unchanged (cancel_subscription still drives it).

Two-factor setup. The code field is now input_otp. It still posts user_totp[code]. The wrapper takes id and the real input is id <> "-input", so in stock Pro that is totp-code-input. The enabled heading changes case, from “2FA Enabled” to “2FA enabled”, and gains a one-line description underneath.

Account deletion. The inline two-stage confirm on Your Data becomes a destructive alert_dialog. Its show_delete_confirm and cancel_delete events are removed, so code or tests that send them break. The GDPR flow and confirm_delete are unchanged.

Notification preferences render as switches (<.field type="switch">) in place of checkboxes, with the same toggle_preference event and payload. Tests that select checkbox inputs may need updating.

Empty states use <.empty> everywhere. DataTable keeps empty_icon, empty_title and empty_description. The titles keep their wording, so tests that match the copy still pass. Tests that select the old empty-state markup (a bare <p>, a dashed box, an icon circle) need updating to the .pc-empty structure.

Status pills become <.status_badge status={@status}> and roles <.role_badge role={@role}>, both from the new PetalProWeb.StatusBadge, which use PetalProComponents imports. ChangelogHelpers.status_badge_class/1 is removed, as are the private role_label / role_badge_color helpers in OrgsLive and AdminOrgLive.Show. Some colours change: trialing on the admin subscriptions table goes from warning to info, the admin role on the admin users table from warning to info, and on the admin dashboard’s recently-joined list unconfirmed becomes a warning chip and not-onboarded a gray chip (both were a red X). To restore the old colours, edit status_color/1 or role_color/1 in PetalProWeb.StatusBadge.

Flash messages are toasts. PetalProWeb.Flash.flash_group/1 renders petal_components’ <.toast_group>, so every put_flash(:info | :success | :warning | :error) shows as a toast with no call-site changes. Only those four kinds reach the toast, so app-private flash keys stay out. The toast stack defaults to bottom-right, where the disconnected banner also sits, so the two can overlap. Pass position="bottom-left" to flash_group if that bothers you.

Billing. Tests that relied on the old spinner markup need updating. The meter summary guards now raise a clear ArgumentError for an inverted time range, where they used to raise an opaque FunctionClauseError.

Fixed: the month-boundary billing crash. If your billing screen crashed with FunctionClauseError for a metered subscription in the first days of a month, that is fixed (#348). The guards compared DateTime structs structurally, so a valid Aug 31 to Sep 1 window failed. They now use DateTime.compare.

7. If you customised these files, merge by hand

  • page_components.ex - the settings screens use a new two-pane layout. If you customised sidebar_tabs_container/1 or sidebar_menu_item/1, merge them by hand. They rely on new pieces: assets/js/hooks/scroll-strip-hook.js (registered as ScrollStripHook in hooks/index.js) and two @utility blocks in app.css, scrollbar-none and scroll-strip-fade. The same file gains settings_header/1, which every settings screen now calls. page_header/1 and box/1 are unchanged.
  • assets/css/colors.css - the semantic alias block at the top of the file (primary, danger, success and the rest) switches from @theme inline to @theme. Without it a utility like text-danger-400 can silently fall back to an inherited gray. If you edited this file, make the same one-line change on the alias block:
assets/css/colors.css
-@theme inline {
+@theme {
  • The onboarding modal and both email-link unsubscribe pages (user_onboarding_live.ex, unsubscribe_from_notification_subscription.html.heex and marketing_unsubscribed_confirmation.html.heex) replace their hand-rolled modal markup with <.modal hide_header>. If you customised these templates, re-port them onto <.modal hide_header>.
  • PetalProComponents - match the import list in step 1.

8. Check these screens

Click through these after upgrading, in light and dark mode, and on a phone for the settings screens:

  1. Sign-in page: the Google and GitHub buttons
  2. A public page (e.g. the landing page): the colour-scheme switch
  3. Every settings screen: Profile, Email, Password, Notifications, Passkeys, two-factor (set up, disable, regenerate backup codes), Your Data, and org General. On a phone the nav becomes a horizontal strip
  4. Billing: an active plan, the cancel dialog, the empty state, and a metered subscription in the first days of the month
  5. The sidebar user menu: the colour-scheme switch, and the profile row at the bottom on iOS
  6. Admin user and org show pages: the membership picker (combobox), memberships and the new Status row
  7. Admin indexes filtered down to nothing (empty state with “Clear filters”), the notifications page and bell, and the admin dashboard
  8. Any put_flash in your app now shows as a toast
  9. Anywhere you render local_time
  10. Both unsubscribe pages and the onboarding modal: the content is clickable
  11. In production: sign in, then check the last_signed_in_ip column on your user row (or a new impersonation audit entry) holds a real address and not your proxy’s. On Fly, a deploy without CLIENT_IP_HEADER records Fly’s proxy address there, which is the sign it is missing. Also check your health check still passes

4.3.0 -> 4.4.0

Petal Pro 4.4.0 moves up to petal_components 4.6. The headline: two components you used to get from Petal Pro, aurora and border_beam, now live in the free petal_components library. They got rebuilt on the way over (glow, multiple beams, spring easing), so Pro drops its own copies and consumes the free ones like every other component. floating_div is gone too, replaced by the free popover.

If you take 4.4.0 the normal way, most of this is handled for you. The one thing that will bite is bumping petal_components on an older Pro.

Take Pro 4.4.0 before you run mix deps.update petal_components

Pro 4.4.0 requires petal_components ~> 4.6. If you update petal_components first, while still on an older Pro, the build dies with:

error: function border_beam/1 imported from both PetalProWeb.BorderBeam and PetalComponents.BorderBeam, call is ambiguous

Both libraries now export border_beam/1, both are in scope, so any unqualified call is ambiguous. aurora/1 is the same problem but quieter: Pro never calls <.aurora> itself, so the build stays green and it only breaks the first time you use <.aurora> in your own templates.

The fix is Pro 4.4.0, which deletes Pro’s copies and switches to the free ones. So the order is:

  1. Bump your Petal Pro version to 4.4.0 first
  2. Then mix deps.get pulls petal_components 4.6

If you never touched these two components, that is the whole job. If you customised them, you have a few attribute renames to do.

border_beam attribute renames

The free border_beam styles its own panel now (surface, border, radius), so on top of the renames you can drop the background, border and radius classes you used to pass alongside it.

Old (Pro) New (free 4.6) Notes
gradient_color_start color_from
gradient_color_end color_to
animation_duration duration
beam_size size
offset_distance initial_offset was a string like "0%", now an integer
border_color (removed) the beam draws its own border
border_radius border_radius still accepted, but leave it off and the beam follows your --pc-radius token

Pro’s only border_beam call site is the auth card in auth_layout.ex. Here is the before and after so you can see the class cleanup:

lib/petal_pro_web/components/pro_components/auth_layout.ex
-<.border_beam
- gradient_color_start="#3b82f6"
- gradient_color_end="#67e8f9"
- border_radius="0.75rem"
- animation_duration="10s"
- class="border-gray-200! shadow-gray-200/50 bg-white px-5 py-8 shadow-lg dark:border-gray-700/80! dark:bg-gray-800/80 dark:shadow-none dark:backdrop-blur-sm sm:rounded-xl sm:px-10"
->
+<.border_beam
+ color_from="#3b82f6"
+ color_to="#67e8f9"
+ duration="10s"
+ class="shadow-gray-200/50 px-5 py-8 shadow-lg dark:shadow-none sm:px-10"
+>
{render_slot(@inner_block)}
</.border_beam>

aurora attribute renames

Old (Pro) New (free 4.6) Notes
invert invert was a boolean, now a string: "auto", "none", or "always"
animation_duration speed
background_gradient (removed) pass a colors list instead
aurora_gradient (removed) pass a colors list instead
opacity opacity unchanged
blur blur unchanged
mask_position mask_position unchanged
mask_coverage mask_coverage unchanged

Careful: unknown attributes fail silently

petal_components components pass anything they don’t recognise straight through to the DOM as a plain HTML attribute. So an old call like <.border_beam gradient_color_start="#3b82f6"> will not error after you switch to the free component. It renders a gradient_color_start attribute on the div, the browser ignores it, and your beam still shows up looking wrong. No compile error, no crash, just a component that quietly stopped matching your design. Work through the rename tables so you don’t ship one.

floating_div is gone

floating_div had no call sites left in Pro, so 4.4.0 deletes it along with its @floating-ui/dom npm dependency. If you used <.floating_div> in your own code you get a compile error on upgrade. Swap it for the free <.popover> in top-layer mode, which covers the same case (a panel that needs to escape a clipped or overflow-hidden container):

<.popover top_layer placement="bottom-start">
<:trigger>Open</:trigger>
Your floating content
</.popover>

Catch this in your own app

The whole thing came from Pro shipping a component with the same name as one the free library exports. You can hit it the same way in your own code: define a component named the same as a petal_components one and every unqualified call becomes ambiguous. use PetalComponents names are a reserved namespace.

This test walks both sides at runtime and fails if any of your components shadow a use PetalComponents export. Drop it into your test suite. Two things to change for your app: swap :petal_pro for your OTP app name, and /petal_pro_web/components/ for wherever your components live (and adjust the @exempt list, or empty it).

defmodule MyAppWeb.PetalComponentsCollisionTest do
use ExUnit.Case, async: true
# Modules that render without `use PetalComponents` (e.g. email templates
# on bare Phoenix.Component). Leave empty if you have none.
@exempt [MyAppWeb.EmailComponents]
@ignored_exports [:module_info]
defp generated?(name) do
name = Atom.to_string(name)
String.starts_with?(name, "__") and String.ends_with?(name, "__")
end
test "no component shadows a name exported by `use PetalComponents`" do
free = free_export_names()
assert MapSet.size(free) > 50,
"only found #{MapSet.size(free)} free exports - the import-block parser is probably broken"
offenders =
for mod <- app_component_modules(),
mod not in @exempt,
{name, arity} <- mod.module_info(:exports),
name not in @ignored_exports,
not generated?(name),
MapSet.member?(free, name) do
"#{inspect(mod)}.#{name}/#{arity}"
end
assert offenders == [], """
Reserved-namespace collision. These components define names that
`use PetalComponents` also exports, so any unqualified call is ambiguous:
#{Enum.map_join(offenders, "\n", &" - #{&1}")}
If the free library now ships this component, delete your copy and move the
call sites to the free one. If it is genuinely yours, rename it.
"""
end
defp free_export_names do
for mod <- free_import_block(),
Code.ensure_loaded?(mod),
{name, _arity} <- mod.module_info(:exports),
name not in @ignored_exports,
not generated?(name),
into: MapSet.new(),
do: name
end
defp free_import_block do
source =
Mix.Project.deps_paths()
|> Map.fetch!(:petal_components)
|> Path.join("lib/petal_components.ex")
|> File.read!()
[_, block] = Regex.run(~r/import PetalComponents\.\{(.+?)\}/s, source)
block
|> String.split(",")
|> Enum.map(&String.trim/1)
|> Enum.reject(&(&1 == ""))
|> Enum.map(&Module.concat(PetalComponents, &1))
end
defp app_component_modules do
{:ok, mods} = :application.get_key(:petal_pro, :modules)
Enum.filter(mods, fn mod ->
Code.ensure_loaded?(mod) and
function_exported?(mod, :__components__, 0) and
mod |> source_path() |> String.contains?("/petal_pro_web/components/")
end)
end
defp source_path(mod) do
to_string(mod.module_info(:compile)[:source])
rescue
_ -> ""
end
end

If you can’t pull 4.4.0

If your membership has lapsed you can still fix this by hand, no repo access needed. You are deleting Pro’s two component copies, dropping their imports, and porting the one call site.

  1. Delete these two files:
lib/petal_pro_web/components/pro_components/aurora.ex
lib/petal_pro_web/components/pro_components/border_beam.ex
  1. Remove these imports:
lib/petal_pro_web/components/pro_components.ex
- import PetalProWeb.Aurora
- import PetalProWeb.BorderBeam
lib/petal_pro_web/components/pro_components/auth_layout.ex
- import PetalProWeb.BorderBeam
  1. Port the border_beam call in auth_layout.ex per the rename table (before and after above).

  2. If you used <.aurora> anywhere, rename its attributes per the aurora table.

  3. Now mix deps.update petal_components is safe.

That is the complete fix. The free components are a superset of what Pro shipped, so you lose nothing by switching.


4.0.x -> 4.1.0

New migrations

Run mix ecto.migrate after updating. Two new table groups are added:

  • WebAuthn passkeys - user_passkeys table plus a passkey_2fa_preferred boolean column on the users table
  • Admin chat history - admin_chat_conversations and admin_chat_messages tables for persistent AI chat

Both sets of migrations are additive - they won’t touch your existing data.

WebAuthn passkeys (optional)

Passkeys let your users register Face ID, Touch ID, or hardware keys. There are two modes: passwordless primary auth, and 2FA on top of password login. If you don’t want passkeys yet, skip this section - the migrations are still safe to run, the feature just won’t be reachable.

To wire up passkeys in an existing project:

  1. Add the new config keys to config/config.exs:
config :petal_pro, :webauthn,
enabled: true,
rp_name: "Your App Name",
rp_id: "yourdomain.com",
origin: "https://yourdomain.com"
  1. Copy the new passkey LiveViews from the 4.1.0 source into your project:

    • lib/petal_pro_web/live/auth/passkey_registration_live.ex
    • lib/petal_pro_web/live/auth/passkey_login_live.ex
    • lib/petal_pro_web/live/user_settings/passkey_settings_live.ex
  2. Add the new passkey routes to your router (copy from the 4.1.0 router.ex).

  3. The security settings page gains a “Passkeys” section automatically once the routes are in place.

Persistent admin chat history (optional)

Admin chat conversations are now stored in the DB and survive reloads and restarts. The sidebar lists recent conversations. This is purely additive - just run the migrations and you’re done, no config needed.

mix quality now runs credo –strict and dialyzer

This is the one change that may require some work on existing projects. Fresh clones of 4.1.0 pass both out of the box, but an existing project that’s been customised will likely have some credo violations to clean up.

Steps:

  1. Run mix credo --strict and fix any violations it finds
  2. Get dialyzer running: mix dialyzer (first run builds the PLT, takes a few minutes)
  3. Fix any dialyzer warnings that come up

Both tools are optional to run locally, but CI will run them via mix quality from 4.1.0 onwards. If you don’t want strict credo or dialyzer in your CI, update your mix quality alias in mix.exs to match your preferences.

Upgrade steps

  1. Update your Petal Pro version in mix.exs
  2. Run mix deps.get
  3. Run mix ecto.migrate (picks up the passkeys and admin chat tables)
  4. Run mix credo --strict and fix violations
  5. Run mix dialyzer and address any warnings
  6. If you want passkeys: add the config, copy the LiveViews, add the routes (see above)

3.0 -> 4.0

Breaking changes

Jido AI replaces LangChain for admin chat

The admin chat system has been rewritten around Jido. If you added custom LangChain tools, you’ll need to migrate them to the Jido tool behaviour pattern.

Each tool is a module that implements the PetalPro.Ai.Tool behaviour:

defmodule MyApp.Ai.Tools.MyTool do
@behaviour PetalPro.Ai.Tool
@impl true
def name, do: "my_tool"
@impl true
def description, do: "Does something useful"
@impl true
def parameters do
%{
type: "object",
properties: %{
user_id: %{type: "string", description: "The user's ID"}
},
required: ["user_id"]
}
end
@impl true
def execute(%{"user_id" => user_id}, _context) do
# your logic here
{:ok, "result"}
end
end

Register tools in your PetalPro.Ai.Tools registry module. Remove any LangChain dependencies from mix.exs.

Req replaces HTTPoison and Tesla

All HTTP calls now use Req. Replace any remaining HTTPoison or Tesla calls:

# mix.exs
- {:httpoison, "~> 2.0"},
- {:tesla, "~> 1.8"},
+ {:req, "~> 0.5"},
# Before (HTTPoison)
HTTPoison.get!("https://example.com/api")
# After (Req)
Req.get!("https://example.com/api")

ChangelogUpdates context renamed to Changelog

The changelog context and its schema modules have been renamed:

- PetalPro.ChangelogUpdates
+ PetalPro.Changelog
- PetalPro.ChangelogUpdates.ChangelogUpdate -> PetalPro.Changelog.Update
- PetalPro.ChangelogUpdates.ChangelogLike -> PetalPro.Changelog.Like
- PetalPro.ChangelogUpdates.ChangelogRead -> PetalPro.Changelog.Read

Update any references in your own code. A new migration handles the underlying table renames.

Styler upgraded from 0.11 to 1.11

Styler 1.x applies additional formatting rules. After updating deps, run mix format — expect a large diff of auto-reformatted code. This is cosmetic only.

Sidebar-only layout

The desktop header layout has been removed. All authenticated pages now use the sidebar layout exclusively. If you have pages using a header-based layout, migrate them to type="sidebar".

Email provider simplified to Resend

The email adapter is now Resend only. Set RESEND_API_KEY in your environment. Remove any SES or other adapter configuration.

New environment variables

Variable Required Purpose
RESEND_API_KEY Yes Transactional email via Resend
SENTRY_DSN No Auto-activates Sentry error monitoring when set
MCP_ADMIN_TOKEN Recommended Bearer token for the admin MCP server at POST /api/mcp

New migrations

Run mix ecto.migrate after updating. The new migrations cover:

  • GDPR tables — data_export_requests and data_deletion_logs for the Your Data feature
  • Notification preferences — notification_preferences table for per-type in-app/email toggles
  • AI cost tracking — ai_call_logs table for token counts, costs, and timing
  • Changelog schema rename — renames underlying tables from changelog_updates/changelog_likes/changelog_reads to updates/likes/reads within the changelog context

Recommended upgrade steps

  1. Update mix.exs — bump Petal Pro version, swap LangChain/HTTPoison/Tesla for Jido/Req, update Styler to ~> 1.11
  2. Run mix deps.get
  3. Run mix ecto.migrate
  4. Run mix format — Styler 1.11 will reformat a lot of code; review the diff but don’t worry about it
  5. Update RESEND_API_KEY in your secrets/.envrc; remove old email adapter config
  6. If you added custom LangChain tools: migrate them to the Jido tool behaviour pattern (see above)
  7. If you used HTTPoison or Tesla directly: replace calls with Req
  8. If you reference PetalPro.ChangelogUpdates: update to PetalPro.Changelog and new schema names
  9. Optionally set SENTRY_DSN and MCP_ADMIN_TOKEN in production

2.2 -> 3.0

Petal Pro has been upgraded to Tailwind 4. Some utilities have been removed or renamed. See the Tailwind upgrade guide for more information.

To upgrade to Tailwind 4 in your project, make sure you update mix.exs:

- {:tailwind, "~> 0.2", runtime: Mix.env() == :dev}
+ {:tailwind, "~> 0.3", runtime: Mix.env() == :dev}

And config.exs (note that the paths have changed and that you need 4.0.9 or above):

config :tailwind,
- version: "3.3.3",
+ version: "4.1.11",
default: [
args: ~w(
- --config=tailwind.config.js
- --input=css/app.css
- --output=../priv/static/assets/app.css
+ --input=assets/css/app.css
+ --output=priv/static/assets/app.css
),
- cd: Path.expand("../assets", __DIR__)
+ cd: Path.expand("..", __DIR__)
]

Don’t forget to run:

mix tailwind.install

Updated app.css

app.css has been updated to support CSS first configuration:

app.css
@import "tailwindcss";
@source "../../deps/petal_components/**/*.*ex";
@import "../../deps/petal_components/assets/default.css";
@import "./colors.css";
@import "./combo-box.css";
@import "./editorjs.css";
@import "./animations.css";
@import "../node_modules/tippy.js/dist/tippy.css" layer(components);
@plugin "@tailwindcss/typography";
@plugin "@tailwindcss/forms";
@plugin "@tailwindcss/aspect-ratio";
@plugin "./tailwind_heroicons.js";
...

To see the latest changes for 3.0.0, go to:

https://github.com/petalframework/petal_pro/tree/v3.0.0/assets/cssgithub.com

The following files have changed:

  • app.css
  • combo-box.css
  • editorjs.css

The following files have been added:

  • colors.css
  • animations.css
  • tailwind_heroicons.js

Finally, tailwind.config.js has been removed.

Now you should be able to follow the Tailwind upgrade guide to update the rest of your project. Running mix format should automatically arrange tailwind classes in your project.

2.0 -> 2.2

With Petal Components 2.0.6, the heroicons dependency has been replaced with a CSS-based approach. This is based on what has been implemented in the Phoenix repo - the reasoning is explained in this issue. To upgrade an existing Petal Pro project, add the dependency in mix.exs:

mix.exs
def deps do
[
+ {:heroicons,
+ github: "tailwindlabs/heroicons",
+ tag: "v2.1.5",
+ app: false,
+ compile: false,
+ sparse: "optimized"},
]
end

This will download a copy of the source SVG files directly from GitHub (into deps/heroicons/optimized). Then the following code will process these files to create custom CSS classes:

assets/tailwind.config.js
const colors = require("tailwindcss/colors");
const plugin = require("tailwindcss/plugin");
+ const fs = require("fs");
+ const path = require("path");
module.exports = {
plugins: [
+ // Embeds Heroicons (https://heroicons.com) into your app.css bundle
+ // See your `CoreComponents.icon/1` for more information.
+ //
+ plugin(function({matchComponents, theme}) {
+ let iconsDir = path.join(__dirname, "../deps/heroicons/optimized")
+ let values = {}
+ let icons = [
+ ["", "/24/outline"],
+ ["-solid", "/24/solid"],
+ ["-mini", "/20/solid"],
+ ["-micro", "/16/solid"]
+ ]
+ icons.forEach(([suffix, dir]) => {
+ fs.readdirSync(path.join(iconsDir, dir)).forEach(file => {
+ let name = path.basename(file, ".svg") + suffix
+ values[name] = {name, fullPath: path.join(iconsDir, dir, file)}
+ })
+ })
+ matchComponents({
+ "hero": ({name, fullPath}) => {
+ let content = fs.readFileSync(fullPath).toString().replace(/\r?\n|\r/g, "")
+ let size = theme("spacing.6")
+ if (name.endsWith("-mini")) {
+ size = theme("spacing.5")
+ } else if (name.endsWith("-micro")) {
+ size = theme("spacing.4")
+ }
+ return {
+ [`--hero-${name}`]: `url('data:image/svg+xml;utf8,${content}')`,
+ "-webkit-mask": `var(--hero-${name})`,
+ "mask": `var(--hero-${name})`,
+ "mask-repeat": "no-repeat",
+ "background-color": "currentColor",
+ "vertical-align": "middle",
+ "display": "inline-block",
+ "width": size,
+ "height": size
+ }
+ }
+ }, {values})
+ })
],
};

1.8 -> 2.0

Starting with 2.0, the Petal Framework has returned to Petal Pro. There is a discussion with regards to this change in the PR. The Petal Framework package will be supported in the long run - so there is no need to upgrade immediately. However, over time new features will be added to Petal Pro, rather than the Petal Framework package. If you upgrade to 2.0, you will no longer need to provide your Petal Framework license key. The private Petal hex repo that key unlocked has since been shut down, so if your Dockerfile has a RUN --mount=type=secret,id=PETAL_LICENSE_KEY step that adds it, delete the whole step and drop the PETAL_LICENSE_KEY build secret with it. Nothing replaces it, because nothing is fetched from petal.build at build time any more:

  • Petal Pro itself is a zip you download from petal.build/users/downloads after purchase. The code lives in your own repo.
  • The components come from public Hex. Add {:petal_components, "~> 4.17"} to your deps in mix.exs, run mix deps.get, and put use PetalComponents in your web module.

In addition, the npm recipe has been merged. Petal Pro is still using esbuild, however, javascript libraries are now downloaded as an npm package (instead of depending on a CDN).

You may need to add nodejs and npm to your Dockerfile:

Dockerfile
# install build dependencies
+ RUN apt-get update -y && apt-get install -y build-essential git nodejs npm \
+ && apt-get clean && rm -f /var/lib/apt/lists/*_*

In the past mix assets.setup would install Tailwind CSS and esbuild. Tailwind is now installed with mix setup, esbuild is installed via npm with mix assets.deploy. You’ll need to remove:

Dockerfile
- RUN mix assets.setup

Finally, lib/petal_pro_web/petal_framework_translations.ex is no longer required. Instead, components like the DataTable can use Gettext directly.

1.6 -> 1.7

Starting in this release, we now use Styler to format our codebase. This means there will be a large amount of changes. To minimise merge or rebase c onflicts when upgrading, we recommend you swap out Recode with Styler first:

mix.exs
- {:recode, "~> 0.6", only: [:dev, :test]},
+ {:styler, "~> 0.11", only: [:dev, :test], runtime: false},

Then, replace the content of .credo.exs with the one in this repo.

Finally, run the formatter for Styler to take care of things:

Another change we recommend you make before upgrading, especially if you’ve made changes to your landing page, is to rename PetalProWeb.Components.LandingPage to PetalProWeb.LandingPageComponents, make sure you also rename the file from landing_page.ex to landing_page_components.ex.

Given the amount of changes in this release, we recommend you backup your branch, then use merge instead of rebase to bring your branch up to date.

1.5.2

This version pulled the petal_framework package from a private hex repo on petal.build. That repo has been shut down, so there’s nothing to add to your local hex any more. If you’re still on 1.5.2 to 1.8, upgrade straight to 2.0 or later, where that code lives inside Petal Pro (see 1.8 -> 2.0 above).

Updating Petal Components

Petal Components is a regular Hex dependency. Bump the version in mix.exs ({:petal_components, "~> 4.17"} at the time of writing) and run mix deps.update petal_components.

Updating the boilerplate code

Here is some discussion amongst members in a Github issue.

Firstly, I’d use {rename_project, "~ 0.1.0"} to rename your project back to PetalPro if you renamed it to something else.

Personally, I’d use option 3.

Option 1 - Copy your files into a fresh project

Manual and time-consuming, but surgical.

If you haven’t changed too many existing files and added mostly new ones, you could start a fresh project with the latest Petal Pro and migrate over the work you’ve done from the previous project. This is likely the easiest route. If you want to keep your git history, then you could try copying the .git folder from the previous project into the new one.

Option 2 - Using git branches

With this option, you maintain a “pure” Petal branch in your repository with no other modifications. Then, you merge this branch into your main app when you upgrade.

Follow the instructions here.

Option 3 - Rebasing

Keep a branch in sync with the PetalPro repo, and when it updates, you rebase (replay) your commits on top of it.

Option 4 - Attempt a git merge

Option 5 - rsync

  • rsync -r –delete –exclude=.git ~/code/petal_pro-1.3.0/ ~/code/your-app
  • git checkout HEAD path/to/files/rsync/deleted/but/shouldnt/have (I used –delete with rsync so I’d know about files that were removed, for example, I think some of the org stuff was moved, and I don’t want cruft)
  • git add -p
  • Use rename_phoenix_project.sh to rename back to your app name

Option 6 - Use a diffing tool like Araxis merge

Comment from a Pro user:

The easiest way for me is to create a fresh project from the updated petal_pro, rename it to the same name as your existing project, and then run a diff tool like Araxis merge against the root directories. As long as you have mostly added your own files and not modified the template files much it doesn’t take too long. You can either merge the template changes into your existing project (better for git history) or merge your customizations into the fresh project.