# Petal Pro Documentation # https://petal.build/petal-pro # This file contains all Petal Pro documentation concatenated for LLM consumption. # Individual pages available at /petal-pro/raw/{path} # Page index available at /petal-pro/docs.json # What is Petal Pro? # Source: https://petal.build/petal-pro # What is Petal Pro? [Petal Pro](https://petal.build) is a Phoenix boilerplate template with the goal of drastically reducing your time from a new project to a production-ready web application. We've worked on web applications for over a decade now. PHP, Ruby on Rails, Backbone JS, React, Meteor JS, Ember JS, and now Phoenix. Having built and deployed a number of Phoenix apps into the wild ([Kindly](https://www.kindlyapp.com.au/), [Travel Massive](https://www.travelmassive.com/) and [Talentbookr](https://talentbookr.com.au/)) we realised that the `mix phx.new` generator it produces a very lean web application and leaves a lot of decision-making to the developer. To the more experienced developer, this can be liberating, however, it's also great to have more of a turnkey solution with a sensible set of defaults that get you fully up and running. A solution that, out of the box provides: - a component library so you don't have to think too much about the design - working authentication and user management so users can register and change their settings right away - admin functionality allowing the basic management of users - a way of logging user activity so you can see how users use the application - some email templates that are ready to go and easily editable - a cheap and reliable email service provider chosen for you (but easily changeable) to send transactional emails - a CRUD generator that produces a clean and deployable interface - a way to deploy to production in less than 10 minutes Having not found the above solution, me and my business partner Nic decided to build it - the result is Petal Pro.

ℹ️ Information: Not an Elixir developer?: Phoenix web apps now compete with Javascript single-page applications thanks to its impressive web socket abilities via LiveView. We hope more Javascript developers will see the immense time-saving abilities of using Phoenix (along with Petal Pro). Imagine having a web application that feels like a SPA, but is all server-side code. You still can create reusable components and don't need to worry about an API. It really can cut your development time in half.

## What's included in v4 v4 is the biggest release yet. Here's a summary of what's new on top of the existing foundation: ### GDPR compliance A "Your Data" settings page (`/app/users/your-data`) lets users download all their personal data as a JSON file and submit account deletion requests. Deletions run as background jobs via Oban, with soft-delete and anonymization cascade across related records. ### AI admin chat (Jido-powered) The admin chat interface is now powered by [Jido](https://hex.pm/packages/jido) with a clean tool behaviour pattern. Built-in tools cover user management, org management, changelog operations, and AI cost stats. Adding your own tools is straightforward. Write a `Jido.Action` module under `PetalPro.AI.AdminChat.Actions` and add it to `@actions` in `PetalPro.AI.AdminChat.ActionRegistry`. The admin chat and the MCP server both pick it up. ### Admin MCP server Connect Claude Code or Claude Desktop directly to your running app. The MCP server at `POST /api/mcp` exposes admin tools via JSON-RPC 2.0 with bearer token auth. Set `MCP_ADMIN_TOKEN` and add the server to your `.mcp.json` — then your AI assistant can query users, manage orgs, publish changelog entries, and more without leaving your editor. ### Per-type notification preferences Users can now control in-app and email delivery independently for each notification type. Security-critical notifications (like password change alerts) are forced-on and cannot be disabled. Use `Notifications.notify/3` as the single entry point — it handles preference checks automatically before dispatching. ### Rate limiting and error tracking Auth endpoints are now protected by Hammer-based rate limiting out of the box. Sentry error monitoring auto-activates when you set the `SENTRY_DSN` environment variable — no code changes needed. ### Production Dockerfile A production-ready Dockerfile is included for containerized deployments. No more rolling your own from scratch. ### Claude Code recipe commands `.claude/commands/recipes/` ships with slash commands for common customizations: removing billing, switching auth methods, adding integrations, structural changes, and more. See the [recipes page](/petal-pro/recipes) for the full list. --- # Changelog # Source: https://petal.build/petal-pro/changelog # Changelog A history of changes to Petal Pro ### 4.5.2 - 2026-11-16 4.5.2 needs 4.5.1 underneath. On 4.5.0 or older, take 4.5.1 first, see the [upgrade guide](/petal-pro/upgrade-guide#4-5-1-4-5-2). #### Security - **Browser password sign-in is limited.** The sign-in form had no limit at all, so only the speed of the password check slowed a script working through passwords. An account now gets ten tries per ten minutes, counted before the password is checked, and a correct password counted on the account starts the count again. An email with no account is counted the same way, so a refusal doesn't show whether the account exists. A refused attempt goes back to the sign-in page with "Too many attempts. Please try again later." This has been the case since 4.0.0. See the [upgrade guide](/petal-pro/upgrade-guide#4-5-1-4-5-2). - A count on an account could be turned against its owner, because anyone who knows an email could keep the count full. So a browser that has signed in to an account is counted on its own first, through a new cookie, `_petal_pro_web_sign_in_device` (encrypted, HttpOnly, one year). A stranger who uses up an account's count can then only block browsers that have never signed in to it. The cookie grants nothing else and stops counting when the account's password changes. A sign-in from a trusted browser leaves the account's count as it is, so other browsers stay refused until the window ends. List it in your cookie policy. A password reset also starts the account's count again. See [Trusted Browsers](/petal-pro/fundamentals/deployment#trusted-browsers). - With `CLIENT_IP_HEADER` or `TRUSTED_PROXY_HOPS` set, one address also gets 100 failed tries per ten minutes across all accounts. Without either there is no limit per address, because every visitor would share it, and the app logs one warning when it sees proxy headers with neither set. - Upgrade: take `lib/petal_pro_web/controllers/user_session_controller.ex` and `lib/petal_pro_web/live/auth/user_reset_password_live.ex`. Each runs without the other. The reset only starts the API count again with the new API `session_controller.ex` below. A test suite that posts more than ten wrong passwords for one account inside ten minutes now sees the refusal. - **Limits that protect an account are counted on the account, not on the text typed.** The pin, API sign-in and password reset limits were keyed on the email as text. Postgres treats some spellings as the same email that `String.downcase/1` leaves different. Each such spelling found the same account and got a fresh count, so on common database setups the 4.5.1 pin limit could be multiplied. Every account limit is now keyed on the user id found by the same lookup the sign-in uses. The password reset limit was keyed on the raw text, so capitals alone got round it. See [Rate Limiting](/petal-pro/fundamentals/deployment#counted-on-the-account). - Upgrade: take `lib/petal_pro_web/live/auth/passwordless_auth_live.ex`, `lib/petal_pro_api/controllers/session_controller.ex` and `lib/petal_pro_web/live/auth/user_forgot_password_live.ex`. Each works on its own. If you keep your own copy of one, key its limit on `user.id` after looking the user up, not on the email. Step 3 of the [upgrade guide](/petal-pro/upgrade-guide#4-5-1-4-5-2) shows the change for each. - **An admin with a pending second factor could impersonate a user.** Signing in puts the user in the session before the two-factor step, and `POST /auth/impersonate` only checked for an admin. Impersonating and switching back gave a full admin session without the code ever being asked for, so an admin's password alone was enough. The controller now sends a pending sign-in to finish first. Impersonation is on by default. - Upgrade: take `lib/petal_pro_web/controllers/user_impersonation_controller.ex`. If you have routes of your own behind `:require_admin_user` without `:authenticated`, add `:authenticated` to them: they have the same hole. - **Confirmation emails can't be resent without limit.** The resend form and `POST /api/send-instructions` had no limit, so anyone could send confirmation emails to an unconfirmed account's address over and over. Both now share three per ten minutes for an account. The API answers a refusal with a 429. - Upgrade: take `lib/petal_pro_web/live/auth/user_confirmation_instructions_live.ex` and `lib/petal_pro_api/controllers/registration_controller.ex`. #### Changed - **Per-address limits count an IPv6 client by its /64.** One subscriber usually holds a whole /64, so counting each address gave them a fresh budget on every request. Clients that arrive as IPv4-mapped or NAT64 addresses are counted as the IPv4 address they carry. `ClientIp.get/2` is unchanged, so `last_signed_in_ip` and the audit log still record the full address. Take `lib/petal_pro_web/client_ip.ex`. - **The passkey sign-in limit only applies when the client address is configured.** Behind a proxy with neither setting made it was one count for the whole app, which a single caller could hold shut for everyone. A passkey can't be guessed, so nothing is lost. Take `lib/petal_pro_web/controllers/user_passkey_controller.ex`, and `test/petal_pro_web/controllers/user_passkey_controller_test.exs` with it: the 4.5.1 "eleventh attempt" test fails against the new controller. - **A malformed sign-in form post is an ordinary failure.** A body with no email or password, or with a list where text should be, used to be a 500. ### 4.5.1 - 2026-11-14 #### Security - **A passwordless sign-in pin could be guessed without limit.** Asking for a pin was limited to three per ten minutes, but "Resend" was not: it issued a new pin with a fresh set of attempts every time it was called, so a script could alternate three guesses and a resend indefinitely. The same email in different capitals also got a limit each. Resend now goes through the same limit as the first request, and the limit is per account whatever the capitals. Guesses sent in parallel could also all pass the attempts check before any of them was counted; each guess now takes its attempt in one database statement before the pin is compared. With the fix an account gets nine guesses per ten-minute window on each machine, and up to twice that for a caller who straddles the end of a window. This has been the case since passwordless sign-in shipped. 4.5.2 closes a way round that limit: on some databases the same account could be reached under another spelling of its email, each with a count of its own, and on 4.5.2 the count is kept on the account. See the [upgrade guide](/petal-pro/upgrade-guide). - Upgrade: take `lib/petal_pro/accounts/user_pin.ex` and `lib/petal_pro_web/live/auth/passwordless_auth_live.ex` together. `UserPin.check_pin/3` replaces `validate_pin/3` followed by `failed_attempt/1`. Both old functions still work and are deprecated: `validate_pin/3` now counts the attempt itself and `failed_attempt/1` does nothing, so a LiveView you customised keeps its three guesses per pin and gets two deprecation warnings until you switch, which fail `mix compile --warnings-as-errors`. That is a stopgap, not the fix: the unlimited resend is in the LiveView. If you keep your own, make the six changes in step 3 of the [upgrade guide](/petal-pro/upgrade-guide): the main ones route its `resend` handler through `send_pin/2`, so a resend meets the same limit as the first request, and lower-case the email in the limit key. Until then "Resend" still issues pins without limit in your app. Take `test/petal_pro/user_pin_test.exs` with the new `user_pin.ex` too, because the 4.5.0 copy has a test that fails against it. - **Two-factor codes are limited to five tries per five minutes.** The TOTP step had no limit, so someone who already had a user's password could work through six-digit codes until one matched. The limit is per user, counts every submit and needs no configuration. A correct code starts the count again, and a user who mistypes five times in a row waits out the window. Backup codes go through the same form and the same limit. - **API sign-in is limited per account as well as per address.** Ten tries per ten minutes for one email, whatever addresses they come from. A sign-in that works starts the count again, so a client that signs in often is not refused for its own successes. The per-address limit alone does nothing against a caller with many addresses (an IPv6 range, a botnet), who meets a fresh budget each time. 4.5.2 closes a way round this limit: on some databases the same account could be reached under another spelling of its email, each with a count of its own, and on 4.5.2 the count is kept on the account. #### Fixed - **The API and passkey rate limits count the client, not the proxy.** The API sign-in (5 a minute), API registration (3 an hour) and passkey sign-in (10 a minute) limits were keyed on `conn.remote_ip`. Behind Fly, Render, nginx or any other proxy that is the proxy's address, so every visitor shared one budget: three API registrations an hour for the whole app, and one caller could use any of the three up for everyone. They now use the address `PetalProWeb.ClientIp` resolves, the one `last_signed_in_ip` has recorded since 4.5.0, through the new `PetalProWeb.ClientIp.rate_limit_key/2`. This has been the case since the limits were added (4.0.0 for the API, 4.1.0 for passkeys). See the [upgrade guide](/petal-pro/upgrade-guide). - Upgrade: this only takes effect once the app knows which address is the client's. If you have not set `CLIENT_IP_HEADER` or `TRUSTED_PROXY_HOPS`, nothing changes and visitors behind your proxy still share a budget. On Fly, add `CLIENT_IP_HEADER = "fly-client-ip"` to the `[env]` block of `fly.toml` (the same step as in the 4.5.0 notes). Behind Cloudflare use `cf-connecting-ip`; behind one nginx or Caddy use `TRUSTED_PROXY_HOPS=1`. See "Client IP Behind a Proxy" in `DEPLOYMENT.md`. - Upgrade: if you copied one of these `rate_limit` plugs, swap its `conn.remote_ip` line for `PetalProWeb.ClientIp.rate_limit_key(conn, "")`. - **The passkey rate limit no longer counts page views, and it answers when it refuses.** The sign-in page asks for a passkey challenge every time it loads, and each one counted against the same ten a minute as real sign-in attempts, so ordinary traffic could use the budget up. Past the limit the request was stopped without a response, which is a 500. Only sign-in attempts count now, and a refused one goes back to the sign-in page with "Too many attempts". ### 4.5.0 - 2026-11-11 #### Security - **`UserAuth.get_ip/1` no longer trusts the client-written `x-forwarded-for`.** It used to take the first `x-forwarded-for` entry, which the client controls. The new `PetalProWeb.ClientIp` returns the connection peer unless config names a trusted proxy. The chosen value is parsed strictly, and anything malformed falls back to the peer. `last_signed_in_ip` and impersonation audit entries now record a real address, and an `x-forwarded-for` entry over 255 characters, or one that isn't valid UTF-8, can no longer 500 a sign-in after the session token was minted. See the [upgrade guide](/petal-pro/upgrade-guide). - Upgrade: on Fly, add `CLIENT_IP_HEADER = "fly-client-ip"` to the `[env]` block in `fly.toml`, or sign-ins will record Fly's proxy address. - Upgrade: elsewhere, set `CLIENT_IP_HEADER` to your proxy's header (e.g. `cf-connecting-ip`) or set `TRUSTED_PROXY_HOPS` (how many trailing `x-forwarded-for` entries your proxies append, default `0`). `TRUSTED_PROXY_HOPS=2` also works on Fly, and `1` works behind a single nginx. It must be a whole number, or the release fails to boot. - Behaviour change: for a peer that isn't an IP, `get_ip/1` now returns `nil` where it used to raise. - **Production forces HTTPS.** The new `PetalProWeb.ForceSSLPlug` wraps `Plug.SSL` with runtime config from `config/runtime.exs` (validated once at boot from `PetalPro.Application`). In prod it trusts `x-forwarded-proto` and `fly-forwarded-proto` (`rewrite_on`), redirects plain http (301 for GET and HEAD, 307 for other methods) and sends a one-year HSTS header on https responses. Because a proxied https request now counts as https, Plug marks the cookies it writes, including the session and remember-me cookies, `Secure`. HSTS itself sets no cookie flags. The session cookie options also set `same_site: "Lax"` and `http_only: true` outright. Behind Fly, Render, Railway and similar hosts, cookies no longer go out without `Secure`, and Firefox and Safari now treat the session cookie as Lax instead of sending it on every cross-site request. See the HTTPS section in `DEPLOYMENT.md`. - Upgrade: the new `FORCE_SSL` env var is on by default in prod (on when unset, `true` or `1`, off for any other value). Behind a proxy that sends no forwarded-proto header, every request redirects to itself unless you set `FORCE_SSL=false`. Keep it on if you terminate TLS in the app. - Upgrade: an HTTP health check (for example one in `fly.toml`) needs an `X-Forwarded-Proto: https` header or a path exclusion in `config :petal_pro, :force_ssl` of the form `exclude: [hosts: ["localhost", "127.0.0.1"], paths: ["/healthz"]]` (keep the `hosts` entry, since any `exclude` replaces Plug.SSL's default), or it gets a 301. Default TCP checks are unaffected. - **Sentry request context.** The new `PetalProWeb.SentryContextPlug` adds request context to Sentry events, using the same client IP as `PetalProWeb.ClientIp`. It masks sign-in secrets: the TOTP code, PIN, `sign_in_token`, passkey assertions, OAuth code and state, and confirm and reset tokens. It does nothing until `SENTRY_DSN` is set. If you care about what you send to Sentry, note that events now include request context, including the client IP. #### Changed - **Settings screens move to a two-pane layout.** At `lg` and up the settings nav sits in its own pane, with a pill and primary-coloured text and icon on the active item, `aria-current` on the active link and a real nav landmark. The content card has new chrome. Below `lg` the nav becomes a horizontal scroll strip with edge fades, and the new `ScrollStripHook` keeps the active item centred. This covers every user, org and billing settings screen, and none of them need code changes on your side. `page_header/1` and `box/1` are unchanged. See the [upgrade guide](/petal-pro/upgrade-guide). - Upgrade: if you customised `sidebar_tabs_container/1` or `sidebar_menu_item/1` in `page_components.ex`, merge those by hand. - New pieces: `assets/js/hooks/scroll-strip-hook.js` (registered as `ScrollStripHook` in `hooks/index.js`), and `scrollbar-none` and `scroll-strip-fade` `@utility` blocks in `app.css`. - **Every settings screen gets a header and its own page title.** Each screen now opens with the new `settings_header/1`, which has a one-line description, and sets its own `page_title`, so browser tabs read "Email - Petal" or "Password - Petal" where stock used to show a literal "Settings" (profile, Your Data) or just the app name. Nav labels are now nouns: "Edit profile" becomes "Profile", "Change email" becomes "Email", "Edit password" becomes "Password", "Edit notifications" becomes "Notifications" and the org "Edit" becomes "General". This only changes copy, but tests that assert the old labels or headings need updating. Every string goes through gettext, so translations need the new msgids. - **Settings forms share one layout.** Single text, email and password fields are capped at `max-w-md`, so the profile, email, password and org forms no longer stretch inputs to about 900px. Every editable form ends in a `border-t` action bar with the primary button on the right. The password form keeps "Forgot your password?" on the left. Only classes and markup changed. Handlers, params and validations are untouched. - **The billing screen is rebuilt around a plan card.** The card shows the product, a Trial badge, the price, and a `dl` with the last invoice, the upcoming invoice and the next charge. Cancelling now goes through a destructive `alert_dialog` ("Keep my subscription" / "Cancel anyway") that shows plan, price and next charge before you confirm. It replaces the dropdown and the browser `data-confirm`. With no subscription you get an `<.empty>` state with a single View plans button, and a provider failure shows a danger `<.alert>`. Event names, routes and params are unchanged, and `cancel_subscription` still drives the cancel. Tests that relied on `data-confirm` or the old spinner markup need updating. - **Account deletion on Your Data becomes a danger-zone panel.** The panel has a danger hairline, a warning icon chip and a list of consequences. The inline two-stage confirm is replaced by a destructive `alert_dialog` ("Delete my account" / "Keep my account"), and status notices are now `<.alert>`s. The GDPR flow and `confirm_delete` are unchanged. The `show_delete_confirm` and `cancel_delete` events that drove the old inline confirm are removed, so any code or tests that send them will break. Org deletion still has no UI, by design. - **Notification preferences are switches.** Each preference renders as `<.field type="switch">` in place of a checkbox, and still sends the same `toggle_preference` event and payload. Channels locked by `allow_disable_in_app` / `allow_disable_email` show as disabled, always-on switches. Tests that select checkbox inputs may need updating. - **TOTP setup is clearer.** Setup is two numbered step cards (a framed QR code or a select-all mono secret), and the code field is now petal_components' `input_otp` (6 segments, `autocomplete="one-time-code"`), so SMS and password-manager autofill work. It still posts `user_totp[code]`. Once 2FA is on, the screen shows a `success-*` status row, and backup codes are select-all mono chips. Disabling 2FA and regenerating backup codes move from `data-confirm` to destructive `alert_dialog`s. Form params are unchanged. Tests that assert "2FA Enabled" (now "2FA enabled") or `data-confirm` selectors need updating. The `input_otp` wrapper takes the `id`, and the real input is `id <> "-input"` (`totp-code-input` in stock Pro). - **The passkeys screen matches the rest of settings.** Its six inner panels move to the gray-400 alpha ladder and `--pc-radius`. This also fixes two dark-mode contrast problems: the gray-800 key-icon circle and the gray-800/50 info wash. Only classes changed. - **The last three hand-rolled modals now use `<.modal>` from petal_components.** The onboarding LiveView and both email-link unsubscribe pages now render petal_components' `<.modal hide_header>` in place of their own hand-rolled modal markup, and pick up the library's dark mode and focus handling. If you customised the onboarding or unsubscribe templates, re-port them onto `<.modal hide_header>`. - **Flash messages are toasts.** `PetalProWeb.Flash.flash_group/1` renders petal_components' `<.toast_group>` with its `put_flash` bridge, so every `put_flash(:info | :success | :warning | :error)` shows as a stacked, swipe-to-dismiss toast with a progress bar. Call sites don't change. The 10 second timer stays, and a new `position` attr sets where toasts appear. LiveViews can call `PetalComponents.Toast.send_toast/3` for richer toasts. Only those four flash kinds reach the toast, so app-private flash keys stay out. The disconnected banner is unchanged. It can overlap a toast bottom-right, so use `position="bottom-left"` if that bothers you. - **Empty states use `<.empty>`.** Every hand-rolled empty state now has a title, a one-sentence description and a single CTA where a create action exists. Covered: the DataTable fallback on all admin indexes (with "Clear filters" when filtered), the notifications page and bell, admin chat history, admin user and org show memberships, the orgs list, org team invitations, passkeys, org invitations, the blog index, the admin dashboard chart panels, and the admin file picker, which had no empty state before. DataTable keeps `empty_icon` / `empty_title` / `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 `

`, a dashed box, an icon circle) need updating to the `.pc-empty` structure. - **Status pills use `<.status_badge>` and roles use `<.role_badge>`.** `<.status_badge status={@status}>` is a `<.badge dot>` rendered through the new `PetalProWeb.StatusBadge` (imported by `use PetalProComponents`). One status-to-colour map now covers subscriptions, the billing card, changelog draft/published/archived, user state, dashboard recently-joined and invitation state. Admin user show gains a Status row, the org team table gains a Status column, and every row in Admin > Users carries a role chip. - Removed helpers: `ChangelogHelpers.status_badge_class/1` is gone, so call `<.status_badge>` in its place. The private `role_label` / `role_badge_color` helpers in `OrgsLive` and `AdminOrgLive.Show` are gone too. - Colour changes: trialing on the admin subscriptions table and the admin role both go from warning to info. On the dashboard, 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`. - **petal_components 4.6.0 to 4.18.0.** The minimum is now `~> 4.18`, and phoenix 1.8.16, phoenix_html 4.4.0 and phoenix_pubsub 2.4.1 come along. The update also moves Pro's production web server, bandit 1.12 to 1.14 and thousand_island 1.5 to 1.6, plus smaller bumps to lazy_html, plug_crypto, elixir_make and fine. See the [upgrade guide](/petal-pro/upgrade-guide). - Upgrade: run `mix deps.update petal_components` after taking this release. - Upgrade: `Layouts.empty/1` is renamed to `Layouts.blank/1`, because the library now ships `<.empty>`, so calls to `Layouts.empty` break. - Upgrade: the library now exports names Pro used to define (`combo_box` from 4.12, `data_table` from 4.13, plus the four components under Removed). `PetalProComponents` imports the free modules, drops the Pro copies it deletes, and keeps Pro's own `data_table` with `import PetalComponents.DataTable, except: [data_table: 1]`. If you edited that file, match the 4.5.0 import list in the upgrade guide or the build fails with "call is ambiguous". - What you pick up along the way: - 4.6.1/4.6.2: dark and ghost surfaces follow the remapped gray, so sign-in inputs and dropdown triggers match Pro's slate panels. - 4.11: `hide_header` on `<.modal>`. - 4.12: free `combo_box`. - 4.13: free `data_table`. - 4.15: `<.empty>`, a `:footer` slot on modal, and dropdown auto-flip (a dropdown panel opens upward when there's no room below). - 4.16: Typeset font tokens (`--pc-font-heading`, `--pc-font-body`, `--pc-font-mono`), so one `@theme` block can retype the whole UI, plus lining numerals on counters, a single error ring on `input_group`, and a `slide_over` that falls back instead of crashing on an unknown origin. - 4.16.1: `shrink-0` on the colour-scheme switch and icon triggers. - 4.17.1: multi-select `combo_box` posts values in pick order. - 4.18.0: the toast hook no longer logs a console error on controller-rendered pages, and `<.alert>` gains `dismiss_label`. - New components such as empty, slider, filters, kbd and qr_code are available. - **Flop 0.26.3 to 0.27.0.** This supports the new DataTable FlopBridge (below). Pro's two settings modules were updated for it. - Upgrade: `mix.exs` still allows `~> 0.20`, so the bump comes from `mix.lock`. Flop 0.27.0 requires `:ecto_type` on every join field and custom field, so your own `Flop.Schema` derivations with `join_fields` or `custom_fields` fail until they're annotated. - Behaviour change: 0.27 caps filters per request at 20 by default (`max_filters`). #### Removed - **Four Pro components retire in favour of their petal_components versions.** `color_scheme_switch`, `language_select`, `local_time` and `social_button` are now provided by the free library, so the Pro copies are deleted. `PetalProComponents` imports the free modules, so `use PetalProComponents` still provides every name. The `ColorSchemeHook` and `LocalTimeHook` JS hooks are deleted. See the [upgrade guide](/petal-pro/upgrade-guide). - Upgrade: delete the four old files in `lib/petal_pro_web/components/pro_components/` (`color_scheme_switch.ex`, `language_select.ex`, `local_time.ex`, `social_button.ex`), and `assets/js/hooks/color-scheme-hook.js` and `local-time-hook.js` along with their `index.js` entries. Fully qualified calls such as `PetalProWeb.ColorSchemeSwitch.color_scheme_switch` break, so use the plain tags. - `color_scheme_switch`: now requires an `id`. `` in the head becomes `<.color_scheme_script />`. It uses the same `localStorage.scheme` key, so saved preferences survive, and it adds live system-preference tracking and cross-tab sync. - `local_time`: now requires an `id`. `for=` becomes `at=`. luxon `preset=` names and `format=` token strings are replaced by `format="datetime"` (the default, roughly the old `DATETIME_MED`), `"date"`, `"time"`, `"relative"` or a map of `Intl.DateTimeFormat` options. `locale` now defaults to the browser's own, where it used to default to `"en"`. luxon is now orphaned in `package.json` and can be dropped. - `social_button`: `logo=` becomes `provider=` and `link_type="a" to=` becomes `href=` (`navigate=` and `patch=` cover the live link types). The twitter bird is now `x`. `variant` now defaults to `"outline"`, where it used to default to `"solid"`. - `language_select`: a straight swap. - If you have a customised fork of the old Pro copies, keep it and skip this part. - **Tom Select.** `PetalProWeb.ComboBox`, the `ComboBoxHook`, `assets/css/combo-box.css` (about 12 KB) and the `tom-select` npm package are deleted. The two admin membership pickers and the `petal.gen.live` / `petal.gen.html` generators now render `<.field type="combobox">` from petal_components, which carries its value in a hidden native select. Selections now survive a LiveSocket reconnect through LiveView's own form recovery (customer issue #306). A new `tom_select_retired_test.exs` fails if any remnant is left. See the [upgrade guide](/petal-pro/upgrade-guide). - Upgrade: `<.combo_box label= help_text= />` becomes `<.field type="combobox" label= help_text= />`. `tom_select_plugins` (its `remove_button` plugin) becomes `clearable`, which is off by default where the old remove button was on, and `remove_button_title` becomes `remove_label`. `multiple`, `create`, `max_items`, `placeholder`, `disabled`, `required`, `remote_options_event_name` and `remote_options_target` keep their names. `tom_select_options` and `tom_select_options_global_variable` have no equivalent. - Behaviour change: a disabled single-select combobox posts nothing for its field, because there is no longer a hidden `""` input. - Cleanup: delete `assets/js/hooks/combo-box-hook.js` and its `ComboBoxHook` line in `hooks/index.js`, `assets/css/combo-box.css` and its `@import` in `app.css`, and `lib/petal_pro_web/components/pro_components/combo_box.ex` with its `import PetalProWeb.ComboBox` in `PetalProComponents` (replaced by `import PetalComponents.ComboBox`). Then run `npm uninstall tom-select --prefix assets`. - If you have a forked wrapper, keep it and skip this part. #### Added - **Layout shell options.** `sidebar_layout` gains a `mobile_top_right` slot. Menu items take `related_pages`, matched by one shared function, `PetalProWeb.SidebarMenu.menu_item_active?/2`, and the active link carries `aria-current`. In stock config `:subscribe` relates `:subscribed` and `:billing`, so Subscribe stays highlighted on billing pages. `sidebar_user_profile` gains a `top_nav` variant and an `id` attr, so the user menu can live in a top bar. - Upgrade: matching is explicit (no prefix match), so add `related_pages` for any nested page that should light up an item. - Upgrade: the colour-scheme switches now have fixed ids (in 4.4.0 each render got a random UUID): `sidebar-user-profile-color-scheme` in the sidebar user dropdown (prefixed by the new `id` attr, default `sidebar-user-profile`), `navbar-color-scheme` / `navbar-color-scheme-mobile` in the stacked layout and `public-navbar-color-scheme` on public pages. - **DataTable FlopBridge.** `PetalPro.DataTable.FlopBridge` connects Flop queries to petal_components' free `data_table`, and a differential test gate checks 986 cases against the library's in-memory engine. No admin screen uses it yet, so nothing visible changes. It lays the groundwork for moving admin screens to the free `data_table` later. - **A third collision-guard test.** It compiles the real `use PetalProWeb, :html` import scope to catch name clashes between Pro and petal_components. - **Generator CI job.** Every `petal.gen.*` generator runs on every push and its output has to compile, so generator drift shows up in CI. #### Fixed - **The billing screen no longer crashes at a month boundary.** The meter summary guards compared `DateTime` structs with `>`, which compares them structurally, so a valid Aug 31 to Sep 1 window failed with `FunctionClauseError`. That hit metered subscriptions in the first days of any month whose billing period started the month before. The check now uses `DateTime.compare/2` (or an integer compare for Unix timestamps). An inverted range now raises a clear `ArgumentError`. - **The failed billing state no longer shows "No active subscriptions" under the error.** A provider failure now renders only the danger `<.alert>`. - **Semantic colour utilities always render their real colour.** The semantic aliases in `colors.css` (`danger`, `success` and the rest) used `@theme inline`. Tailwind v4 tree-shakes each stop separately, so a semantic stop went unresolved unless the matching literal palette stop happened to be used somewhere, and utilities like `text-danger-400` silently fell back to inherited gray. The alias block now uses plain `@theme`. If you edited `assets/css/colors.css`, make the same one-line change on your alias block. - **The unsubscribe pages are clickable again.** Under Tailwind v4 the gray overlay on both email-link unsubscribe pages painted over the confirmation panel and blocked clicks. The move to `<.modal>` (above) replaces that hand-rolled markup. - **Sidebar menu items with the same label no longer produce duplicate HTML ids.** Ids now derive from `:name`, falling back to a slug of the label. This applies to `menu_item__anchor` and `dropdown_` / `dropdown__button`. It fixes invalid markup and broken id-based test selectors when menus reuse a label, such as "Settings" in both the org and user groups (customer issue #298). 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`. Custom JS, CSS or tests that target the old label-derived ids need updating. - **Combo box selections survive a LiveSocket reconnect** (customer issue #306). See the Tom Select removal above. - **Mobile layouts clear the iOS browser bar.** `sidebar_layout` and `stacked_layout` use `h-dvh` in place of `h-screen`, so the sidebar's profile row and the last line of a page no longer sit under the browser bar. `<.layout type="stacked">` also renders the caller's `top_right` / `top_right_mobile` slots, which it used to drop. - **`mix quality` passes end to end on a fresh clone again.** A too-deep function in the passkey settings LiveView is flattened for `credo --strict`. The S3 module now signs download and delete requests with the full SigV4 config, which clears 11 dialyzer warnings with no new ignore entries. - **Flash messages on controller-rendered pages no longer log a console error.** A flash on a page rendered by a controller, not a LiveView, used to log "unable to push hook event. LiveView not connected" in the browser console, because the toast hook tried to talk to a LiveView that wasn't there. Fixed upstream in petal_components 4.18.0, which this release requires. - **The Stripe logo on the landing page draws in full.** A doubled minus sign in its SVG path data stopped the browser parsing partway through, so the "p" lost its counter, the "e" never drew and every visit logged an SVG path error in the console. --- ### 4.4.0 - 2026-07-17 #### Changed - **Adopted petal_components v4.6.** `aurora` and `border_beam` used to be Petal Pro components. They are now part of the free petal_components library, rebuilt with glow, multiple beams, and spring easing, so Pro deletes its own copies and consumes the free ones like every other component. The dependency minimum is now `~> 4.6`. Take Pro 4.4.0 *before* you run `mix deps.update petal_components`: bump petal_components first on an older Pro and the build fails with `function border_beam/1 imported from both PetalProWeb.BorderBeam and PetalComponents.BorderBeam, call is ambiguous`, because both libraries now export it. `aurora` is the same problem but quieter, since Pro never calls it itself. If you customised either component a handful of attributes were renamed. See the [upgrade guide](/petal-pro/upgrade-guide) for the rename tables and, if your membership has lapsed, a complete manual fix that needs no repo access. - **Ported the sign-in card to the free `border_beam`.** `auth_layout` now uses the free component (`gradient_color_start` becomes `color_from`, `gradient_color_end` becomes `color_to`, `animation_duration` becomes `duration`). The free beam styles its own panel, so the card's background, border and radius classes came out, and the corner radius now follows your `--pc-radius` theme token. Dark mode picks up the library's material in place of the old translucent blur. #### Removed - **`floating_div` and its `@floating-ui/dom` npm dependency.** It had no call sites left in Pro. Reach for the free `popover` in top-layer mode (`<.popover top_layer>`) instead, which covers the same case of a panel escaping a clipped container. A `<.floating_div>` in your own code raises a compile error on upgrade; the [upgrade guide](/petal-pro/upgrade-guide) has the swap. #### Added - **Reserved-namespace guard test.** `test/petal_pro_web/components/petal_components_collision_test.exs` walks both libraries at runtime and fails if any Pro component defines a name that `use PetalComponents` also exports. This is what stops the ambiguous-import bug from ever coming back, and it drops straight into your own test suite. - **Excluded the petal_components showcase from the Tailwind scan.** `assets/css/app.css` gains a `@source not` line for the dependency's showcase example modules, so their markup stops pulling extra classes into your CSS build. --- ### 4.3.0 - 2026-06-24 #### Added - **Private S3 buckets.** Set `private: true` in your `:s3` config and uploads stay out of public view. `consume_uploaded_entries/2` stores just the object key, and `PetalPro.FileUploads.download_url/1` returns a short-lived presigned GET URL when you display the file. It is a no-op for public buckets and other providers, so you can call it unconditionally in your templates. - **Cloudflare R2 and Fly Tigris support.** Point the new `endpoint` config at R2, Tigris, or any S3-compatible service and uploads, downloads, and deletes all run through the same presigned path. Both ride on the existing S3 provider. - **File deletion across providers.** Every upload provider now implements `delete_file/1`, and a user's old avatar is removed from storage automatically when they replace or clear it. - **SAML SSO recipe.** A new `/recipes:add-saml-sso` walkthrough for wiring up enterprise identity providers (Okta, Microsoft Entra, Google Workspace), with the security prerequisites spelled out. --- ### 4.2.0 - 2026-06-08 #### Changed - **Upgraded to Petal Components v4.** Petal Components dropped Alpine.js (every component is now `Phoenix.LiveView.JS` only) and ships its own JS. `assets/js/app.js` now imports the `petal_components` bundle and merges its hooks into the LiveSocket - these power the password / copyable / clearable inputs, the accordion, and the Chat components. Alpine.js stays for Petal Pro's own components (sidebar persistence etc.), so nothing else changes for you. The `js_lib` attribute was removed from `<.dropdown>`, `<.accordion>`, and the menu components and now raises if passed - if you've customised a call site that passes `js_lib`, drop it. See the [Petal Components v4 upgrade guide](https://hexdocs.pm/petal_components/upgrade_guide.html). --- ### 4.1.0 - 2026-05-21 #### Added - **WebAuthn passkey authentication** - register up to 5 passkeys (Face ID, Touch ID, hardware keys) from your security settings. Two modes: primary auth (passwordless sign-in) and second factor (2FA on top of password). Includes cloned authenticator detection via sign count validation and a guard against passkey 2FA bypass in `require_authenticated_user/2` - **Persistent admin chat history** - AI admin chat conversations are now stored in the DB. They survive reloads and restarts, and the sidebar lists recent conversations so you can pick up where you left off - **`mix quality` now runs `credo --strict` and `dialyzer`** - fresh clones pass both out of the box. Existing projects will need to clean up any strict credo violations and get dialyzer running #### Fixed - Passkey sign-in session establishment before redirect - Cloned authenticator detection via sign count validation - Passkey 2FA bypass guard in `require_authenticated_user/2` --- ### 4.0.0 - 2026-05-04 #### Added - **GDPR compliance** — "Your Data" settings page (`/app/users/your-data`) lets users download all personal data as JSON and submit account deletion requests with soft-delete, anonymization cascade, and Oban background processing - **Per-type notification preferences** — users can toggle in-app and email channels independently per notification type; security-critical notifications (e.g. password changes) are forced-on and cannot be disabled - **`Notifications.notify/3` entry point** — single dispatch function that checks per-user, per-type preferences before sending in-app or email notifications - **Welcome notification** on registration and password change alert on password update - **Admin MCP server** — exposes admin tools to external AI clients (Claude Code, Claude Desktop) via JSON-RPC 2.0 at `POST /api/mcp` with bearer token auth; set `MCP_ADMIN_TOKEN` env var - **AI cost tracking** — Req plugin that automatically logs every AI API call with token counts, costs, and timing to the `ai_call_logs` table - **Admin chat tools** — `ManageUser` (suspend/unsuspend/delete/restore/promote), `ListOrgs`, `ManageOrg` (rename/delete/members), and `GetAiCallStats` - **Changelog MCP tools** — `list_changelog_updates`, `manage_changelog`, and `create_changelog_update` for AI admin chat and external MCP clients - **In-app feedback system** — users can submit feedback from any page; admin dashboard for reviewing and managing submissions - **Sentry error monitoring** — auto-activates when `SENTRY_DSN` env var is set; no code changes required - **Hammer-based rate limiting** — applied to auth endpoints via plugs - **Resend email adapter** — set `RESEND_API_KEY` to use Resend for transactional email via Swoosh - **Production Dockerfile** — ready-to-use containerized deployment - **Generic JS hooks collection** — infinite scroll, scroll to bottom, scroll to hash, select all, share - **Email component enhancements** — configurable gap, gray button variant, and callout boxes - **Dev scripts** — `server.sh`, `reset_db.sh`, `kill_db.sh` for common development tasks - **Lightweight page view analytics** — bot filtering and daily aggregation - **Daily Slack digest worker** — activity summaries via Oban cron - **Slow query telemetry logging** — configurable threshold for dev environment - **Interactive DB schema visualizer** — dev page with Mermaid ER diagrams (pan/zoom), domain-grouped tables, column details with PK/FK indicators - **Hierarchical route tree** — collapsible tree view mirroring URL path structure with verb badges and click-to-copy helpers - **22 AI-powered recipe commands** (`.claude/commands/recipes/`) — Claude Code slash commands for common customizations: auth, billing, feature removal, integrations, structural changes - **Claude Code sub-agents** — `schema-architect`, `test-runner`, `elixir-reviewer`, `heex-reviewer`, `ui-ux-reviewer` - **Claude Code skills and commands** — CI, commit, review, changelog, scaffolding workflows - **COMPONENTS.md** — reference document cataloging all available components and JS hooks - **CLAUDE.md project instructions** — scoped per directory for in-repo AI context #### Updated - **Jido AI for admin chat** — replaced LangChain with native `Jido.Action` modules under `PetalPro.AI.AdminChat.Actions.*`, registered in `ActionRegistry` and shared by both the chat LiveView and the MCP server - **Req for all HTTP calls** — replaced HTTPoison and Tesla throughout - **Sidebar-only layout** — converted to sidebar-only; no desktop header; integrated user profile and notification badge - **Styler upgraded from 0.11 to 1.11** — run `mix format` after upgrading - **Changelog context** — restructured `ChangelogUpdates` → `Changelog` with proper schema naming (`Update`, `Like`, `Read`), Flop DataTable with pagination/sorting/filtering on admin index, shared `ChangelogHelpers` module, comprehensive test coverage, and SEO meta descriptions on public pages - **Modularized seed system** — split into production and development modules - **Fly.io deploy** — now triggers on push to main - **NPM packages updated** — including ESbuild, with updated `esbuild.js` - **Sidebar collapse button** — redesigned as flush edge tab with directional chevrons; deferred transitions prevent flash on load - **Updated deps** — `phoenix_live_view 1.1.27`, `petal_components 3.0.2`, `jido 2.1`, `sentry 12.0.3`, `swoosh 1.23.1` #### Fixed - Wallaby test race condition in signup flow --- ### 3.0.0 - 2025-07-22 - Upgrades Petal Pro to Tailwind 4! - New Pro components - Aurora and BorderBeam - Adds support for Stripe metered usage - Replaces Admin Jobs with Oban Web - Adds `TailwindFormatter` - Port is configurable for the test environment - Updated: Adds `mix assets.build` - Updated: Combobox will warn if `:tom_select_options_global_variable` includes load handler and `:remote_options_event_name` is set - Fixed: SubscribeController redirects and shows Stripe error - Fixed: Authenticated views no longer auto-subscribe to user notifications - Fixed: Adds missed exception for blog route - Fixed: Seeder clears posts/files properly - Fixed: Post/File is based on PetalPro.Schema - Fixed: Combobox does not disappear when navigating to another page #### Upgrade Notes Petal Pro has been upgraded to Tailwind 4. Some utilities have been removed or renamed. See the [Tailwind upgrade guide](https://tailwindcss.com/docs/upgrade-guide) for more information. To upgrade to Tailwind 4 in your project, make sure you update `mix.exs`: ```diff - {: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): ```diff 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: ```shell mix tailwind.install ``` #### Updated app.css `app.css` has been updated to support CSS first configuration:

app.css
```elixir @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](https://github.com/petalframework/petal_pro/tree/v3.0.0/assets/css) 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](https://tailwindcss.com/docs/upgrade-guide) to update the rest of your project. Running `mix format` should automatically arrange tailwind classes in your project. ### 2.2.0 - 2024-12-19 - Upgrades Petal Pro to LiveView 1.0.1! - Admin/User AI chat - use LangChain to interrogate Petal Pro - Content Editor component - based on Editor.js - Blog/Content Management System - leveraging Content Editor - Updated: Using latest Heroicons from Petal Components 2.0.6 - Updated: address gettext deprecation issue - Updated: `petal.gen.live` uses Table instead of Data Table (and is based on streams). Use the `--data-table` option to generate templates using a Data Table - Updated: Compatability increased for code generated by `phx.gen.live` and `phx.gen.html` - Fixed: `sticky` class for stacked layout - Fixed: Sub-menu will display for Stacked Layout in mobile mode - Fixed: User notifications marked as read based on `socket` url (previously only worked with `conn` request path) - Fixed: Combobox has rounded corners after selection #### Upgrade Notes In Petal Components, the `heroicons` dependency has been replaced with an alternate CSS-based approach. This is based on what has been implemented in the Phoenix repo - the reasoning is explained in this [issue](https://github.com/phoenixframework/phoenix/issues/5622). To upgrade an existing Petal Pro project, add the dependency in `mix.exs`:
mix.exs
```diff 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
```diff 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}) + }) ], }; ``` ### 2.0.0 - 2024-08-15 - Petal Framework is merged into Petal Pro - Npm packages recipe is merged in as default - Persistent user notifications - Graphs/stats dashboard in the Admin console - See who's currently active (via Presence) in the Admin console - If user belongs to only one org, current org is automatically set - `User.is_admin` is replaced with `User.role`. User role is an enum - Integrate `:typed_ecto_schema` with `Ecto.Schema` fallback for users who have not installed it. - Orgs are added to log view - Ecto insights tab is enabled in LiveDashboard - Fixed: Edge case for Combo Box - Tom Select is re-generated when there is a change in option count - Fixed: App does not crash when impersonating a user and the session has expired - Fixed: Subscription logs weren't working! - Fixed: Race condition with subscription create/update when responding to Stripe web hooks - Fixed: In docker compose, postgres container will not auto-restart if stopped #### Upgrade Notes Starting with this release, the Petal Framework is no longer referenced as an external package, and the private Petal hex repo it came from has since been shut down. If your Dockerfile has a `RUN --mount=type=secret,id=PETAL_LICENSE_KEY` step that adds that repo, 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](https://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. You may need to add `nodejs` and `npm`:
Dockerfile
```diff # 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: Finally, `lib/petal_pro_web/petal_framework_translations.ex` is no longer required. Components like the DataTable can use Gettext directly. ### 1.8.0 - 2024-04-04 - JSON API: You can use the Petal Pro API for user management (register, sign in and update). It comes with OpenAPI support out of the box. Includes Swagger UI - Update: Can sync all Stripe subscriptions including cancelled ones - Added expanded user and org admin pages - Fixed: PetalProWeb.Controllers.UserAuth.disconnect_user_liveviews doesn't disconnect the user's live views #216 - Fixed: Passwordless sign in issue from latest Phoenix Live View fixed #222 - Update: Sidebar layout now collapsible ### 1.7.0 - 2024-11-01 - Stripe integration - can buy subscriptions and manage them - support for both individuals and orgs - Use `styler` for code formatting - Updated landing page components to a more modern look #### Upgrade Notes Starting in this release, we now use [Styler](https://github.com/adobe/elixir-styler) to format our codebase. This means there will be a large amount of changes. To minimise merge or rebase conflicts when upgrading, we recommend you swap out Recode with Styler first: 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.6.2 - 2023-11-03 - Fix bug where users registering via passwordless / 3rd parties would not get invites to orgs ### 1.6.1 - 2023-9-28 - Important passwordless security fix - anyone using passwordless should update - Update deps ### 1.6.0 - 2023-7-05 #### New - <.image_upload> component for uploading single images like avatars. Used in user settings - Local, Cloudinary and S3 support for <.image_upload> - User impersonation - admins can login as any user without knowing their password - available via the Admin console (under the User menu). #### Updated - All forms now use the new FormField structure - <.public_layout> has been moved into public.html.heex (it's likely you'll want to modify this to your brand and hence a component doesn't make sense) #### Fixed - Reset password page now accessible when logged in (previously would redirect) #### Removed - Page builder (it was getting too complex to manage - let us know if you used this a lot and we'll consider bringing it back) ### 1.5.2 - 2023-4-20 #### New - Uses the `petal_framework` private package (deletes all the `_petal_framework` folders). This will allow for an easier upgrade process in the future, especially for components like the data table. - Data Table supports `base_url_params`. Keep custom query params when changing sort order. - Data Table is now self contained in the live view - code isn't scattered across the model and context. - Added `mix recode` for code linting and refactoring - Use `<.flash_group>` to show flash messages (Petal Framework 0.3.0) #### Changes - Enabled Wallaby tests by default (`mix test`) - Updated Tailwind to 3.3 - Updated Erlang to 25.3 - Added `rename_project` lib to replace custom mix task #### Breaking - Data table API has changed slightly. See our docs https://petal.build/components/data-table on how to use #### Fixed - Data table going blank when changing page size - Navigation problems for the Data Table when setting the `default_limit` via a schema file - Fix Finch issue with email sending ### 1.5.1 - 2023-3-10 #### New - Develop Petal Pro in GitHub CodeSpaces! - Data Table column - can now filter by a select list - Data Table column - can now filter by a float #### Changed - topbar.js version updated to 2.0 - mix setup no longer fetches tailwind/esbuild if they already exist - Upgrade Petal Components to 1.0 - Data Table is now a function component #### Fixed - Github auth working again ### 1.5.0 - 2023-2-10 #### Changed - Upgraded Phoenix to 1.7 - Routes use the new verified routes - Authentication pages converted to live views - Upgraded fully from Hericons v1 to v2 - `petal.gen.live` now uses the Data Table component - Tesla now uses the more secure Finch over Hackney (https://github.com/petalframework/petal_pro/issues/66) - Confirmation page will redirect to org invitations if invitation exists (https://github.com/petalframework/petal_pro/issues/68) - Removed Petal Enhance (it was more complex than we thought) #### Fixes - Redirect to `/app/orgs` if an invalid org slug is used (https://github.com/petalframework/petal_pro/issues/70) - When editing user via `/admin/users` - `patch_back_to_index` no longer crashes (https://github.com/petalframework/petal_pro/issues/61) - Always show Data Table filters (https://github.com/petalframework/petal_pro/issues/60) ### 1.4.1 - 2022-11-15 16:30:00 #### Added - Add Petal Enhance (recipes) #### Fixes - Fix admin users modal. Clicking off the modal now works - Change avatar_url to text in DB for long URLs - Whitelist Google profile picture images in CSP - Fix Mailbluster unsubscribe route + documentation ### 1.4.0 - 2022-10-12 23:44:20 #### Added - Updated to LiveView 0.18 + Petal Components 0.18 - All components updated with declarative assigns (attr / slot) - Data table component - Local time component - Sobelow for security checking - Coveralls for code test coverage - test.yml Github action for code quality - Easily modifiable content security policy to help prevent XSS - Added a docker-compose.yaml that adds Postgres so you don't need to install it #### Changed - Router significantly more streamlined - Some routes have been moved into their own files: AdminRoutes, AuthRoutes, DevRoutes, MailblusterRoutes - Users are forced to be confirmed to access /app routes (easily configurable) - Use Ecto enums for org roles #### Fixes - Fix reset password failing when signed in - Clean up dashboard_live.ex - some old code unused was left in there - Improved SEO meta tags in _head.html.eex - Show a warning in the logs when no title/meta_desciprion is set on a public page - Added `open-graph.png` (to be replaced by dev) - Fix require_confirmed_user plug - Fix landing page GSAP not working ### 1.3.0 - 2022-06-17 02:43:55 #### Added - Two-factor authentication using time-based one time passwords (paired with something like Google Authenticator) #### Changed - Decoupled DashboardLive from Orgs so you can get started quicker if you don't want orgs - Can pass a custom header class to the public layout - Sidebar and stacked layouts now support grouped menu items (see dev_layout_component.ex for an example) - Update Tailwind to 3.1 - Split CSS into different files thanks to Tailwind 3.1 #### Fixed - Onboarding now remembers user_return_to - Fixed nav dropdown bug after modal toggle - Fixed gettext in live views ### 1.2.0 - 2022-05-31 07:34:11 #### Added - Login with Google & Github - easy to add more auth providers - Passwordless auth - register/sign in via a code sent to your email - Orgs - create an org, invite & manage members, and more - User lifecycle actions - run code after actions like register, sign_in, sign_out, password_reset, etc - New generator: mix petal.gen.html (same args as phx.gen.html) - New component: <.markdown content=""> & <.pretty_markdown content=""> (uses Tailwind Typography plugin) - Added License and Privacy pages (with some content from a template to get you started) - New layout: <.layout type="public">, for public marketing related pages like landing, about us, privacy, etc - Hooks can now be run in dead views if compatible (see color-scheme-hook.js as an example) #### Changed - Simpler config access (`PetalPro.config(:app_name)` instead of `Application.get_env(:petal_pro, :app_name)`) - Refactor <.layout> to take less props - Refactor dark/light mode system. Much simpler now and no longer needs cookies - Put Petal Pro Components in their own folder for easier future upgrades (can duplicate if you want to modify them) - Sidebar and stacked layout have a new slot for the top right corner (if you want to add something like a notifications bell) #### Fixed - Log metadata wasn't being cast - More user actions are logged - Fixed petal.live generator tests - Added tests for user settings live views ### 1.1.1 - 2022-03-12 20:45:36 - Bump Oban version to stop random error showing - Bump Petal Components - Use new <.table> component in petal.gen.live generator & logs - Dark mode persists on all pages with cookies - Fix logo showing twice in emails - Improved the Fly.io deploy flow - Fix admin user search - Remove guide (this is now online) ### 1.1.0 - 2022-02-28 00:08:52 - Added generator `mix petal.gen.live` - Add gettext throughout public facing templates - Improved dev_guide - Add Oban - Easy Fly.io deployment --- # Upgrade Guide # Source: https://petal.build/petal-pro/upgrade-guide # 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](#4-5-0-4-5-1) 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
```diff - {: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: ```elixir @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
```elixir 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: ```elixir 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
```elixir 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
```elixir 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: ```elixir 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
```elixir 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](/petal-pro/fundamentals/deployment#counted-on-the-account). #### 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](/petal-pro/fundamentals/deployment#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: ```shell fly ssh console --app your-app-name --select /app/bin/your_app remote ``` Then: ```elixir 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](#4-5-0-4-5-1) 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
```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: ```diff - 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: ```shell 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
```elixir 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: ```diff -{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 | | `` | `<.color_scheme_script />` | goes in the same place in the head |
lib/petal_pro_web/components/layouts/head.html.heex
```diff - + <.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: ```shell 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 ` <%!-- Per-row checkboxes --%> ``` ### ShareHook Uses the Web Share API to trigger the native OS share sheet on mobile. Falls back to copying the URL to the clipboard on desktop browsers that don't support `navigator.share`. On clipboard copy, it pushes a `link_copied` event to LiveView so you can show a flash message. **Data attributes (all optional):** - `data-title` — share title (defaults to `document.title`) - `data-text` — share body text - `data-url` — URL to share (defaults to `window.location.href`) **Usage:** ```heex ``` Handle the clipboard fallback in LiveView: ```elixir def handle_event("link_copied", _params, socket) do {:noreply, put_flash(socket, :info, "Link copied to clipboard!")} end ``` --- # Translations # Source: https://petal.build/petal-pro/fundamentals/translations # Translations If you're new to translations then please take a look at our [Twitter thread](https://twitter.com/PetalFramework/status/1496216170084864000) explaining the basics. Also check out: - the [hex docs for Gettext](https://hexdocs.pm/gettext/Gettext.html) - a good [blog post](https://phrase.com/blog/posts/i18n-for-phoenix-applications-with-gettext/) explaining Gettext In a nutshell, you run text that you want translated through the `gettext` function and then add in your translations. These are found in `priv/gettext`. The `.pot` files are auto-generated - you just need to modify the files in the `LC_MESSAGES` folders. Note that you should only modify the files in the `LC_MESSAGES` folders — the `.pot` files are auto-generated. We've tried to implement `gettext` throughout the public facing areas of the boilerplate (we may have missed some places - feel free to point them out to us or a PR would be very helpful). ### How to add update your pot/po files after adding more gettexts When you add new `gettext` calls, your translation files won't show them until this command is run: ```shell mix gettext.extract --merge ``` Or if you can use our easier-to-remember alias (aliases are defined in the `mix.exs` file): ```shell mix update_translations ``` Then go and add your translations to the files in the `LC_MESSAGES` folders for each language. ### How to add/remove languages Modify the languages in the `confix.exs` file:
config.exs
```css config :petal_pro, PetalProWeb.Gettext, allowed_locales: ~w(en fr) config :petal_pro, :language_options, [ %{locale: "en", flag: "🇬🇧", label: "English"}, %{locale: "fr", flag: "🇫🇷", label: "French"} ] ``` If you're adding a new language, you'll need to run this (keep in mind `fr` means French - change this to whatever language you're adding - here's [a list of them all](https://www.gnu.org/software/gettext/manual/html_node/Usual-Language-Codes.html)): ```shell mix gettext.merge priv/gettext --locale fr ``` To delete a language, remove it from the config and delete the corresponding folder in `priv/gettext`. --- # Impersonation # Source: https://petal.build/petal-pro/fundamentals/impersonation # Impersonation Admins can sign in as any user In version 1.6 ([pull request](https://github.com/petalframework/petal_pro/pull/152)) we added the ability for admins to impersonate normal users. From the admin panel, admins can impersonate any normal user. This adds two routes: ```elixir post "/impersonate",UserImpersonationController,:create delete "/impersonate",UserImpersonationController,:delete ``` Clicking the "Impersonate" button will perform a POST request to the above route, including the user_id of the user to be impersonated. We store the admin's id in the session as `:impersonator_user_id`, and sign in the admin as that user. Once the admin has finished, the sign out button will be replaced with an "Exit impersonation" button. This button will hit the `:delete` action route, which looks for `:impersonator_user_id` in the session and uses it to sign in to the admin user again. An admin has to finish signing in before they can impersonate. Since 4.5.2, an admin who has typed their password but still owes a two-factor code or passkey is sent to that step instead. Before 4.5.2, impersonating and switching back skipped the second factor, so a password alone gave a full admin session. #### Turn off impersonation You can toggle impersonation on/off easily in `config.exs`: ```css config :petal_pro, impersonation_enabled?: false ``` --- # AI & Developer Tooling # Source: https://petal.build/petal-pro/fundamentals/ai-admin-chat # AI & Developer Tooling Petal Pro v4 includes a suite of AI-powered admin tools and first-class Claude Code integration. This page covers the in-app AI chat, the MCP server for external AI clients, and the Claude Code configuration that ships with every project. ## AI Admin Chat The AI Admin Chat is an admin-only chat interface that lets you interrogate your running Petal Pro app using natural language. Ask it to pull stats, look up users, manage orgs, or check AI usage costs — it figures out which tools to call, chains multiple calls if needed, and presents the results as readable text. It's powered by [Jido](https://github.com/agentjido/jido) and [ReqLLM](https://hexdocs.pm/req_llm) using Google Gemini, and shares the same action registry as the [Admin MCP Server](#admin-mcp-server). Conversations are saved to the database and survive page reloads and server restarts. The sidebar lists recent chats so you can pick up where you left off. ![AI admin chat with conversation history](/images/petal_pro_docs/v4/ai-admin-chat/admin_ai_chat_history.png) > **v4 migration note:** The AI Admin Chat was rewritten in v4 to use Jido and ReqLLM (replacing the LangChain-based implementation from v3). If you added custom LangChain tools in v3, you'll need to reimplement them as native `Jido.Action` modules described below. The tool surface is the same; only the implementation pattern changed. ### Architecture ``` Admin LiveView │ ▼ PetalPro.AI.Actions.AdminChatAction (Jido.Action) │ streams responses from Gemini via ReqLLM │ runs tool loop until no more tool calls ▼ PetalPro.AI.AdminChat.ActionRegistry (single source of registered actions) │ Jido.AI.Turn validates args + dispatches by name ▼ PetalPro.AI.AdminChat.Actions.* (individual Jido.Action modules) ▼ Your Repo / Contexts ``` The default model is `google:gemini-2.5-flash-lite`, overridable via the `:ai_admin_chat_model` app env. Every call goes through `PetalPro.AI.HTTP.client/1`, which attaches `PetalPro.AI.CostTrackerPlugin` as a Req response step — token counts and cost are logged to `ai_call_logs` automatically. ### Tools Are Native Jido Actions Every tool is a `Jido.Action` module. The action declares its name, description, and a [NimbleOptions](https://hexdocs.pm/nimble_options) schema, and Jido handles argument validation, JSON Schema generation for the LLM, and dispatch. ```elixir defmodule PetalPro.AI.AdminChat.Actions.ManageUser do use Jido.Action, name: "manage_user", description: "Manage a user account.", schema: [ user_id: [type: :string, required: true, doc: "The user's UUID."], action: [ type: {:in, ["suspend", "unsuspend", "delete", "undelete", "make_admin", "remove_admin"]}, required: true, doc: "Action to perform." ] ] @impl true def run(%{user_id: user_id, action: action}, _context) do # ... end end ``` | Field | Purpose | |---|---| | `name` | Unique string identifier used in `tools/call` | | `description` | Shown to the model — write it like a good function docstring | | `schema` | NimbleOptions keyword list — emits as JSON Schema for the LLM | | `run/2` | Receives validated, atom-keyed params and a context map | `:in` constraints emit as JSON Schema `enum` arrays so strict MCP clients see typed choices instead of free-form strings. ### Action Registry `PetalPro.AI.AdminChat.ActionRegistry` holds the `@actions` list and exposes two helpers used by both the chat LiveView and the MCP server: ```elixir # ReqLLM-shaped tool definitions (cached) ActionRegistry.req_llm_tools() # Action lookup map used by Jido.AI.Turn for dispatch (cached) ActionRegistry.action_map() ``` Both results are memoised in `:persistent_term`, so the registry has zero per-request overhead. Action modules live in `lib/petal_pro/ai/admin_chat/actions/`. The full list registered by default: - `get_site_stats` — user/org counts by period - `list_recent_users` — recently registered users - `search_users` — text search with filters - `manage_user` — suspend, unsuspend, delete, undelete, change role - `list_orgs` — organizations with member counts - `manage_org` — rename, delete, list members - `get_ai_call_stats` — AI usage costs and token breakdown - `list_changelog_updates` — read changelog entries - `create_changelog_update` — add a new changelog entry - `manage_changelog` — update or delete changelog entries ### AI Cost Tracking Every Gemini call is automatically tracked. The mechanism: 1. `PetalPro.AI.HTTP.client/1` returns a `Req` client with `CostTrackerPlugin` attached. 2. When a response comes back from a known AI provider, the plugin extracts token counts and snapshots the current per-million-token price. 3. An `AICallLog` record is inserted asynchronously via `Task.Supervisor` — cost tracking failure never interrupts the AI call. 4. The `operation` and `user_id` are read from the process dictionary (`:ai_cost_context`). To set attribution context before making AI calls: ```elixir Process.put(:ai_cost_context, %{operation: :my_feature, user_id: user.id}) ``` `AdminChatAction` already does this automatically (`operation: :admin_chat`). There's no admin screen for these logs yet. Query them with the `get_ai_call_stats` tool (from the admin chat or the MCP server), or read the `ai_call_logs` table directly. The `AICallLog` schema: ```elixir typed_schema "ai_call_logs" do field :provider, :string field :model, :string field :operation, :string field :input_tokens, :integer field :output_tokens, :integer field :input_price_per_million, :integer field :output_price_per_million, :integer field :total_cost_cents, :integer field :response_time_ms, :integer field :http_status, :integer field :error_message, :string belongs_to :user, PetalPro.Accounts.User timestamps(type: :utc_datetime, updated_at: false) end ``` ### Daily Budget The chat action enforces a per-user daily budget (default 500 cents / $5.00). Configure it in `config/config.exs`: ```elixir config :petal_pro, ai_daily_budget_cents: 500 ``` ### Configuration The API key is read from `config/runtime.exs` via the `:jido_ai` keyring: ```elixir config :jido_ai, keyring: [ google_gemini_api_key: System.get_env("GOOGLE_GEMINI_API_KEY") ] ``` Set `GOOGLE_GEMINI_API_KEY` in your environment. Without it, the action returns a descriptive error rather than crashing. The model used is `gemini-3.1-flash-lite-preview` (configured in `AdminChatAction`). The action supports up to 8 tool-call iterations per message (configurable via `config :petal_pro, ai_max_tool_iterations: 8`). ## Admin MCP Server Petal Pro ships with a built-in [Model Context Protocol](https://modelcontextprotocol.io/specification/2025-03-26) (MCP) server that exposes your app's admin tools to external AI clients such as Claude Code and Claude Desktop. Instead of logging into an admin panel to look up a user or check billing stats, you can ask your AI assistant directly — it talks to your running app over JSON-RPC 2.0, executes the relevant tool, and hands you back real data. ### The Endpoint All MCP traffic goes through a single HTTP endpoint: ``` POST /api/mcp Authorization: Bearer Content-Type: application/json ``` The server speaks [JSON-RPC 2.0](https://www.jsonrpc.org/specification) and accepts both single messages and batched arrays. Supported methods: | Method | Description | |---|---| | `initialize` | Protocol handshake — returns server name, version, and capabilities | | `tools/list` | Returns all registered tools with their input schemas | | `tools/call` | Executes a named tool with arguments | | `ping` | Health check | Quick sanity check with curl: ```shell curl -X POST http://localhost:4000/api/mcp \ -H "Authorization: Bearer dev-mcp-token" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' ``` ### Setup #### The Token The server authenticates via a static bearer token read from the `MCP_ADMIN_TOKEN` environment variable. In dev, a default of `"dev-mcp-token"` is used so you can get started immediately. Set a real secret for staging and production: ```shell # runtime.exs already reads this — just set the env var export MCP_ADMIN_TOKEN="your-long-random-secret" ``` On Fly.io: ```shell fly secrets set MCP_ADMIN_TOKEN="your-long-random-secret" ``` The token is compared with `Plug.Crypto.secure_compare/2` to avoid timing attacks. #### The Route The route is already wired in the router. You don't need to add anything. For reference, the controller that handles requests is `PetalProWeb.McpController`. ### Connecting Claude Code Create a `.mcp.json` file at the root of your project. It isn't gitignored out of the box, so add `.mcp.json` to your `.gitignore` before you put a real token in it: ```json { "mcpServers": { "petal-pro-dev": { "type": "http", "url": "http://localhost:4000/api/mcp", "headers": { "Authorization": "Bearer dev-mcp-token" } }, "petal-pro-prod": { "type": "http", "url": "https://yourapp.fly.dev/api/mcp", "headers": { "Authorization": "Bearer your-long-random-secret" } } } } ``` After saving, run `claude mcp list` or restart Claude Code — the `petal-pro-dev` server should appear. You can now ask things like "list the 5 most recent users" or "suspend user with id abc-123" directly in the chat. ### Connecting Claude Desktop Add the server to your Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS): ```json { "mcpServers": { "petal-pro": { "type": "http", "url": "https://yourapp.fly.dev/api/mcp", "headers": { "Authorization": "Bearer your-long-random-secret" } } } } ``` Restart Claude Desktop and the tools will appear in the tools panel. ### Built-in Tools The following tools ship with Petal Pro. They're all native `Jido.Action` modules under `lib/petal_pro/ai/admin_chat/actions/` and registered in `PetalPro.AI.AdminChat.ActionRegistry`. #### `get_site_stats` Returns platform metrics — total users, total orgs, and new signups/orgs for a given period (`today`, `week`, `month`, `all`). Useful for a quick health check. #### `list_recent_users` Lists recently registered users with basic profile info. #### `search_users` Text search across user accounts with optional status filters. #### `manage_user` Performs account management actions on a single user identified by UUID. Available actions: | Action | Effect | |---|---| | `suspend` | Prevents login | | `unsuspend` | Re-enables login | | `delete` | Soft-deletes the account | | `undelete` | Reverses soft-delete | | `make_admin` | Grants admin role | | `remove_admin` | Revokes admin role | All actions are audit-logged via `Logs.log_async/2`. #### `list_orgs` Lists organizations with member counts. Accepts an optional search term and result limit. #### `manage_org` Manages an organization by slug or UUID. Available actions: `rename` (requires `new_name`), `delete`, `list_members`. #### `get_ai_call_stats` Returns AI usage and cost statistics for a configurable lookback period (default 30 days, max 365). Includes total calls, token counts, costs in both cents and dollars, and breakdowns by model and operation. #### `list_changelog_updates`, `create_changelog_update`, `manage_changelog` Tools for reading and managing your app's changelog entries from the AI client. ### Adding a Custom Tool Define a `Jido.Action` module under `lib/petal_pro/ai/admin_chat/actions/`: ```elixir defmodule MyApp.AI.AdminChat.Actions.GetFeedbackStats do @moduledoc "Admin chat tool: feedback submission counts by status." use Jido.Action, name: "get_feedback_stats", description: "Get feedback submission counts grouped by status (open, in_progress, resolved). " <> "Optionally filter by number of days to look back.", schema: [ days: [ type: {:or, [:pos_integer, {:in, [nil]}]}, default: nil, doc: "Look back this many days. Omit to return all-time counts." ] ] import Ecto.Query alias MyApp.Feedback.Submission alias MyApp.Repo @impl true def run(%{days: days}, _context) do base = if days do since = DateTime.add(DateTime.utc_now(), -days, :day) from(s in Submission, where: s.inserted_at >= ^since) else Submission end counts = base |> group_by([s], s.status) |> select([s], {s.status, count(s.id)}) |> Repo.all() |> Map.new() {:ok, %{period_days: days, counts: counts}} end end ``` Append it to `@actions` in `PetalPro.AI.AdminChat.ActionRegistry`: ```elixir @actions [ # ... existing actions ... MyApp.AI.AdminChat.Actions.GetFeedbackStats ] ``` The tool immediately appears in both the admin chat UI and the MCP server — one registration covers both interfaces. Add a test under `test/petal_pro/ai/admin_chat/actions/` calling `run/2` directly. ### Removing a Tool Delete the module from `@actions` in `ActionRegistry`. The tool disappears from `tools/list` and `tools/call` at the next compile. You can delete the module file (and its test) too if you don't need it. ### Security Considerations - **The token is the only auth mechanism.** Treat `MCP_ADMIN_TOKEN` like a root password — use a long random string in production and rotate it if compromised. - **Tools run with full database access.** Every tool executes in your app process with your Repo. Don't add tools that expose raw SQL execution or unfiltered bulk data. - **Destructive actions are logged.** `manage_user` and `manage_org` both call `Logs.log_async/2` so you have an audit trail. - **Don't commit `.mcp.json`.** Stock Petal Pro doesn't gitignore it, so add `.mcp.json` to your `.gitignore`. If you ever accidentally commit it with a production token, rotate the token immediately. - **Consider network restrictions for production.** If your MCP client only needs to reach production from your own IP, add a firewall rule or Fly.io private networking rather than exposing the endpoint publicly. ## Claude Code Integration Petal Pro v4 ships with first-class Claude Code support. Sub-agents, skills, recipes, and scoped CLAUDE.md files are all pre-configured — you get an AI-aware codebase out of the box. ### Sub-Agents Sub-agents are specialized Claude Code agents that automatically activate based on context. They live in `.claude/agents/` and are invoked by Claude Code when relevant. | Agent | Description | |-------|-------------| | `schema-architect` | Designs database schemas following Petal Pro conventions (UUID v7 PKs, proper indexes, on_delete strategies) | | `test-runner` | Runs tests, interprets failures, and suggests fixes | | `elixir-reviewer` | Reviews Elixir code for correctness, conventions, and common pitfalls | | `heex-reviewer` | Reviews HEEx templates for proper interpolation, component usage, and accessibility | | `ui-ux-reviewer` | Reviews UI/UX for design quality, usability, and consistency with the app's design system | You don't invoke these directly — Claude Code activates the appropriate agent automatically. ### Skills Skills are slash commands for scaffolding new code. They enforce project conventions so generated code is consistent with the rest of the codebase. Run them from Claude Code with an optional argument describing what you want. #### Scaffolding | Command | Description | |---------|-------------| | `/new-liveview` | Scaffolds a new LiveView page — layout wrapping, imports, assign patterns, handle_params/handle_event structure | | `/new-context` | Scaffolds a new Phoenix context module — CRUD patterns, filters, error handling, logging | | `/new-email` | Creates a new transactional email template with inline styling and the deliver/render pipeline | | `/new-oban-worker` | Scaffolds an Oban background worker — queue config, retry strategy, logging, error handling | | `/schema-migration` | Guides schema and migration changes — UUID v7 PKs, indexes, Ecto schema patterns | #### Feature Addition | Command | Description | |---------|-------------| | `/add-org-feature` | Scaffolds a new org-scoped resource end-to-end: schema with org_id, context, migration, LiveView pages, routes, GDPR updates | | `/add-notification` | Adds a new notification type end-to-end: schema, context function, email template, component renderer | | `/add-admin-page` | Scaffolds an admin section page with DataTable, Flop pagination, sorting, and filtering | | `/add-api-endpoint` | Adds a new REST API endpoint with OpenAPI specs, bearer auth, JSON views, and tests | | `/add-billing-feature` | Guides through billing additions: new plans, subscription gates, webhook handlers, Stripe calls | | `/add-route` | Safely adds routes to the router — enforces live_session grouping, pipeline selection, scope conventions | #### Utilities | Command | Description | |---------|-------------| | `/ci` | Simulates the full GitHub Actions CI pipeline locally and fixes failures | | `/gdpr-compliance` | Ensures new user-associated schemas are included in data export and deletion workflows | | `/liveview-js` | Guides use of `Phoenix.LiveView.JS` for client-side UI state (show/hide, toggles, tabs) instead of server round-trips | ### Recipes Recipes are slash commands for larger-scale customizations — removing features, switching architecture, adding integrations. See the [Recipes](/petal-pro/recipes) page for the full list. ### CLAUDE.md Files The project ships with scoped `CLAUDE.md` files at multiple levels. Claude Code reads these automatically when working in each directory, giving it the right context without you having to explain it every time. | File | Scope | |------|-------| | `CLAUDE.md` (root) | Project overview, feature table, dev scripts, architectural patterns, config keys | | `lib/CLAUDE.md` | Elixir conventions, Ecto guidelines, Mix guidelines | | `lib/petal_pro/CLAUDE.md` | Business logic patterns, multi-tenancy, auth, billing, background jobs | | `lib/petal_pro_web/CLAUDE.md` | Web layer conventions, LiveView patterns, layout system | | `assets/CLAUDE.md` | JS/CSS conventions, Tailwind v4 setup, Alpine.js patterns | | `test/CLAUDE.md` | Testing conventions, Mimic mocking, factory patterns | ### How to Use #### Installation ```shell npm install -g @anthropic-ai/claude-code ``` #### Starting a session ```shell cd your-petal-pro-project claude ``` Claude Code picks up all the CLAUDE.md context files automatically. #### Running a skill Type the slash command with an optional description of what you want: ``` /new-liveview A settings page for managing notification preferences ``` ``` /add-org-feature Projects — users can create and manage projects within their org ``` #### Running a recipe ``` /recipes:remove-billing ``` #### Using sub-agents Sub-agents activate automatically — when you ask Claude Code to review a template it will invoke `heex-reviewer`, when you ask it to design a schema it will use `schema-architect`. You don't need to call them explicitly. #### Asking Claude Code to work on a task The workflow commands handle the full development cycle: ``` /task:plan Add a feedback widget to the dashboard ``` This interviews you, then writes a structured task file to `.claude/tasks/`. Then: ``` /task:do ``` This implements it. Run the `/ci` skill to check it passes CI locally, then: ``` /git:commit ``` This formats the code and commits it in logical chunks. Push when you're happy. --- # Admin MCP Server # Source: https://petal.build/petal-pro/fundamentals/admin-mcp-server # Admin MCP Server Petal Pro ships with a built-in [Model Context Protocol](https://modelcontextprotocol.io/specification/2025-03-26) (MCP) server that exposes your app's admin tools to external AI clients such as Claude Code and Claude Desktop. Instead of logging into an admin panel to look up a user or check billing stats, you can ask your AI assistant directly — it talks to your running app over JSON-RPC 2.0, executes the relevant tool, and hands you back real data. This is especially useful during development and operations: you can interrogate production (carefully) or a staging environment without leaving your editor. ## The Endpoint All MCP traffic goes through a single HTTP endpoint: ``` POST /api/mcp Authorization: Bearer Content-Type: application/json ``` The server speaks [JSON-RPC 2.0](https://www.jsonrpc.org/specification) and accepts both single messages and batched arrays. Supported methods: | Method | Description | |---|---| | `initialize` | Protocol handshake — returns server name, version, and capabilities | | `tools/list` | Returns all registered tools with their input schemas | | `tools/call` | Executes a named tool with arguments | | `ping` | Health check | Quick sanity check with curl: ```shell curl -X POST http://localhost:4000/api/mcp \ -H "Authorization: Bearer dev-mcp-token" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' ``` ## Setup ### The Token The server authenticates via a static bearer token read from the `MCP_ADMIN_TOKEN` environment variable. In dev, a default of `"dev-mcp-token"` is used so you can get started immediately. Set a real secret for staging and production: ```shell # runtime.exs already reads this — just set the env var export MCP_ADMIN_TOKEN="your-long-random-secret" ``` On Fly.io: ```shell fly secrets set MCP_ADMIN_TOKEN="your-long-random-secret" ``` The token is compared with `Plug.Crypto.secure_compare/2` to avoid timing attacks. ### The Route The route is already wired in the router. You don't need to add anything. For reference, the controller that handles requests is `PetalProWeb.McpController`. ## Connecting Claude Code Create a `.mcp.json` file at the root of your project. It isn't gitignored out of the box, so add `.mcp.json` to your `.gitignore` before you put a real token in it: ```json { "mcpServers": { "petal-pro-dev": { "type": "http", "url": "http://localhost:4000/api/mcp", "headers": { "Authorization": "Bearer dev-mcp-token" } }, "petal-pro-prod": { "type": "http", "url": "https://yourapp.fly.dev/api/mcp", "headers": { "Authorization": "Bearer your-long-random-secret" } } } } ``` After saving, run `claude mcp list` or restart Claude Code — the `petal-pro-dev` server should appear. You can now ask things like "list the 5 most recent users" or "suspend user with id abc-123" directly in the chat. ## Connecting Claude Desktop Add the server to your Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS): ```json { "mcpServers": { "petal-pro": { "type": "http", "url": "https://yourapp.fly.dev/api/mcp", "headers": { "Authorization": "Bearer your-long-random-secret" } } } } ``` Restart Claude Desktop and the tools will appear in the tools panel. ## Built-in Tools The following tools ship with Petal Pro. They're all native `Jido.Action` modules under `lib/petal_pro/ai/admin_chat/actions/` and registered in `PetalPro.AI.AdminChat.ActionRegistry`. ### `get_site_stats` Returns platform metrics — total users, total orgs, and new signups/orgs for a given period (`today`, `week`, `month`, `all`). Useful for a quick health check. ### `list_recent_users` Lists recently registered users with basic profile info. ### `search_users` Text search across user accounts with optional status filters. ### `manage_user` Performs account management actions on a single user identified by UUID. Available actions: | Action | Effect | |---|---| | `suspend` | Prevents login | | `unsuspend` | Re-enables login | | `delete` | Soft-deletes the account | | `undelete` | Reverses soft-delete | | `make_admin` | Grants admin role | | `remove_admin` | Revokes admin role | All actions are audit-logged via `Logs.log_async/2`. ### `list_orgs` Lists organizations with member counts. Accepts an optional search term and result limit. ### `manage_org` Manages an organization by slug or UUID. Available actions: `rename` (requires `new_name`), `delete`, `list_members`. ### `get_ai_call_stats` Returns AI usage and cost statistics for a configurable lookback period (default 30 days, max 365). Includes total calls, token counts, costs in both cents and dollars, and breakdowns by model and operation. ### `list_changelog_updates`, `create_changelog_update`, `manage_changelog` Tools for reading and managing your app's changelog entries from the AI client. ## Adding a Custom Tool Tools are native `Jido.Action` modules. Define one under `lib/petal_pro/ai/admin_chat/actions/`: ```elixir defmodule MyApp.AI.AdminChat.Actions.GetRevenueStats do @moduledoc "Fetch monthly revenue figures." use Jido.Action, name: "get_revenue_stats", description: "Get monthly recurring revenue and new subscription counts. " <> "Specify a number of months to look back (default 3).", schema: [ months: [ type: :pos_integer, default: 3, doc: "Months to look back (default 3)." ] ] alias MyApp.Billing @impl true def run(%{months: months}, _context) do {:ok, Billing.monthly_revenue_stats(months)} end end ``` The `schema` is a [NimbleOptions](https://hexdocs.pm/nimble_options) keyword list — Jido validates incoming arguments against it and emits a JSON Schema for the LLM. Use `:in` constraints (`type: {:in, ["a", "b"]}`) to surface enum choices to clients. Then append it to `@actions` in `PetalPro.AI.AdminChat.ActionRegistry`: ```elixir @actions [ # ... existing actions ... MyApp.AI.AdminChat.Actions.GetRevenueStats ] ``` That's it. The tool immediately appears in `tools/list` responses and can be called via `tools/call`. Both the admin chat UI and the MCP server read from the same registry, so one registration covers both interfaces. Add a test under `test/petal_pro/ai/admin_chat/actions/` — call your action's `run/2` directly to assert behaviour, and let Jido handle schema validation. ## Security Considerations - **The token is the only auth mechanism.** Treat `MCP_ADMIN_TOKEN` like a root password — use a long random string in production and rotate it if compromised. - **Tools run with full database access.** Every tool executes in your app process with your Repo. Don't add tools that expose raw SQL execution or unfiltered bulk data. - **Destructive actions are logged.** `manage_user` and `manage_org` both call `Logs.log_async/2` so you have an audit trail. - **Don't commit `.mcp.json`.** Stock Petal Pro doesn't gitignore it, so add `.mcp.json` to your `.gitignore`. If you ever accidentally commit it with a production token, rotate the token immediately. - **Consider network restrictions for production.** If your MCP client only needs to reach production from your own IP, add a firewall rule or Fly.io private networking rather than exposing the endpoint publicly. --- # Claude Code Integration # Source: https://petal.build/petal-pro/fundamentals/claude-code-integration # Claude Code Integration Petal Pro v4 ships with built-in Claude Code support. Sub-agents, skills, recipes, and scoped CLAUDE.md files are all pre-configured, so you get an AI-aware codebase out of the box. ## Sub-Agents Sub-agents are specialized Claude Code agents that automatically activate based on context. They live in `.claude/agents/` and are invoked by Claude Code when relevant. | Agent | Description | |-------|-------------| | `schema-architect` | Designs database schemas following Petal Pro conventions (UUID v7 PKs, proper indexes, on_delete strategies) | | `test-runner` | Runs tests, interprets failures, and suggests fixes | | `elixir-reviewer` | Reviews Elixir code for correctness, conventions, and common pitfalls | | `heex-reviewer` | Reviews HEEx templates for proper interpolation, component usage, and accessibility | | `ui-ux-reviewer` | Reviews UI/UX for design quality, usability, and consistency with the app's design system | You don't invoke these directly — Claude Code activates the appropriate agent automatically. ## Skills Skills are slash commands for scaffolding new code. They enforce project conventions so generated code is consistent with the rest of the codebase. Run them from Claude Code with an optional argument describing what you want. ### Scaffolding | Command | Description | |---------|-------------| | `/new-liveview` | Scaffolds a new LiveView page — layout wrapping, imports, assign patterns, handle_params/handle_event structure | | `/new-context` | Scaffolds a new Phoenix context module — CRUD patterns, filters, error handling, logging | | `/new-email` | Creates a new transactional email template with inline styling and the deliver/render pipeline | | `/new-oban-worker` | Scaffolds an Oban background worker — queue config, retry strategy, logging, error handling | | `/schema-migration` | Guides schema and migration changes — UUID v7 PKs, indexes, Ecto schema patterns | ### Feature Addition | Command | Description | |---------|-------------| | `/add-org-feature` | Scaffolds a new org-scoped resource end-to-end: schema with org_id, context, migration, LiveView pages, routes, GDPR updates | | `/add-notification` | Adds a new notification type end-to-end: schema, context function, email template, component renderer | | `/add-admin-page` | Scaffolds an admin section page with DataTable, Flop pagination, sorting, and filtering | | `/add-api-endpoint` | Adds a new REST API endpoint with OpenAPI specs, bearer auth, JSON views, and tests | | `/add-billing-feature` | Guides through billing additions: new plans, subscription gates, webhook handlers, Stripe calls | | `/add-route` | Safely adds routes to the router — enforces live_session grouping, pipeline selection, scope conventions | ### Utilities | Command | Description | |---------|-------------| | `/ci` | Simulates the full GitHub Actions CI pipeline locally and fixes failures | | `/gdpr-compliance` | Ensures new user-associated schemas are included in data export and deletion workflows | | `/liveview-js` | Guides use of `Phoenix.LiveView.JS` for client-side UI state (show/hide, toggles, tabs) instead of server round-trips | ## Recipes Recipes are slash commands for larger-scale customizations — removing features, switching architecture, adding integrations. See the [Recipes](/petal-pro/recipes) page for the full list. ## CLAUDE.md Files The project ships with scoped `CLAUDE.md` files at multiple levels. Claude Code reads these automatically when working in each directory, giving it the right context without you having to explain it every time. | File | Scope | |------|-------| | `CLAUDE.md` (root) | Project overview, feature table, dev scripts, architectural patterns, config keys | | `lib/CLAUDE.md` | Elixir conventions, Ecto guidelines, Mix guidelines | | `lib/petal_pro/CLAUDE.md` | Business logic patterns, multi-tenancy, auth, billing, background jobs | | `lib/petal_pro_web/CLAUDE.md` | Web layer conventions, LiveView patterns, layout system | | `assets/CLAUDE.md` | JS/CSS conventions, Tailwind v4 setup, Alpine.js patterns | | `test/CLAUDE.md` | Testing conventions, Mimic mocking, factory patterns | ## How to Use ### Installation ```shell npm install -g @anthropic-ai/claude-code ``` ### Starting a session ```shell cd your-petal-pro-project claude ``` Claude Code picks up all the CLAUDE.md context files automatically. ### Running a skill Type the slash command with an optional description of what you want: ``` /new-liveview A settings page for managing notification preferences ``` ``` /add-org-feature Projects — users can create and manage projects within their org ``` ### Running a recipe ``` /recipes:remove-billing ``` ### Using sub-agents Sub-agents activate automatically — when you ask Claude Code to review a template it will invoke `heex-reviewer`, when you ask it to design a schema it will use `schema-architect`. You don't need to call them explicitly. ### Asking Claude Code to work on a task The workflow commands handle the full development cycle: ``` /task:plan Add a feedback widget to the dashboard ``` This interviews you about the feature and generates a structured task file in `.claude/tasks/`. Then: ``` /task:do feedback_widget ``` This implements it step by step, with the sub-agents reviewing as it goes. Then: ``` /ci ``` This runs the full CI pipeline locally (format, compile warnings, tests, credo, sobelow) and fixes what fails. When it is green: ``` /git:commit ``` This runs `mix format` and commits in logical chunks with conventional messages. --- # Feedback & Analytics # Source: https://petal.build/petal-pro/fundamentals/feedback-system # Feedback & Analytics Petal Pro includes an in-app feedback system and a lightweight server-side page analytics system. Together they give you qualitative user input and quantitative usage data — all without external services. ## Feedback System Users submit feedback via a floating widget (available on any LiveView) or the dedicated feedback page at `/app/feedback`. Submissions are stored in the `feedbacks` table via `PetalPro.Feedback.FeedbackItem`. Admins review submissions at `/admin/feedback`. Both authenticated and anonymous submissions are supported. ### Schema `PetalPro.Feedback.FeedbackItem` has these fields: | Field | Type | Notes | |-------|------|-------| | `message` | string | Required. The feedback text. | | `category` | string | One of `general`, `bug`, `feature`, `question`. Defaults to `general`. | | `page_url` | string | The URL the user was on when they submitted. Optional. | | `user_id` | uuid | Nullable. Nil for anonymous submissions. | ### Context module `PetalPro.Feedback` is the public interface: ```elixir # Create feedback for an authenticated user Feedback.create_feedback(%{"message" => "Love it", "category" => "general"}, user) # Create anonymous feedback (no user association) Feedback.create_feedback_anonymous(%{"message" => "Found a bug", "category" => "bug"}) # Fetch for admin review Feedback.list_feedbacks() Feedback.get_feedback!(id) Feedback.delete_feedback(feedback_item) ``` ### Adding the feedback widget `PetalProWeb.FeedbackComponent` renders a floating button (bottom-right corner) that toggles a slide-up panel with the feedback form. Add it to any LiveView template: ```heex ``` The widget works for both authenticated and anonymous users — pass `current_user={nil}` for public pages. After a successful submission the LiveComponent sends `{:feedback_submitted, feedback}` to the parent LiveView. Handle it if you want to show a flash: ```elixir def handle_info({:feedback_submitted, _feedback}, socket) do {:noreply, put_flash(socket, :info, "Thanks for your feedback!")} end ``` #### Dedicated feedback page There is also a standalone page at `/app/feedback` rendered by `PetalProWeb.FeedbackLive`. Users reach it via the sidebar menu. It uses the same `FeedbackFormComponent` as the widget, so behaviour is identical. ### Admin dashboard `PetalProWeb.AdminFeedbackLive` lives at `/admin/feedback`. It uses the `DataTable` component (Flop-backed) with: - **Sortable columns**: category, submitted date - **Filterable columns**: category (exact match) - **Full-text search**: across `message` and `category` - **Per-row delete**: confirmation dialog before removal - **User link**: authenticated submissions link to the user's admin profile; anonymous submissions show "Anonymous" Categories are color-coded: bug → red, feature → blue, question → yellow, general → gray. ### Extending the feedback system #### Adding custom categories The allowed categories are validated in `FeedbackItem.changeset/2`: ```elixir |> validate_inclusion(:category, ~w(general bug feature question)) ``` Add your category to the validation list and update the options in `FeedbackFormComponent` and `category_color/1` in `AdminFeedbackLive`: ```elixir # In FeedbackFormComponent render/1 options={[ {"General", "general"}, {"Bug Report", "bug"}, {"Feature Request", "feature"}, {"Question", "question"}, {"Praise", "praise"} # new ]} # In AdminFeedbackLive defp category_color("praise"), do: "success" ``` #### Webhook notifications on new feedback The `Feedback.create_feedback/2` and `create_feedback_anonymous/1` functions return `{:ok, feedback_item}` on success. Wrap the call site in `FeedbackFormComponent` to trigger a side effect, or add an Oban worker that fires after insert: ```elixir # In FeedbackFormComponent handle_event "submit" case Feedback.create_feedback(feedback_params, current_user) do {:ok, feedback} -> # Fire and forget Task.start(fn -> MyApp.Workers.FeedbackWebhookWorker.enqueue(feedback.id) end) {:noreply, assign(socket, submitted: true)} {:error, changeset} -> {:noreply, assign(socket, form: to_form(changeset))} end ``` The worker can then POST the payload to a Slack webhook, Discord, or any HTTP endpoint using `Req`. ## Page Analytics Petal Pro ships with a lightweight, server-side page view tracking system. It records view counts per page per day using atomic Postgres upserts — no external service, no JavaScript, no cookies, no PII. ### What it tracks - **Page name** — a string you define when instrumenting a LiveView (e.g. `"dashboard"`, `"pricing"`) - **Date** — UTC date of the view - **View count** — atomically incremented integer per page per day ### What it does not track - Individual users or sessions - IP addresses or user agents (used only for bot filtering, never stored) - Referrers, UTMs, or any request metadata - Clicks, scroll depth, or client-side events This makes it safe to use without cookie consent banners. It complements — not replaces — external analytics tools like Fathom or PostHog. ### How daily aggregation works The schema is `PetalPro.Analytics.DailyPageStat` backed by the `daily_page_stats` table: ```elixir typed_schema "daily_page_stats" do field :page_name, :string field :date, :date field :view_count, :integer, default: 0 timestamps(type: :utc_datetime) end ``` There is a unique constraint on `[:page_name, :date]`. Every call to `record_page_view/1` does a Postgres `ON CONFLICT` upsert that increments the counter atomically — safe to call concurrently from many LiveView processes: ```elixir Repo.insert( %DailyPageStat{page_name: page_name, date: today, view_count: 1}, on_conflict: [inc: [view_count: 1], set: [updated_at: now]], conflict_target: [:page_name, :date] ) ``` One row per page per day. No cleanup job needed. ### Instrumenting a page Use `PetalProWeb.PageViewHelper.track_page_view/2` in your LiveView `mount/3`: ```elixir defmodule MyAppWeb.DashboardLive do use MyAppWeb, :live_view alias PetalProWeb.PageViewHelper @impl true def mount(_params, _session, socket) do PageViewHelper.track_page_view(socket, "dashboard") {:ok, socket} end end ``` `track_page_view/2` only records a view when: 1. The socket is **connected** (not the initial static render) — prevents double-counting on first load 2. The user agent is **not a bot** — checked against a built-in list of ~30 known bot/crawler patterns including Googlebot, GPTBot, ClaudeBot, curl, and uptime monitors The actual DB write runs in a `Task.start/1` so it never blocks the LiveView response. #### Tracking a custom event You can use `PetalPro.Analytics.record_page_view/1` directly to track anything, not just page loads: ```elixir PetalPro.Analytics.record_page_view("checkout_started") PetalPro.Analytics.record_page_view("pricing_page") ``` The `page_name` is just a string — pick a naming convention and stick to it. ### Querying analytics data `PetalPro.Analytics` exposes three query functions: ```elixir # Top pages by views for a date range (default limit: 20) Analytics.top_pages(~D[2025-01-01], ~D[2025-01-31]) # => [%{page_name: "dashboard", total_views: 4201}, ...] # Daily breakdown for a specific page Analytics.page_views_by_day("dashboard", ~D[2025-01-01], ~D[2025-01-31]) # => [%{date: ~D[2025-01-01], views: 142}, ...] # Total views across all pages Analytics.total_views(~D[2025-01-01], ~D[2025-01-31]) # => 18_432 ``` ### Viewing analytics in the admin There's no admin screen for page analytics yet, so query the data with the functions above. `PetalPro.Workers.DailySlackDigestWorker` also includes the day's top 5 pages (via `top_pages/3`) in its Slack digest. Add it to your Oban cron to switch it on, e.g. `{"0 13 * * *", PetalPro.Workers.DailySlackDigestWorker}`. ### Configuration No configuration is required. The system is always active. If you don't call `track_page_view/2` on a LiveView, that LiveView simply isn't tracked. To disable tracking on a specific page, just don't call the helper — or add a conditional: ```elixir def mount(_params, _session, socket) do unless Application.get_env(:my_app, :disable_analytics) do PageViewHelper.track_page_view(socket, "dashboard") end {:ok, socket} end ``` ### Difference from Fathom / external analytics | | Internal page analytics | Fathom (or similar) | |---|---|---| | Where it runs | Server-side Elixir | Client-side JavaScript | | What it tracks | Named events you instrument | All pageloads automatically | | PII stored | None | IP anonymized, device info | | Bot filtering | Yes (server UA check) | Yes (client-side) | | Real-time | No (daily buckets) | Yes | | Bounce rate / session data | No | Yes | | Cost | Free (your DB) | Paid subscription | Use internal analytics for product-specific instrumentation (e.g. "how many users hit the upgrade screen") and Fathom for traffic/SEO/marketing metrics. --- # Changelog System # Source: https://petal.build/petal-pro/fundamentals/changelog-system # Changelog System The changelog system gives your app a public-facing update feed. Users can browse releases, like entries, and track what they've read. Admins manage entries through the admin DataTable UI or directly via Claude Code using the built-in MCP tools. > **v4 note**: The context was renamed from `ChangelogUpdates` (v3) to `PetalPro.Changelog` in v4. The primary schema is now `PetalPro.Changelog.Update`. ## What's included - Public changelog page at `/changelog` (also accessible from the sidebar) - Per-entry slug URLs (`/changelog/:slug`) with SEO meta descriptions - Like/unlike on individual entries (authenticated users) - Read tracking — the sidebar notification bell shows unread count - Optional site-wide **banner** that can be attached to any published entry - Notification and email dispatch on publish (opt-in per entry) - Admin DataTable at `/admin/changelog` with full Flop pagination, sorting, and filtering - MCP tools for managing entries via Claude Code ## Schemas ### `PetalPro.Changelog.Update` The primary content record: | Field | Type | Notes | |-------|------|-------| | `title` | string | Required. Auto-generates `slug`. | | `slug` | string | URL-safe, unique, auto-derived from title. | | `summary` | string | Short teaser shown in lists and meta descriptions. | | `content` | string | Full content as EditorJS JSON. | | `status` | enum | `:draft`, `:published`, `:archived` | | `category` | enum | `:new`, `:improve`, `:fix` | | `published_at` | utc_datetime | Set automatically on publish. | | `show_banner` | boolean | Promotes this entry to the site-wide banner. | | `banner_style` | enum | `:info`, `:success`, `:warning`, `:error` | | `banner_cta_text` | string | Button label for the banner. | | `banner_cta_url` | string | Button destination for the banner. | | `banner_expires_at` | utc_datetime | Auto-hides banner after this time. | | `send_notification` | boolean | Send in-app notification to all users on publish. | | `send_email` | boolean | Send email to all users on publish. | ### `PetalPro.Changelog.Like` Tracks which users liked which updates. Unique constraint on `[:changelog_update_id, :user_id]`. ### `PetalPro.Changelog.Read` Tracks whether a user has read an update and how (`read_via`: `:changelog_page` or `:banner`). Used to power the unread count in the notification bell. ## Context module `PetalPro.Changelog` is the public interface. Key functions: ```elixir # Admin: list all updates (optional status filter) Changelog.list_changelog_updates() Changelog.list_changelog_updates(%{status: :draft}) # Public: list published updates with like counts and user like status Changelog.list_public_changelog_updates(%{}, current_user) # Fetch by slug (raises if not found or not published) Changelog.get_published_changelog_update_by_slug!("my-update-slug") # CRUD Changelog.create_changelog_update(attrs) Changelog.update_changelog_update(update, attrs) Changelog.publish_changelog_update(update, published_by_user) Changelog.unpublish_changelog_update(update) Changelog.archive_changelog_update(update) Changelog.delete_changelog_update(update) # Read tracking Changelog.mark_as_read(update, user, :changelog_page) Changelog.get_unread_count(user) # Likes Changelog.toggle_like(update, user) Changelog.get_like_count(update) # Banner Changelog.get_active_banner() ``` Publishing dispatches an Oban job (`ChangelogNotificationWorker`) if `send_notification` or `send_email` is set on the entry. Only one banner can be active at a time — publishing a second banner-enabled entry returns a validation error. ## Admin DataTable `PetalProWeb.AdminChangelogLive` at `/admin/changelog` uses the `DataTable` component backed by Flop. Features: - Sort by title, category, status, published date - Filter by status - Inline publish/unpublish/archive/delete actions - Per-entry read count and like count stats - Link to the public entry ## Public page and SEO The public changelog lives at `/changelog`. Individual entries are at `/changelog/:slug`. The `summary` field populates the `` tag for each entry page, so write it like you mean it — search engines and unfurl previews both use it. ## MCP tools (Claude Code integration) Petal Pro exposes three changelog tools via its admin MCP server at `POST /api/mcp`. These are available to Claude Code and Claude Desktop when connected with a bearer token. ### `list_changelog_updates` Lists updates with optional status filter and limit. ``` list_changelog_updates(status: "draft", limit: 10) ``` Returns: `id`, `title`, `slug`, `status`, `category`, `show_banner`, `published_at`, `author`. ### `manage_changelog` Performs a single action on an existing update identified by slug or UUID. ``` manage_changelog(identifier: "my-update-slug", action: "get") manage_changelog(identifier: "my-update-slug", action: "publish", publisher_email: "admin@example.com") manage_changelog(identifier: "my-update-slug", action: "unpublish") manage_changelog(identifier: "my-update-slug", action: "archive") manage_changelog(identifier: "my-update-slug", action: "delete") manage_changelog(identifier: "my-update-slug", action: "update", title: "New title", category: "fix") ``` The `get` action returns full details including read count, read percentage, and like count. The `publish` action requires `publisher_email` — it must belong to an admin user. ### `create_changelog_update` Creates a new entry in `:draft` status. ``` create_changelog_update( title: "Better dark mode", content: "{\"blocks\":[{\"type\":\"paragraph\",\"data\":{\"text\":\"We overhauled dark mode...\"}}]}", category: "improve", summary: "Dark mode now respects system preference on first visit.", send_notification: true ) ``` Content must be an EditorJS JSON string. `category` defaults to `"new"`. `author_email` defaults to the first admin user if omitted. ### Creating a changelog entry from Claude Code ``` > Use the create_changelog_update tool to draft a changelog entry titled "Faster search" in the "improve" category. Summary: "Search results now load 3x faster." Then publish it using my email: matt@example.com ``` Claude will call `create_changelog_update` to draft the entry, then `manage_changelog` with `action: "publish"` to go live. The whole flow takes seconds without touching the admin UI. --- # Deployment # Source: https://petal.build/petal-pro/fundamentals/deployment # Deployment How to get your app running in production ## Before deploy Before deployment, we've found an issue in production with the new content security policy headers. Basically, you need to add `wss://...` and your domain to the `:content_security_policy` `default_src` array, like below.
config.exs
```css config :my_app, :content_security_policy, %{ default_src: [ .... "wss://yourdomain.com", "wss://yourdomain.com/live/websocket" ] } ``` Read more: - [Petal Pro Github issue](https://github.com/petalframework/petal_pro/issues/46) - [Blog post about content security policy in Phoenix apps](https://furlough.merecomplexities.com/elixir/phoenix/security/2021/02/26/content-security-policy-configuration-in-phoenix.html) ### Removing CSP If you don't care about content security policies, you can remove this config and then in `router.exs` change: ```elixir # Change this: plug(:put_secure_browser_headers, %{ "content-security-policy" => ContentSecurityPolicy.serialize( struct(ContentSecurityPolicy.Policy, PetalPro.config(:content_security_policy)) ) }) # To this: plug :put_secure_browser_headers ``` ### Faker dependency and the Landing Page The landing page and seeders use [Faker](https://hexdocs.pm/faker), so `mix.exs` already pulls it in for every environment (`{:faker, "~> 0.17"}`). Nothing to change for prod. Once you've replaced the landing page you can scope it back to `only: [:test, :dev]` if nothing else in prod uses it. ## A word on environment variables In production, Petal Pro requires the following environment variables to be set: - `SECRET_KEY_BASE` - `DATABASE_URL` - `PHX_HOST` - `PORT` - `RESEND_API_KEY` — transactional email via Resend Optional but recommended: - `SENTRY_DSN` — error tracking auto-activates when set - `MCP_ADMIN_TOKEN` — bearer token for the admin MCP API If you're deploying to Fly.io, the core variables should be automatically taken care of. However, if you're testing `prod` on your dev machine or using a different deployment mechanism, you'll need to set these yourself. `SECRET_KEY_BASE` and `DATABASE_URL` are secrets and need to be protected. Follow best practices for managing secrets on the platform you are deploying to. ## Docker Petal Pro v4 ships a production-ready `Dockerfile` in the repo root. It uses a multi-stage build: a builder stage compiles the Elixir release (including npm asset pipeline), and a lean Debian runner stage contains only the compiled release. ### Build the image ```shell docker build -t myapp . ``` ### Run locally ```shell docker run -p 4000:4000 \ -e SECRET_KEY_BASE="your_secret_key_base" \ -e DATABASE_URL="ecto://user:pass@host/db" \ -e PHX_HOST="localhost" \ -e PORT="4000" \ -e RESEND_API_KEY="re_..." \ myapp ``` ### Key runtime environment variables | Variable | Required | Notes | |---|---|---| | `SECRET_KEY_BASE` | Yes | Generate with `mix phx.gen.secret` | | `DATABASE_URL` | Yes | PostgreSQL connection string | | `PHX_HOST` | Yes | Your domain (no `https://`) | | `PORT` | Yes | Usually `4000` | | `RESEND_API_KEY` | Yes | Transactional email | | `SENTRY_DSN` | No | Error tracking | | `MCP_ADMIN_TOKEN` | No | Admin AI tool access | | `CLIENT_IP_HEADER` | No | Unset by default. A header your proxy overwrites on every request: `fly-client-ip` on Fly, `cf-connecting-ip` behind Cloudflare | | `TRUSTED_PROXY_HOPS` | No | Defaults to `0`. How many trailing `x-forwarded-for` entries your proxies append (`1` behind a single nginx or Caddy). Must be a whole number, or the release fails to boot | | `FORCE_SSL` | No | On in prod when unset, `true` or `1`. Any other value turns off the https redirect, HSTS and `Secure` cookies | The last three arrived in 4.5.0. Behind a proxy, set `CLIENT_IP_HEADER` or `TRUSTED_PROXY_HOPS`, or every sign-in records the proxy's address, and since 4.5.2 browser and passkey sign-in have no limit per address (see [Limits per Address](#limits-per-address)). Step 5 of the [4.4.0 to 4.5.0 upgrade guide](/petal-pro/upgrade-guide) covers when to set each one. The Dockerfile targets Elixir 1.19.5 / OTP 27.3.4 on Debian Bookworm slim. To change versions, update the `ARG` lines at the top of the file (Pro needs Elixir 1.19 or later). ## Deployment with Fly.io To deploy to Fly.io, use the following guide: [Deploy to Fly.io](/petal-pro/guides/deploy-to-fly.io) ## Error Tracking Petal Pro uses [Sentry](https://sentry.io) for error tracking. It auto-activates when the `SENTRY_DSN` environment variable is set — no code changes required. ### How It Works Sentry is configured in `config/runtime.exs`: ```elixir if sentry_dsn = System.get_env("SENTRY_DSN") do config :sentry, dsn: sentry_dsn end ``` A Sentry logger handler is attached at application startup, which captures errors logged via Elixir's `Logger`: ```elixir :logger.add_handler(:sentry_handler, Sentry.LoggerHandler, %{ config: %{metadata: [:file, :line]} }) ``` In development, if `SENTRY_DSN` is not set, errors go to your local logs and nothing is sent to Sentry. Set the DSN in dev if you want to test the integration. ### Setup #### 1. Create a Sentry project 1. Sign up or log in at [sentry.io](https://sentry.io) 2. Create a new project — select **Elixir** as the platform 3. Copy the DSN from the project settings (looks like `https://abc123@o123456.ingest.sentry.io/789`) #### 2. Set the DSN in production **Fly.io:** ```shell fly secrets set SENTRY_DSN=https://your-dsn@sentry.io/project-id ``` **Other platforms:** Set `SENTRY_DSN` as an environment variable in your deployment configuration. That's it. Deploy and Sentry will start receiving errors. ### What Gets Captured Automatically - Unhandled exceptions in controllers and LiveViews - LiveView crash reports - Any `Logger.error/2` or `Logger.warning/2` calls - Errors from Oban workers - Anything that bubbles up through the OTP supervision tree - Request context on every event: URL, method, headers and the client address (the same one sign-ins record, so set `CLIENT_IP_HEADER` or `TRUSTED_PROXY_HOPS` behind a proxy). Since 4.5.0 this comes from `PetalProWeb.SentryContextPlug`, which masks sign-in secrets first: passwords, the TOTP code, the PIN and `sign_in_token`, passkey assertions, the OAuth `code` and `state`, and the token in confirm, reset-password and confirm-email links. If you care about what goes to Sentry, that's the plug to tune. ### Adding Custom Context #### Setting user context Call this when a user authenticates to attach their identity to all subsequent errors in that process: ```elixir Sentry.Context.set_user_context(%{ id: user.id, email: user.email, name: user.name }) ``` A good place to do this is in your auth hooks or controller plugs. #### Capturing custom messages For non-exception events you want to track: ```elixir Sentry.capture_message("Billing webhook received unexpected event type", level: :warning, extra: %{event_type: event_type, payload: payload} ) ``` #### Capturing exceptions manually ```elixir try do risky_operation() rescue e -> Sentry.capture_exception(e, stacktrace: __STACKTRACE__, extra: %{context: "my_function"}) reraise e, __STACKTRACE__ end ``` ### Verifying It Works The easiest test is to trigger an error from IEx on your production instance and confirm it appears in Sentry within a minute or two. From a Fly.io console: ```shell fly ssh console --app your-app-name /app/bin/your_app remote ``` Then in IEx: ```elixir Sentry.capture_message("Test error from IEx", level: :error) ``` Check your Sentry project — the event should appear shortly. You can also check that the DSN is loaded correctly: ```elixir Application.get_env(:sentry, :dsn) ``` If this returns `nil`, `SENTRY_DSN` isn't set in the environment. ### Environment Behavior | Environment | `SENTRY_DSN` set? | Behavior | |-------------|-------------------|----------| | Production | Yes | Errors sent to Sentry | | Production | No | Errors logged only (misconfiguration — set the DSN) | | Dev/Test | No | Errors logged locally, nothing sent to Sentry | | Dev/Test | Yes | Errors sent to Sentry (useful for testing the integration) | ## Rate Limiting Petal Pro uses [Hammer](https://github.com/ExHammer/hammer) with an ETS backend for rate limiting. It's applied to the endpoints in the table below out of the box and is straightforward to add anywhere else. ### What's Rate Limited by Default | What | Key | Limit | What starts it again | A refusal | |------|-----|-------|----------------------|-----------| | Browser password sign-in (`POST /auth/sign-in`), per account | The account (`web_sign_in_account:`). An email with no account: `web_sign_in_unknown:` | 10 per 10 minutes | A correct password counted on it, and a password reset | Back to the sign-in page with a flash | | Browser password sign-in, from a browser that has signed in to the account before | The browser's cookie (`web_sign_in_device:`) | 10 per 10 minutes, then counted on the account like any other browser | Each successful sign-in gives the browser a new nonce, so a new count | Back to the sign-in page with a flash | | Browser password sign-in, per address (only with a client address set, see below) | Client address (`web_sign_in:`) | 100 failures per 10 minutes, across every account | A successful sign-in gives back its own hit, never more | Back to the sign-in page with a flash | | API sign-in (`POST /api/sign-in`) | Client address (`api_sign_in:`) | 5 per minute | Nothing | A 429 | | API sign-in, per account | The account (`api_sign_in_account:`). An email with no account: `api_sign_in_unknown:` | 10 per 10 minutes | A successful sign-in, and a password reset | A 429 | | API registration (`POST /api/register`) | Client address (`api_register:`) | 3 per hour | Nothing | A 429 | | Passkey sign-in (`POST /auth/sign-in/passkey`, only with a client address set) | Client address (`passkey_auth:`) | 10 per minute | Nothing | Back to the sign-in page with a flash | | Two-factor code, TOTP or backup (`POST /app/users/totp`) | User (`totp:`) | 5 per 5 minutes | A correct code | A 429 and the code form | | Passwordless pin request, first send and "Resend" | The account (`passwordless_pin:`) | 3 per 10 minutes | Nothing | A message on the form | | Password reset request | The account (`password_reset:`). An email with no account: `password_reset_unknown:` | 3 per 10 minutes | Nothing | Back to the sign-in page with a flash | | Confirmation email resend, the browser form and `POST /api/send-instructions` together | The account (`confirm_instructions:`). An email with no account: `confirm_instructions_unknown:` | 3 per 10 minutes | Nothing | Browser: back to the home page with a flash. API: a 429 | | Feedback form | User (`feedback_user:`) | 10 per day | Nothing | A flash | | Admin chat | Admin user (`admin_chat:`) | 10 messages per minute | Nothing | A message in the chat | In the keys: - `` is the account the email belongs to, found through the database. See [Counted on the Account](#counted-on-the-account). - `` is only used when no account matches. It's the email trimmed and lower-cased by the database, or `sha256:` and a hash of it when that's longer than 320 bytes, so a caller can't fill the table with long keys. - `` is the client address `PetalProWeb.ClientIp` resolves, through `PetalProWeb.ClientIp.rate_limit_key/2`. An IPv4 address is used as it is. An IPv6 address is cut to its /64 (`2001:db8:1:2::/64`), the block a provider usually gives one customer, so one subscriber doesn't get a fresh count from each of its addresses. An IPv4 address written as IPv6 (IPv4-mapped or NAT64) counts as the IPv4 address it carries. `last_signed_in_ip` and the audit log still record the full address. "Client address" is the same address sign-ins record in `last_signed_in_ip`. Since 4.5.1 the address limits use it. Before that they keyed on `conn.remote_ip`, which behind a proxy is the proxy, so every visitor shared one budget. It only follows the visitor once you set `CLIENT_IP_HEADER` (`fly-client-ip` on Fly) or `TRUSTED_PROXY_HOPS`. With neither set it is still the connection peer. See [Limits per Address](#limits-per-address). Every request counts, right or wrong, and it's counted before the password, pin or code is compared, so guesses sent in parallel can't all slip past one check. A refused request counts too. A few details worth knowing: - **Browser sign-in** is new in 4.5.2, and counts inside the action rather than in a plug, because which count a request uses depends on the account and the browser. A post with no email or password, or with a list where text should be, gets "Invalid email or password" and isn't counted. - **API sign-in** checks the address limit first, then the account limit. A request with no `email` param only meets the address limit. - **Passkeys** only count the sign-in attempt. The challenge (`GET /auth/passkey/challenge`) is asked for on every sign-in page load and isn't limited, since 4.5.1. - **Passwordless pins** are limited twice. Each pin allows three guesses (counted atomically by `UserPin.check_pin/3`) and expires after 10 minutes, and a new pin, resend included, goes through the request limit above. That caps an account at nine guesses per ten-minute window, since 4.5.1. 4.5.2 closes a way round it: 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. - **Two-factor** is keyed on the user, so it needs no proxy setting. Getting to the code form takes the first sign-in step (the password, a passwordless pin or an OAuth login), so only someone who got past that can use up the five tries. It's new in 4.5.1. - **Confirmation resends** are new in 4.5.2. The browser form and the API share one count, and an email with no account, or one already confirmed, spends it the same way. The first email, sent at registration, isn't counted. What a refusal looks like: - **Browser password sign-in:** a redirect back to the sign-in page with "Too many attempts. Please try again later." The answer is the same for an email with no account, so a refusal doesn't show which emails have accounts. - **API sign-in, registration and Send Instructions:** a 429 with `{"errors": {"detail": "Too many requests"}}`. - **Passkey sign-in:** a redirect back to the sign-in page with a "Too many attempts. Please try again later." flash. In 4.5.0 and earlier this was a 500. - **Two-factor:** a 429 that renders the code form with "Too many attempts. Please try again later." - **Passwordless pin request:** the form shows "Too many attempts. Please try again later." and no pin is sent. - **Password reset request:** a redirect to the sign-in page with a "Too many attempts. Please try again later." flash. - **Confirmation resend in the browser:** a redirect to the home page with a "Too many attempts. Please try again later." flash. The counts live in ETS on each machine, so with two machines a caller gets twice the number, and a deploy starts every count again. Windows are also fixed and line up with the clock, so a caller who straddles a window boundary can get up to twice a limit in a short burst. ### Counted on the Account Since 4.5.2, a limit that protects an account is counted on the account's id, found through the database with the same lookup the sign-in uses, never on the text that was typed. That covers browser and API sign-in, pins, password reset requests and confirmation resends. The reason: the `email` column is citext, so Postgres decides which spellings are one email, and it doesn't always agree with Elixir's `String.downcase/1`. On common database setups a few spellings that `String.downcase/1` keeps apart find the same account, and a count kept on the text gave each of them a fresh budget. In 4.5.1 that applied to the pin and API sign-in limits. The password reset limit was keyed on the text exactly as typed, so capitals alone got round it. An email that matches no account is counted on its text, folded by the database (`SELECT lower($1::text)`) the same way the column compares it. Every request does that fold, known email or not, so a refusal looks the same and takes the same work for both. Your own limits should follow the same rule, see [Adding Rate Limiting to a Controller](#adding-rate-limiting-to-a-controller). ### Trusted Browsers A count on an account could be turned against its owner: anyone who knows an email could keep the count full. So when a password sign-in works, the browser gets a cookie, `_petal_pro_web_sign_in_device` (encrypted, HttpOnly, SameSite=Lax, one year, `Secure` over https). A browser that holds it for an account is counted on its own first, with ten tries per ten minutes, and once those are used up it's counted like any other browser. So a stranger who uses up the account's count can only block browsers that have never signed in to it, and someone who mistypes on their own laptop is never worse off than in a private window. - The cookie only picks which count a request uses. It grants nothing else. - It remembers up to five accounts, newest first, so a shared computer works for a few people. - Each successful sign-in writes a new entry for the account, with a count of its own. - An entry stops counting as soon as the account's password changes, so a password change or reset ends the trust of every browser at once. - Only the password form sets it. People who sign in with OAuth, a passkey or a pin don't get one, and don't need one, because those doors don't use the password count. - Rotating `secret_key_base` makes every cookie unreadable. Nothing breaks: browsers are counted like new ones until their next sign-in. List it in your cookie policy as a security cookie. A password reset also starts the account's browser and API sign-in counts again, so someone who has just proved they own the email isn't refused. ### Limits per Address Four limits count per address. Two of them, browser password 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. The API sign-in and API registration limits apply either way, see below. That means `CLIENT_IP_HEADER` or `TRUSTED_PROXY_HOPS` is set, and the request's address came from it. A request whose header was missing, or that reached the app's port without going through the proxy, falls back to the peer and is left out. - **With neither setting made**, every visitor behind your proxy has the proxy's address, and one caller could use either count up for all of them, so both are off. The app logs one warning per boot when a sign-in arrives with proxy headers: `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.` A script trying one password against many accounts is then only limited per account. - **The browser sign-in count is failures only.** A sign-in that works gives back its own hit, never more, so signing in to your own account between guesses doesn't clear it, and an office behind one address isn't refused for its own sign-ins. - **Some sign-ins skip it.** A browser trusted for the account skips it while its own count lasts. So does the sign-in straight after registration, so a full address count can't strand someone who has just registered. - **The API sign-in (5 a minute) and API registration (3 an hour) limits still apply with no setting**, as one budget for your whole app, the same as in 4.5.1. - **A wrong setting is worse than none.** A hop count too low can land on one of your proxies, and the count is then shared by every visitor who isn't trusted. A hop count too high, or a header your proxy doesn't overwrite, lets a caller pick their own address. Check `last_signed_in_ip` on your own user shows your public address. ### What Isn't Limited - **Browser registration** (`/auth/register`), and the account passwordless sign-in creates for a new email. Each sends one email to the address it was given. Resends are limited; 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. Put a limit in front of those yourself if your app is a target, or use your proxy's rate limiting. ### How It Works The rate limiter is defined in `lib/petal_pro/rate_limiter.ex`: ```elixir defmodule PetalPro.RateLimiter do use Hammer, backend: :ets end ``` It starts as part of the application supervision tree. All state lives in ETS — no Redis or external dependency needed. Call `hit/3` with a key, time window (in milliseconds), and request limit: ```elixir PetalPro.RateLimiter.hit("some_key", :timer.minutes(1), 10) # => {:allow, count} | {:deny, retry_after_ms} ``` ### Adding Rate Limiting to a Controller Use a plug that calls `hit/3` and halts on denial: ```elixir defmodule MyAppWeb.MyController do use MyAppWeb, :controller plug :rate_limit when action in [:create] defp rate_limit(conn, _opts) do # "my_action:", the same address sign-ins record. It honours # CLIENT_IP_HEADER / TRUSTED_PROXY_HOPS, so behind Fly or nginx you count the visitor # and not your proxy. key = PetalProWeb.ClientIp.rate_limit_key(conn, "my_action") case PetalPro.RateLimiter.hit(key, to_timeout(minute: 1), 10) do {:allow, _count} -> conn {:deny, _retry_after} -> conn |> put_status(:too_many_requests) |> json(%{errors: %{detail: "Too many requests"}}) |> halt() end end end ``` Don't key a limit on `conn.remote_ip`. Behind a proxy that's the proxy's address, so every visitor shares one bucket. Pro's own address limits use `rate_limit_key/2` since 4.5.1. If you copied one of the 4.5.0 plugs, swap its `conn.remote_ip` line for it. #### Key naming Use a descriptive prefix with a per-user or per-IP discriminator: ```elixir # Per IP PetalProWeb.ClientIp.rate_limit_key(conn, "sign_in") # Per user "api:#{user_id}" # Per account, found by the email that was typed (good for password reset) "reset:#{user.id}" ``` A limit that protects an account goes on the account's id, never on the email as typed, even trimmed and lower-cased: the database treats some spellings as one email that `String.downcase/1` doesn't (see [Counted on the Account](#counted-on-the-account)). Look the account up first, the way the sign-in does, and for an email with no account count its text the way the database folds it, so a refusal doesn't show which emails have accounts: ```elixir user = PetalPro.Accounts.get_user_by_email(String.trim(email)) key = case user do %PetalPro.Accounts.User{id: id} -> "reset:" <> id nil -> "reset_unknown:" <> limit_email(email) end # The same helper as in Pro's forgot-password LiveView 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 ``` ### Adding Rate Limiting to a LiveView LiveViews don't have plugs, so check the limit inside the event handler: ```elixir def handle_event("submit", _params, socket) do user_id = socket.assigns.current_user.id case PetalPro.RateLimiter.hit("my_form:#{user_id}", to_timeout(minute: 1), 5) do {:allow, _count} -> # proceed {:noreply, do_the_thing(socket)} {:deny, _retry_after} -> {:noreply, put_flash(socket, :error, "You're doing that too fast. Try again in a minute.")} end end ``` ### Time Windows Use `to_timeout/1` (available in Phoenix controllers) or `:timer` functions: ```elixir to_timeout(minute: 1) # 60_000 ms to_timeout(hour: 1) # 3_600_000 ms :timer.minutes(1) # same as above, works anywhere :timer.hours(1) ``` ### Response When Rate Limited API controllers return HTTP 429 with a JSON body: ```json {"errors": {"detail": "Too many requests"}} ``` A browser controller should answer the way its other failures do. Pro's two-factor form re-renders with a 429 and an error, and browser and passkey sign-in redirect to the sign-in page with a flash. LiveViews should use `put_flash/3` to show an error message — there's no HTTP status code to set. ### Clearing a Rate Limit In dev, restart your server. ETS is in-memory and doesn't persist across restarts. That's the fastest way to clear all limits. In production a deploy or a restart does the same. If you need to clear a specific key without restarting, reset its count to zero from IEx, passing the same window the call site uses: ```elixir PetalPro.RateLimiter.set("api_sign_in:127.0.0.1", to_timeout(minute: 1), 0) ``` To let a locked-out user back in to password sign-in, clear the account's browser and API counts in a remote IEx shell (on Fly, `fly ssh console` then `/app/bin/your_app remote`). The counts are per machine, so do it on each one: ```elixir 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) ``` Or ask the user to reset their password, which does the same on the machine that serves the reset. Browser sign-in, two-factor and the API account limit also clear their own counts in code when a sign-in succeeds. ### Configuration There's no central config file for limits — each call site defines its own window and limit inline. This is intentional: different actions have different risk profiles, and collocating the limit with the code that enforces it makes it easier to reason about. To change a limit, find the `RateLimiter.hit/3` call and update the second (window) or third (max requests) argument. Browser sign-in keeps its numbers in module attributes at the top of `PetalProWeb.UserSessionController` (`@window`, `@attempt_limit` and `@address_limit`). If you change `@window`, change the window in `clear_sign_in_limit/1` in `PetalProWeb.UserResetPasswordLive` to match, and use the new one when you clear a count from IEx. Hammer files each count under its window length, so clearing with a different one clears a count nothing reads. The API account limit has its own `@account_window` in `PetalProApi.SessionController`, which the same helper clears. --- # Background Tasks & Jobs # Source: https://petal.build/petal-pro/fundamentals/background-tasks-and-jobs # Background Tasks and Jobs ## Once-off background tasks When you just want to run some code in a background task, start it under the app's task supervisor: ```elixir Task.Supervisor.start_child(PetalPro.TaskSupervisor, fn -> do_some_time_intensive_stuff() end) ``` This is useful for speeding up responses in an HTTP request or LiveView action — delegate anything that takes time to a background task (e.g. sending emails, posting to Slack, creating audit logs). Since we want to respond to a user request as soon as possible, you run these non-essential tasks in the background and it won't hold up the response. ## Background jobs with Oban A background job is something you want to run outside of a normal HTTP request/response cycle — things like sending weekly emails or processing images. We use [Oban](https://github.com/sorentwo/oban) for this. A background job is performed by a "worker". Each worker gets its own file. Petal Pro comes with an example worker you can duplicate: ```elixir defmodule PetalPro.Workers.ExampleWorker do @moduledoc """ Example of how to do async work with Oban. Run with: Oban.insert(PetalPro.Workers.ExampleWorker.new(%{})) """ use Oban.Worker, queue: :default require Logger @impl Oban.Worker def perform(%Oban.Job{} = _job) do today = Timex.now() |> Timex.to_date() Logger.info("ExampleWorker: Today is #{today}") :ok end end ``` You can run this worker by inserting a job into the database: ```elixir Oban.insert(PetalPro.Workers.ExampleWorker.new(%{})) ``` Once in the database, Oban will try running the task and retry it if it fails. You can see any failed jobs by checking the database: You can inspect job status directly in the `oban_jobs` database table. In dev mode, you can use Oban Web: ``` http://localhost:4000/admin/oban ``` Jobs that have been completed are deleted every 24 hours so your database won't swell over time. ### Cron jobs You can tell your workers to run at certain times with Oban's cron functionality. See the examples in `config.exs`: ```elixir config :petal_pro, Oban, repo: PetalPro.Repo, queues: [default: 5], plugins: [ {Oban.Plugins.Pruner, max_age: (3600 * 24)}, {Oban.Plugins.Cron, crontab: [ {"@daily", PetalPro.Workers.ExampleWorker} # {"* * * * *", PetalPro.EveryMinuteWorker}, # {"0 * * * *", PetalPro.EveryHourWorker}, # {"0 */6 * * *", PetalPro.EverySixHoursWorker}, # {"0 0 * * SUN", PetalPro.EverySundayWorker}, # More examples: https://crontab.guru/examples.html ]} ] ``` ## Daily Slack digest worker Petal Pro v4 ships `PetalPro.Workers.DailySlackDigestWorker` — an Oban cron job that sends a summary of yesterday's activity to a Slack channel. It pulls new user signups, audit log action counts, and top page views, then formats them as a single Slack message. ### Enabling the digest Add the worker to the cron schedule in `config.exs`: ```elixir {Oban.Plugins.Cron, crontab: [ {"0 13 * * *", PetalPro.Workers.DailySlackDigestWorker} # 8am ET / 1pm UTC ]} ``` ### Slack configuration The digest uses `PetalPro.Slack` to post the message. You need two environment variables: ```shell # OAuth token from your Slack app's "OAuth and Permissions" page fly secrets set SLACK_OAUTH_TOKEN="xoxb-..." # The ID of the Slack channel to post to fly secrets set SLACK_CHANNEL_ID="C0123456789" ``` To find your channel ID: run `PetalPro.Slack.read_channels()` in IEX — it returns a list of `[id, name]` pairs. If the digest is not configured (no `SLACK_CHANNEL_ID`), it silently skips sending and logs a message instead. To test locally: ```elixir PetalPro.Slack.message("Hello from Petal Pro!") ``` ## Slow query telemetry (dev only) In development, Petal Pro logs any database queries that exceed a configurable time threshold. This makes it easy to spot N+1 queries and unexpectedly slow operations without any additional tooling. The threshold is set in `config/dev.exs`: ```elixir # Log queries slower than this many milliseconds (dev only) config :petal_pro, :dev_query_threshold_ms, 100 ``` Queries that exceed the threshold are logged to the console with their duration and SQL. To tighten the threshold and catch more queries, lower the value: ```elixir config :petal_pro, :dev_query_threshold_ms, 50 ``` Set it to `0` to log every query. This config has no effect in production. --- # Seeding # Source: https://petal.build/petal-pro/fundamentals/seeding # Seeding Seeding means populating the database with records. We do this in development to show what the web app looks like with data. `priv/repo/seeds.exs` just picks a seed module (`mix setup` and `mix ecto.reset` run it):
seeds.exs
```elixir if Mix.env() == :prod do PetalPro.Seeds.Production.run() else PetalPro.Seeds.Development.run() end ``` The dev data lives in `lib/petal_pro/seeds/development.ex`. It wipes the tables, then seeds: ```elixir def run do clean() admin = UserSeeder.admin() normal_user = UserSeeder.normal_user(%{ email: "user@example.com", name: "Sarah Cunningham", password: "password", confirmed_at: DateTime.truncate(DateTime.utc_now(), :second) }) UserSeeder.fake_subscription(normal_user) org = OrgSeeder.random_org(admin) PetalPro.Orgs.create_invitation(org, %{email: normal_user.email}) UserSeeder.random_users(20) all_users = PetalPro.Accounts.list_users() FileSeeder.create_files(admin) PostSeeder.create_posts(admin) FeedbackSeeder.create_feedback(all_users) end ``` Add your own tables to `run/0`, and to `clean/0` so a re-seed starts fresh. We use the faker library for randomizing data: ```elixir def random_user_attributes(attrs \\ %{}) do Enum.into(attrs, %{ name: Faker.Person.En.first_name() <> " " <> Faker.Person.En.last_name(), email: unique_user_email() }) end ``` Seeds should be regularly updated with any new tables you create. This allows you to better test and develop your app. --- # Testing # Source: https://petal.build/petal-pro/fundamentals/testing # Testing ## Getting tests to work Run `mix test` to run the tests. Petal Pro uses [Mimic](https://hex.pm/packages/mimic) for mocking in tests (not Mox). Check existing test files for examples of how to mock external services like Stripe. --- # REST API # Source: https://petal.build/petal-pro/fundamentals/rest-api # REST API Petal Pro comes with a pre-built REST API. Though it is limited in scope, the API has been created so that it is easy to extend The REST API is a sample API that has been created for user management. For example, you could use the API with a mobile application to register a user, sign them in and update their profile. Though the API is provided as an example, it can be easily extended or updated. The key to this extensibility is the selection of technologies: - The Phoenix Framework provides [first-class support](https://hexdocs.pm/phoenix/json_and_apis.html) for creating APIs - `phx.gen.auth` is used as a basis for [API Authentication](https://hexdocs.pm/phoenix/api_authentication.html) - Open API support via [Open API Spex](https://hexdocs.pm/open_api_spex) ## Taking Advantage of the Phoenix Framework With the Phoenix Framework, you can use the following command to generate a JSON API: ```elixir mix phx.gen.json Urls Url urls link:string title:string ``` This creates a set of files that take care of the database schema, data access control, the JSON for the output and testing. All you are required to do is add the suggested route to the `/api` scope. This provides a complete/comprehensive starting point for your own work.

ℹ️ Information: The Phoenix generator will put your controller under:

/lib/petal_pro_web/controllers

This isn't a problem, but you might like to move it to where the other API controllers are:

/lib/petal_pro_api/controllers

The same is true for the test that's generated. See Directory Structure (below) for more details

## A Word on Authentication With regards to securing a HTML web page, authentication is stateful. That is, authentication involves user interaction (e.g. via a HTML form) and state is maintained via methods such as maintaining session state on the server and storing essential data in a browser cookie. API authentication, on the other hand, is usually stateless and does not involve direct interaction with the end user. Authentication is usually about authorising a client (application or server) - rather than an individual. This process is handled programmatically between systems and enough data must be sent with each call to achieve authentication. For example, a mobile app may have a client that communicates with the API server. ## The Petal Pro Sample API Token Following the recommendations in the Phoenix Framework [API Authentication](https://hexdocs.pm/phoenix/api_authentication.html) documentation, client devices/services can access the API if they provide a valid API token. However, the API has been created so each user can generate their own token. The "Register", "Send Instructions" and "Sign In" API calls do not require an API token. If you sign In successfully, an API token is supplied. Sign-in, registration and Send Instructions are rate limited. Sign-in allows 5 a minute per client address and, since 4.5.1, 10 per ten minutes per account whatever address they come from. Since 4.5.2 that count is kept on the account itself, so every spelling of one email shares it, and a successful sign-in or a password reset starts it again. An email with no account is counted the same way. Registration allows 3 an hour per client address. Since 4.5.2, Send Instructions allows 3 per ten minutes per account, one count shared with the browser's resend form. Past a limit you get a 429 with `{"errors": {"detail": "Too many requests"}}`. The client address is the one `PetalProWeb.ClientIp` resolves, so behind a proxy set `CLIENT_IP_HEADER` or `TRUSTED_PROXY_HOPS`, or every caller shares one budget. See [Rate Limiting](/petal-pro/fundamentals/deployment#rate-limiting). You can use the token from the "Sign In" call for the other API calls. API calls protected by a token are locked down to that particular user. For example, even if you're an admin user, you can't view the profile of another user. As an alternative, you could create a page in the website where users can generate their API token. You could use this mechanism to tie a client application to an account. However, this would require a change in logic for the API calls (i.e. you would need to allow this user to view/change any user). ## Support for Open API Support for Open API has been added via [Open API Spex](https://hexdocs.pm/open_api_spex). Existing API calls are decorated with meta data that provides enough information to generate an Open API spec. For example, here is a cut down version of the "Sign In" call:
session_controller.ex
```elixir operation :create, summary: "Authenticate user", description: "Authenticate user and generate bearer token", request_body: {"User credentials", "application/json", Schemas.UserCredentials}, responses: [ ok: {"Authenticated response", "application/json", Schemas.AuthResponse}, unauthorized: %Reference{"$ref": "#/components/responses/unauthorised"} ] def create(conn, %{"email" => email, "password" => password}) do # ... end ``` The `operation` macro allows you to keep your Open API spec with your API call - yet keep them logically separated. The general configuration for the Open API spec can be found in `/lib/petal_pro_api/api_spec`. It's used to configure things like the title, version or type of authorisation used in the API. It also defines standard responses. For example, it defines the `unauthorised` response that the above code snippet is referring to. One of the benefits of the Open API spec is that it can be used to generate a UI for testing. To see the SwaggerUI, navigate to: ```css http://localhost:4000/dev/swaggerui ``` The spec itself can be found at: ```css http://localhost:4000/api/openapi ``` You can use this with 3rd party tools to generate code or documentation for an API client. Check out the [documentation](https://hexdocs.pm/open_api_spex) for more details on how to configure your API code with Open API Spex. ## Directory Structure The Petal Pro API has been separated into it's own directory structure. This is relevant to the `/lib` and `/test` directories: ```elixir ├── lib │ ├── petal_pro │ ├── petal_pro_api | | ├── controllers | | ├── api_spec.ex | | ├── routes.ex | | ├── schemas.ex │ ├── petal_pro_web ├── test │ ├── petal_pro │ ├── petal_pro_api │ ├── petal_pro_web ``` For the `/lib/petal_pro_api` directory: - `controllers` is where the API methods are kept - `api_spec.ex` is the starting point for Open API Spex (see above) - `routes.ex` is where the API routes are defined. This is included in `/lib/petal_pro_web/router.ex` - `schemas.ex` are the data models that are used by the Open API Spex definition ## Creating you're own API To get your hands dirty with the sample API, see the following: [Creating Your Own API](/petal-pro/guides/creating-your-own-api) --- # GDPR # Source: https://petal.build/petal-pro/fundamentals/gdpr # GDPR Petal Pro ships with a built-in GDPR compliance system covering two user rights: **the right to data portability** (export) and **the right to erasure** (account deletion). Both are exposed to users through Settings > Your Data and processed by `PetalPro.Accounts.GDPR`. ## Enabling GDPR mode The system is gated behind the `:gdpr_mode` config key. When disabled, the Settings > Your Data page is hidden from users. ```elixir # config/config.exs config :petal_pro, :gdpr_mode, true ``` Check programmatically with: ```elixir PetalPro.gdpr_mode() # => true ``` ## Data export ### What users see Users visit **Settings > Your Data** (`/app/users/your-data`) and click "Download my data". The browser receives a JSON file generated on the fly. ### What's included `PetalPro.Accounts.GDPR.export_user_data/1` assembles a single map with these top-level keys: | Key | Contents | |-----|----------| | `exported_at` | ISO 8601 timestamp | | `user` | Name, email, avatar, role, onboarding status, timestamps | | `organizations` | Org name, slug, membership role, join date | | `notifications` | Up to 1 000 most recent (truncated flag if capped) | | `notification_preferences` | Per-type in-app/email toggles | | `billing` | Masked provider customer ID, subscription history | | `posts` | Post titles, slugs, categories, publish dates | | `files` | File names and URLs | | `feedback` | User's own submitted feedback items | | `ai_usage` | AI call log entries — provider, model, token counts, cost | | `activity_log` | Audit log entries attributed to the user | | `changelog_interactions` | Changelog reads and likes | Security-sensitive data is deliberately excluded: password hashes, auth tokens, TOTP secrets, and PINs are never exported. Billing provider IDs (Stripe customer IDs) are masked to the last four characters. ### Generating the JSON ```elixir user = Repo.get!(User, user_id) # Returns a map data = PetalPro.Accounts.GDPR.export_user_data(user) # Returns a pretty-printed JSON string json = PetalPro.Accounts.GDPR.generate_export_json(user) ``` ### Adding custom data to exports When you add a new schema that associates data with a user, update `export_user_data/1` to include it. The function builds a map — just add a new key: ```elixir def export_user_data(%User{} = user) do user = Repo.preload(user, [:memberships, :customer]) %{ exported_at: DateTime.to_iso8601(DateTime.utc_now()), user: export_user_profile(user), # ... existing keys ... survey_responses: export_survey_responses(user) # your addition } end defp export_survey_responses(user) do MyApp.Surveys.SurveyResponse |> where(user_id: ^user.id) |> Repo.all() |> Enum.map(fn r -> %{ question: r.question, answer: r.answer, submitted_at: r.inserted_at } end) end ``` ## Account deletion ### How it works Deletion is a two-step process: 1. The user clicks "Delete my account" in Settings > Your Data and confirms. 2. `PetalPro.Accounts.GDPR.can_delete_user?/1` runs a guard check — a user cannot be deleted if they are the **sole admin** of any organization. 3. If the check passes, an Oban job (`GDPRDeletionWorker`) is enqueued. The user is informed their deletion is scheduled and the session ends shortly after. 4. The worker calls `execute_data_deletion/1` which runs inside a single database transaction. ### What `execute_data_deletion/1` does The deletion cascade runs in this order: 1. **Logs the deletion** — audit record created before anything is anonymized 2. **Deletes AI call logs** — contain sensitive prompt/response data 3. **Deletes file records** — storage object cleanup is a separate concern 4. **Anonymizes feedback** — `user_id` set to nil, content kept 5. **Anonymizes posts** — `author_id` set to nil, posts shown as "Deleted User" 6. **Deletes notifications** — recipient notifications deleted; sender references nullified 7. **Deletes notification preferences** 8. **Deletes changelog interactions** — reads and likes 9. **Deletes auth data** — tokens, PINs, TOTP configs 10. **Removes org memberships and invitations** 11. **Anonymizes audit logs** — `user_id` nullified, metadata cleared (record kept for compliance) 12. **Anonymizes billing customer** — email replaced, `user_id` cleared (record kept for tax/legal) 13. **Soft-deletes the user** — name set to "Deleted User", email replaced with `deleted-{uuid}@deleted.local`, `deleted_at` timestamp set 14. **Removes marketing email contact** — Resend contact deleted outside the transaction; failure is logged but does not roll back the DB deletion ### Adding custom deletion logic Add cleanup for your new schema inside the transaction in `execute_data_deletion/1`. Choose the right strategy: - **Delete the records** when they contain personal data that serves no compliance purpose. - **Nullify the foreign key** when you want to keep the record but disassociate it from the user. ```elixir def execute_data_deletion(%User{} = user) do result = Repo.transaction(fn -> # ... existing steps ... # Delete records that belong to this user MyApp.Surveys.SurveyResponse |> where(user_id: ^user.id) |> Repo.delete_all() # Or anonymize by nullifying the user reference MyApp.Comments.Comment |> where(author_id: ^user.id) |> Repo.update_all(set: [author_id: nil]) # ... rest of cascade ... end) result end ``` > The CLAUDE.md for `petal_pro` explicitly calls this out as a required step whenever you add a new user-associated schema: update both `export_user_data/1` and `execute_data_deletion/1`. --- # Web App From Start to Finish # Source: https://petal.build/petal-pro/guides/creating-a-web-app-from-start-to-finish # Creating a web app from start to finish Matt here. Let's build a complete web app from scratch — branding, feature building, logging, emails, notifications, tests, and deployment. Before we get into it: this is not a v3-style tutorial where I walk you through every file change. Petal Pro v4 ships with CLAUDE.md files throughout the project that give Claude Code full context about the architecture, conventions, and patterns. Your job is to describe what you want. Claude builds it. You review, understand, and steer. That's the workflow we'll follow.

ℹ️ Note: This tutorial was written using Petal Pro v4

### What you'll learn We're building "Financy" — a personal finance tracker. Along the way: - **Branding** — Logo generation and color theming with one Claude command - **Feature building** — How to describe a feature and let Claude build it - **Layouts & menus** — Adding pages to the sidebar - **Logging** — Track user actions with the built-in logging system - **Emails** — Monthly summary emails scheduled with Oban - **Notifications** — In-app and email alerts - **Testing** — Fixing and extending generated tests - **Deployment** — Ship to Fly.io ## Getting up and running ### What you need - Access to Petal Pro ([petal.build](https://petal.build)) - Elixir & Erlang installed — see our [installation guide](/petal-pro/fundamentals/installation) - PostgreSQL running — [Postgres.app](https://postgresapp.com) for Mac, or use the included `docker-compose.yaml` - [tmux](https://github.com/tmux/tmux/wiki), because Claude starts the server in a tmux session - For deployment (optional): a [Fly.io](https://fly.io/) account and a [Resend](https://resend.com) account for email (Petal Pro sends through Resend when `RESEND_API_KEY` is set) ### Download Head to the [projects page](https://petal.build/pro/projects), create a project, and download the latest version. Unzip it. ### Rename ```zsh mv petal_pro financy cd financy ``` You don't need to rename the internal module names — keeping them as `PetalPro` makes it easier to pull in future Petal Pro updates. ### Get it running ```zsh mix setup ``` Then open Claude Code and ask it to start the server: ``` start the server ``` Claude reads the CLAUDE.md and knows exactly what to do: ``` ⏺ Bash(tmux kill-session -t petal_pro 2>/dev/null; tmux new-session -d -s petal_pro "iex -S mix phx.server") ⎿ (No output) ⏺ Server's up in the petal_pro tmux session. Give it a few seconds to compile, then hit localhost:4000. Attach with tmux attach -t petal_pro if you need IEx. ``` ![Claude starting the server](/images/petal_pro_docs/v4/creating-a-web-app-from-start-to-finish/claude-find-admin-user.png)

Claude knew to use tmux — it read the CLAUDE.md

Navigate to `http://localhost:4000`. You'll see the default Petal Pro landing page — blue buttons, Petal logo. Let's brand it before we go any further. ## Adding your brand Petal Pro ships with a `/generate-brand` command that generates all your logo files from a short description in `docs/branding.md`. Open that file and fill it in:
docs/branding.md
```markdown ## App name Financy ## Tagline (optional, used in OG image) Personal assets visualised ## Primary brand color (hex) #10b981 ## Icon style A dollar sign done in a pixelated way. ``` Then in Claude Code: ``` /generate-brand ``` Claude designs an icon and generates all eight files (`logo_dark.svg`, `logo_light.svg`, three `logo_icon*.svg`, `favicon.svg`, `logo_for_emails.png`, `open-graph.png`) into `priv/static/images/`. Don't like it? Tweak "Icon style" and run it again. Also update `config.exs` with your app details (search for `SETUP_TODO`):
config.exs
```elixir config :petal_pro, app_name: "Financy", business_name: "Financy Pty Ltd", support_email: "support@financy.app", mailer_default_from_name: "Financy", mailer_default_from_email: "support@financy.app", logo_url_for_emails: "https://yourcdn.com/financy-logo.png", seo_description: "Personal finance management — track income, expenses, and build toward your goals" ``` And swap the colors in `assets/css/colors.css` — replace `blue` with `emerald` and `pink` with `slate`. Emerald makes sense for a finance app. Restart the server, reload the browser: ![Financy landing page after branding](/images/petal_pro_docs/v4/creating-a-web-app-from-start-to-finish/landing-page-petal-pro.png)

Landing page after branding — Financy pixel-dollar logo, emerald CTA

ℹ️ Email logo: The logo in emails must be a public URL — email clients can't load local files. Once you're happy with the logo, upload logo_for_emails.png to Cloudinary, S3, or your CDN and paste the URL into logo_url_for_emails in config.exs.

The other SETUP_TODOs cover license and privacy policy content — skip those for now, they're not needed until you go live. ## Explore what's included Before building, take five minutes to understand what Petal Pro already gives you. Ask Claude: ``` give me a quick overview of what's included in this project ``` ``` ⏺ Based on the CLAUDE.md files, here's what's already built: Auth — Email/password with confirmation, passwordless PIN login, Google and GitHub OAuth, TOTP 2FA. All methods can coexist on the same account. Admin panel — /admin with user management, org management, real-time activity logs, email template previewer, database schema visualizer, and route explorer. Multi-tenancy — Full org system with invitations, roles (owner/admin/member), and slug-based routing under /app/org/:org_slug/. User settings — Profile, email change, password, 2FA, notification preferences, GDPR data export and account deletion. Background jobs — Oban with default and billing queues. Built-in daily workers for GDPR cleanup and purging expired invitations. Notifications — In-app notification bell + email delivery, per-type user preferences, real-time PubSub updates. Billing — Full Stripe integration, configurable per user or per org. Blog/CMS — Editor.js rich content editor, drafts, categories. ``` Sign in with `admin@example.com` / `password` and click around. A few things worth seeing: **The admin panel** — Click your avatar → Admin. The Logs tab is where user activity ends up — you'll add to it shortly. Dev → Email templates lets you preview every transactional email. The database schema visualizer generates an interactive ER diagram of your whole schema. ![Admin panel](/images/petal_pro_docs/v4/creating-a-web-app-from-start-to-finish/admin.png)

Admin panel — logs, users, orgs, dev tools

**Authentication** — Before signing in, notice the auth options. Passwordless, email/password, OAuth. All built, all working. ![Sign in page](/images/petal_pro_docs/v4/creating-a-web-app-from-start-to-finish/auth.png)

Multiple auth methods — all configured, nothing to build

**The sidebar layout** - Once signed in you'll see the collapsible sidebar with user profile, navigation, and a Notifications item with a live unread badge. This is the layout you'll wrap your own pages in. ![Dashboard](/images/petal_pro_docs/v4/creating-a-web-app-from-start-to-finish/home.png)

The signed-in layout: sidebar, notifications, user profile

**Organizations** — Full multi-tenancy. For Financy we'll scope transactions to individual users, but if you were building a team product, you'd put everything under `/app/org/:org_slug/` instead. ![Organizations](/images/petal_pro_docs/v4/creating-a-web-app-from-start-to-finish/orgs.png)

Orgs — multi-tenancy ready to use if you need it

**Settings** — Profile, email, password, 2FA, notification preferences, GDPR data export. None of this needs building. ![Settings](/images/petal_pro_docs/v4/creating-a-web-app-from-start-to-finish/settings.png)

User settings — fully built

That's the lay of the land. Now let's build the actual product. ## The transactions page ### Tell Claude what you want ``` Build a transaction tracker for Financy. Users should be able to log income and expenses. Each transaction needs: a description, an amount (decimal), a type that's either "income" or "expense", and a date. Transactions belong to the current user and should only be visible to that user. A user must never be able to view, edit or delete someone else's transaction, even with its id. Use the data table generator for the index. ``` Claude reads the CLAUDE.md files (they describe the conventions, the generator and how menus are structured) and gets to work: ``` ⏺ Here's my plan before I start: 1. Run mix petal.gen.live Finance Transaction transactions with the right fields 2. Fix the schema: use PetalPro.Schema, belongs_to :user instead of field :user_id, add validations. user_id stays out of cast 3. Add has_many :transactions to the User schema 4. Make the context functions take the user: list_transactions(user), get_transaction!(user, id) and create_transaction(user, attrs). List and get go through Ecto.assoc(user, :transactions) 5. Use them for every load: the index query, show, edit, delete and bulk delete. create_transaction sets user_id on the server (never from the form), so the index template passes current_user={@current_user} to the FormComponent 6. Keep only the text columns (:description, :type) in the data table's search_fields. Its search uses ILIKE, which Postgres refuses on the decimal and date columns 7. Swap the type field to a select dropdown (income/expense) 8. Default the date to today 9. Add routes under the /app scope 10. Wrap pages in the sidebar layout 11. Add the :transactions menu item and update home_path 12. Add transactions to PetalPro.Accounts.GDPR: export them in export_user_data/1 and delete them in execute_data_deletion/1 13. Add a test that a second user gets a not-found on show, edit, delete and bulk delete Running the generator... ⏺ Bash(mix petal.gen.live Finance Transaction transactions description:string amount:decimal type:string date:date user_id:references:users --data-table) ⎿ * creating lib/petal_pro_web/live/transaction_live/... * creating lib/petal_pro/finance/transaction.ex * creating priv/repo/migrations/20260503_create_transactions.exs ⏺ Bash(mix ecto.migrate) ⎿ Migrated 20260503_create_transactions in 0.0s ⏺ Write(lib/petal_pro/finance/transaction.ex) - fixed schema, belongs_to, validations ⏺ Edit(lib/petal_pro/accounts/user.ex) - added has_many :transactions ⏺ Edit(lib/petal_pro/finance.ex) - every function takes the user ⏺ Edit(lib/petal_pro_web/live/transaction_live/index.ex) - index, edit, delete, bulk delete scoped to current_user, search on text columns ⏺ Edit(lib/petal_pro_web/live/transaction_live/show.ex) - show scoped to current_user ⏺ Edit(lib/petal_pro_web/live/transaction_live/form_component.ex) - creates through the current user ⏺ Edit(lib/petal_pro_web/live/transaction_live/form_component.html.heex) - select dropdown ⏺ Edit(lib/petal_pro_web/router.ex) - added routes under /app ⏺ Edit(lib/petal_pro_web/live/transaction_live/index.html.heex) - sidebar layout, fixed paths, current_user passed to the form ⏺ Edit(lib/petal_pro_web/live/transaction_live/show.html.heex) - sidebar layout, fixed paths ⏺ Edit(lib/petal_pro_web/menus.ex) - added :transactions get_link, updated sidebar_menu_items ⏺ Edit(lib/petal_pro_web/helpers.ex) - updated home_path to /app/transactions ⏺ Edit(lib/petal_pro/accounts/gdpr.ex) - transactions in the export and the account deletion ⏺ Write(test/petal_pro_web/live/transaction_ownership_test.exs) - a second user gets a not-found ⏺ Done. Navigate to http://localhost:4000/app/transactions. ``` A few of those decisions are worth understanding: **`use PetalPro.Schema` not `use Ecto.Schema`** - The generator writes a plain `use Ecto.Schema` schema with a `:binary_id` key. The CLAUDE.md asks for `use PetalPro.Schema` in every schema, which gives you UUID v7 keys like the rest of the app. **`belongs_to :user` not `field :user_id`** — The generator creates `field :user_id, :binary_id`. That works but doesn't set up the Ecto association. `belongs_to` lets you use `Ecto.assoc/2` for scoped queries and preload the user efficiently. **Every load goes through the user** - The generator's `get_transaction!(id)` loads any transaction by the id in the URL or the event, and show, edit, delete and bulk delete all use it. Scoping only the index hides other people's rows from the list but still lets a signed-in user open, change or delete them by id. So the plan changes the context: `get_transaction!(user, id)` does `Repo.get!(Ecto.assoc(user, :transactions), id)`, which raises `Ecto.NoResultsError` for anyone else's id (Phoenix turns that into a 404 when the page loads), and every LiveView passes `socket.assigns.current_user`. The index uses the same `Ecto.assoc(current_user, :transactions)` query for the data table. **`user_id` is set on the server, not cast** - The form never exposes `user_id` as a field, and the generated changeset leaves `user_id` out of `cast`, so keep it that way. `create_transaction(user, attrs)` starts from `%Transaction{user_id: user.id}`, which means a `user_id` sent in the form params is ignored. Never let the client dictate ownership. **The ownership test** - It signs in a second user and checks that show, edit, delete and bulk delete on the first user's transaction all end in `Ecto.NoResultsError` and leave the row alone. Keep a test like this for every resource you add; it's the thing that catches a missed scope.

⚠️ Built Financy from an earlier version of this guide? The earlier plan only scoped the index. Check your context modules for functions that load a record by id alone, like get_transaction!(id), and for every place that calls them (show, edit, delete, bulk delete). Make them take the current user and look the record up inside that user's records, then add a test that a second user gets a not-found. Do the same for anything else you generated with petal.gen.live or petal.gen.html.

### See it working Let's seed some test data. Claude has access to the running IEx session via the tmux session that was started earlier: ``` Add some test transactions via IEx so we can see the table working ``` ``` ⏺ I'll send IEx commands to the running server via tmux. ⏺ Bash(tmux send-keys -t petal_pro 'admin = PetalPro.Accounts.get_user_by_email("admin@example.com"); [%{description: "Salary", amount: "5200.00", type: "income", date: ~D[2026-05-01]}, %{description: "Rent", amount: "1800.00", type: "expense", date: ~D[2026-05-01]}, %{description: "Groceries", amount: "142.50", type: "expense", date: ~D[2026-05-02]}, %{description: "Freelance project", amount: "3500.00", type: "income", date: ~D[2026-05-02]}] |> Enum.each(&PetalPro.Finance.create_transaction(admin, &1))' Enter) ⎿ :ok ⏺ 4 transactions created. Reload http://localhost:4000/app/transactions. ``` Reload the page: ![Transactions with data](/images/petal_pro_docs/v4/creating-a-web-app-from-start-to-finish/transactions-with-data.png)

Transactions table — green income badges, red expense badges, colour-coded amounts

The new transaction form is equally clean: ![New transaction form](/images/petal_pro_docs/v4/creating-a-web-app-from-start-to-finish/transactions-new-form.png)

New transaction modal — type dropdown, date defaults to today

For new users with no transactions yet: ![Empty state](/images/petal_pro_docs/v4/creating-a-web-app-from-start-to-finish/transactions-empty.png)

Empty state — sidebar, menu, and branding already in place

If you want to see the full sign-up flow, sign out and register as a new user. Click **"Continue with email"**, enter any email, and check the terminal (or tmux session) for a 6-digit PIN. In development, emails aren't sent. The PIN is printed to the console. After PIN entry you'll see the onboarding screen, which collects the user's name before redirecting to the app. ## User activity logging Petal Pro puts logging front and centre — it ends up in the admin panel where you can watch it live. ``` Add activity logging to the transactions feature — log when a transaction is created. Include the description, amount, and type as metadata. ``` ``` ⏺ I'll add "transactions.create" to the allowed log actions, then call it after a successful create. ⏺ Edit(lib/petal_pro/logs/log.ex) ⎿ Added "transactions.create" to @action_options ⏺ Edit(lib/petal_pro_web/live/transaction_live/form_component.ex) ⎿ Added after {:ok, transaction}: PetalPro.Logs.log("transactions.create", %{ user: socket.assigns.current_user, metadata: %{ transaction_id: transaction.id, description: transaction.description, amount: transaction.amount, type: transaction.type } }) ``` Create a transaction, then go to Admin → Logs. You'll see the entry. Turn on "Live logs" and open two windows side by side — one on logs, one on transactions. Add a transaction and watch the log entry appear in real time. That's Phoenix PubSub; nothing to configure. ![Admin logs](/images/petal_pro_docs/v4/creating-a-web-app-from-start-to-finish/admin-logs.png)

Admin logs — real-time, filterable, with full metadata

## Monthly summary email Let's build a monthly email showing users their income, expenses, and net for the month. ``` Build a monthly summary email for Financy. It should show total income, total expenses, and net for the current month. Schedule it to run on the 1st of each month at 9am via Oban. Also add it to the Dev email template previewer so I can see it while building. ``` ``` ⏺ I'll build this in four parts: email function, template, preview, and Oban worker. ⏺ Edit(lib/petal_pro_web/notifications/email.ex) ⎿ Added monthly_summary/2 — builds a Swoosh email struct with a summary map ⏺ Write(lib/petal_pro_web/templates/email/monthly_summary.html.heex) ⎿ Template using EmailComponents.gray_box for the income/expenses/net summary and EmailComponents.button_centered to link to /app/transactions ⏺ Edit(lib/petal_pro_web/controllers/email_testing_controller.ex) ⎿ Added "monthly_summary" to @email_templates and generate_email/2 clause with sample data ⏺ Write(lib/petal_pro/workers/monthly_summary_worker.ex) ⎿ Oban worker — fetches this month's transactions per user, calculates totals, sends email to users who have activity ⏺ Edit(lib/petal_pro/finance.ex) ⎿ Added monthly_summary_for/1 — returns %{total_income, total_expenses, net, month, url} ⏺ Edit(config/config.exs) ⎿ Added {"0 9 1 * *", PetalPro.Workers.MonthlySummaryWorker} to Oban crontab ⏺ Preview it at Admin → Dev → Email templates → monthly_summary. Test manually: Oban.insert(PetalPro.Workers.MonthlySummaryWorker.new(%{})) Check the captured email at http://localhost:4000/dev/mailbox. ``` How email works in Petal Pro: `email.ex` creates `%Swoosh.Email{}` structs (the view), `user_mailer.ex` delivers them (the controller). The dev mailbox at `/dev/mailbox` captures everything locally so nothing actually sends in development. ## In-app notifications The Notifications item in the sidebar is already wired up, with an unread badge. Let's give it something to count when a user's spending exceeds their income. ``` Add an in-app notification that fires when expenses exceed income for the month. Wire it into the monthly summary worker so it runs at the same time. Users should be able to turn it off from their notification preferences. ``` ``` ⏺ I'll register the notification type in the four places Petal Pro reads it, then trigger it from the worker. ⏺ Edit(lib/petal_pro/notifications/user_notification.ex) ⎿ Added :spending_exceeds_income to @notification_types ⏺ Edit(lib/petal_pro/notifications/preferences.ex) ⎿ Added spending_exceeds_income: %{ label: "Spending alerts", description: "When your expenses exceed your income for the month", category: :account, channels: [:in_app], allow_disable_in_app: true, allow_disable_email: false } ⏺ Edit(lib/petal_pro/notifications/user_notification_attrs.ex) ⎿ Added spending_exceeds_income_notification/1: %{ type: :spending_exceeds_income, recipient_id: recipient_id, read_path: ~p"/app/transactions", message: gettext("Your expenses exceeded your income this month.") } ⏺ Edit(lib/petal_pro_web/live/notifications/notifications_components.ex) ⎿ Added a notification_item/1 clause for :spending_exceeds_income ⏺ Edit(lib/petal_pro/workers/monthly_summary_worker.ex) ⎿ Added Notifications.notify/3 call when Decimal.compare(summary.net, 0) == :lt: PetalPro.Notifications.notify( UserNotificationAttrs.spending_exceeds_income_notification(user.id), user ) ``` The sidebar's unread badge updates in real time when a notification arrives, and the message shows on the notifications page. Users can toggle it off from Settings → Notifications. That option is there automatically because we set `allow_disable_in_app: true`, and the `label`, `description` and `category` are what that page shows. All four files matter. The type has to be in `@notification_types`, because `UserNotification` stores it as an `Ecto.Enum`. The attrs have to use the schema's field names (`recipient_id` and `message`). `notification_item/1`, which draws each notification in the list, has no catch-all clause, so each type needs its own. And `notify/3` returns `{:ok, %{in_app: {:error, changeset}}}` when the insert fails, so a wrong type or field doesn't raise. Ask Claude for a test that calls the worker and checks a row lands in `user_notifications`. ## Writing tests ``` The generated test files need updating - the Finance functions take the user now. Fix them, including transaction_live_test.exs: sign in a user and use the /app paths. Also add a test for monthly_summary_for/1. Then run the whole suite, because the Pro tests that expect a redirect to /app need the new home_path. ``` ``` ⏺ Bash(mix test test/petal_pro/finance_test.exs) ⎿ every test fails - the fixture and the tests still call the old arities ⏺ Edit(test/petal_pro/finance_test.exs) ⎿ Added user setup in describe block Updated the fixture and every call to pass the user Added test: create_transaction with negative amount returns error changeset Added test: monthly_summary_for sums income and expenses correctly ⏺ Edit(test/petal_pro_web/live/transaction_live_test.exs) ⎿ Signs in a user, creates fixtures for that user, uses the /app/transactions paths ⏺ Bash(mix test) ⎿ The Pro tests that assert a redirect to "/app" fail - home_path is "/app/transactions" now ⏺ Edit(test/petal_pro_web/controllers/user_auth_test.exs, org_plugs_test.exs, ...) ⎿ Expect ~p"/app/transactions" where the tests expected ~p"/app" ⏺ Bash(mix test) ⎿ 0 failures ``` Why the whole suite and not just `finance_test.exs`: the generator also writes `test/petal_pro_web/live/transaction_live_test.exs`, which still uses the old fixture and the generator's `/transactions` paths, and changing `home_path` breaks the Pro tests that expect a redirect to `/app` (the sign-in, impersonation and org plug tests among them). Running one file hides all of that. ## Using Claude Code effectively A few things that make working with Petal Pro and Claude Code smoother: **Be specific about what you want.** "Add logging" works, but "log when a transaction is created — include the description, amount, and type as metadata, use dotted naming like `transactions.create`" gets it right first time. **Ask for explanations after.** Claude will often make the right call without explaining why. If you want to understand a decision, just ask — "why did you use `Ecto.assoc` instead of a `where` clause?" **Use tmux and the browser for live inspection.** Claude can send IEx expressions to the running server via tmux (`tmux send-keys -t petal_pro '...' Enter`) and read the output. It can also use the Claude browser extension to navigate the app, fill forms, and screenshot results directly — useful for testing UI flows without manual clicking. **The CLAUDE.md files carry the context.** Don't explain Petal Pro conventions to Claude — they're already documented in the CLAUDE.md files across the project. Just describe your feature. If Claude gets something wrong, it's usually worth checking whether the relevant convention is in the docs and asking Claude to re-read it. **Slash commands are your shortcuts.** Petal Pro ships skills like `/new-liveview`, `/add-org-feature` and `/add-admin-page` in `.claude/skills/`, plus recipes in `.claude/commands/recipes/`. See [Claude Code integration](/petal-pro/fundamentals/claude-code-integration) for the full list. ## Deployment with Fly.io To deploy, follow the [Deploy to Fly.io guide](/petal-pro/guides/deploy-to-fly.io). ### Before you go live Things v4 handles for you that you should switch on: - **Error monitoring** - Set `SENTRY_DSN` on your Fly app. Auto-activates when present, nothing else to configure. - **Rate limiting** - Auth endpoints are already rate-limited with Hammer. No configuration needed. - **GDPR** - Users can export and delete their data from Settings → Your data. Soft-deletion and anonymization run automatically via Oban. That covers Petal Pro's own tables. Every user-owned table you add (like `transactions`) has to go into `export_user_data/1` and `execute_data_deletion/1` in `PetalPro.Accounts.GDPR`, which is why the plan has a step for it. Without that, a deleted account leaves its rows behind and the export leaves them out. - **Email** - Set `RESEND_API_KEY` on your Fly app. Without it Petal Pro falls back to `Swoosh.Adapters.Logger`, so emails only show up in the logs. - **Billing** - If you're adding payments, see the [Stripe billing docs](/petal-pro/fundamentals/stripe-billing). ## From nothing to production That's the full loop — branding, feature, logging, email, notifications, tests, deploy. The thing worth reflecting on: most of the boilerplate was written by Claude while you described what you wanted. The CLAUDE.md files meant you never had to explain how Petal Pro works. Claude already knew. `use PetalPro.Schema`, the notification system's `notify/3` API, the dotted log action naming convention: all of that context was already there. The one thing you spelled out was who owns a record, and that's worth spelling out for every resource: the generator doesn't scope records to a user, so the plan has to. The more you work in this project, the more that pattern pays off. Things worth exploring next: - **[Stripe billing](/petal-pro/fundamentals/stripe-billing)** — Add subscription plans or one-time purchases - **[Organizations](/petal-pro/fundamentals/organizations-and-multitenancy)** — Scope transactions under orgs for shared household or business budgets - **[Image uploads](/petal-pro/fundamentals/image-uploads)** — Attach receipts to transactions - **[Generators](/petal-pro/fundamentals/generators)** — Use `petal.gen.live` to scaffold more features If you have any feedback, head [here](https://petal.build/feedback) to get in touch. --- # Deploy to Fly.io # Source: https://petal.build/petal-pro/guides/deploy-to-fly.io # Deploy to Fly.io Ship your Petal Pro app to production on Fly.io. ## Before you start There are a few things to think about before deploying — see [Deployment fundamentals](/petal-pro/fundamentals/deployment) for the full checklist. If you're using Claude Code, the easiest path is to ask: ``` help me deploy this app to Fly.io ``` Claude knows the patterns from the CLAUDE.md files and will walk you through the steps below. The rest of this guide is the same flow, in case you want to do it yourself. ## Dev commands The everyday commands are plain mix: ```shell iex -S mix phx.server # Start Phoenix with IEx attached mix ecto.reset # Drop, create, migrate, and seed the database sh scripts/stripe_webhooks.sh # Forward Stripe webhooks to localhost in a tmux session (needs the Stripe CLI and tmux) ``` ## Launch on Fly.io Fly.io is the cheapest, easiest place to host a Phoenix app. Petal Pro is configured to deploy there with minimal fuss. Install the [Fly.io CLI](https://fly.io/docs/getting-started/installing-flyctl), then [sign in](https://fly.io/docs/getting-started/log-in-to-fly/). Create a new app with: ```shell fly launch ```

ℹ️ Information: Fly will prompt you with default settings and ask if you want to tweak them. Hit Y — it opens a browser configuration UI.

In the configuration UI: - Give your app a name (you can't change it later). - Under Database, choose **Fly Postgres**. - Pick the cheapest server size to start. - Leave Redis as **none**. - Hit Confirm. ## The Dockerfile Petal Pro v4 ships a production-ready `Dockerfile` in the repo root — you don't need to generate one with `mix phx.gen.release --docker`. It's a multi-stage build: - **Builder stage**: Elixir 1.19.5 / OTP 27.3.4 on Debian Bookworm. Compiles deps, runs the npm asset pipeline, produces an Elixir release. - **Runner stage**: Lean Debian Bookworm slim with only the compiled release — no Elixir or build tools in the production image. `fly launch` detects the existing Dockerfile and uses it. If it tries to generate a new one, skip that step — the included Dockerfile already has `nodejs` and `npm` for the asset pipeline. ## Environment variables `fly launch` automatically creates these secrets: - `SECRET_KEY_BASE` - `DATABASE_URL` The generated `fly.toml` also sets: - `PHX_HOST` - `PORT` ### CLIENT_IP_HEADER Not a secret, so it goes in `fly.toml` and not `fly secrets set`. Add one more line to that `[env]` block yourself:
fly.toml
```toml [env] PHX_HOST = "your-app.fly.dev" PORT = "8080" CLIENT_IP_HEADER = "fly-client-ip" ``` Petal Pro records the client's address on sign-in (`last_signed_in_ip`), in the audit log and on Sentry events. Since 4.5.0 it ignores `x-forwarded-for` unless you tell it which proxy to trust, because anyone can write that header. Fly overwrites `fly-client-ip` on every request, so `CLIENT_IP_HEADER = "fly-client-ip"` is the one to trust. Leave it out and every sign-in records Fly's proxy address instead of your user's. ### Required ```shell # Email — required for auth flows (confirmation, password reset, etc.) fly secrets set RESEND_API_KEY="re_..." ``` ### Optional ```shell # Sentry error tracking — auto-activates when set, no code changes needed fly secrets set SENTRY_DSN="https://..." # Admin MCP API bearer token (for AI tool access) fly secrets set MCP_ADMIN_TOKEN="your_secure_token" # Slack notifications (new signups, billing events, daily digest) fly secrets set SLACK_OAUTH_TOKEN="xoxb-..." fly secrets set SLACK_CHANNEL_ID="C0123456789" ``` ### FORCE_SSL Since 4.5.0, production forces https. Plain http gets redirected to https (301 for GET and HEAD, 307 for everything else), https responses get a one-year HSTS header, and cookies are marked `Secure`. Fly terminates TLS at its edge and passes the original scheme along in its `fly-forwarded-proto` header, which Petal Pro trusts, so on Fly there's nothing to set. `FORCE_SSL` is on when it's unset, `true` or `1`. 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. Watch your health checks. An HTTP health check now gets a 301 unless it sends `X-Forwarded-Proto: https` or its path is excluded. The default `fly launch` config uses TCP checks, which are unaffected. If you added an HTTP check, give it the header. Petal Pro ships no health route, so `/healthz` here stands in for whatever path your own check hits:
fly.toml
```toml [[http_service.checks]] path = "/healthz" [http_service.checks.headers] X-Forwarded-Proto = "https" ``` Or exclude its path in the `config :petal_pro, :force_ssl` block of `config/runtime.exs`. Step 5 of the [4.4.0 to 4.5.0 upgrade guide](/petal-pro/upgrade-guide) has that snippet, plus the one entry you need to keep when you add an exclusion. ## Auto-deploy on push to main Petal Pro v4 includes a GitHub Actions workflow at `.github/workflows/fly.yml`. Out of the box it's scoped to a `demo` branch (that's how we deploy our public demo), so pushing to `main` deploys nothing until you change the trigger. Edit `branches` so it reads: ```yaml name: Deploy to Fly.io on: push: branches: - main ``` The rest of the file (concurrency, the flyctl steps) stays as it ships. To enable it: 1. `fly tokens create deploy -x 999999h` to generate a long-lived token 2. In your GitHub repo: **Settings → Secrets and variables → Actions** 3. Add a secret called `FLY_API_TOKEN` with the token value `cancel-in-progress: false` queues deploys instead of cancelling them — so you don't end up half-deployed if you push twice in a row. ## Manual deploy You can also deploy at any time with: ```shell fly deploy ```

ℹ️ Information: If deployment fails, you may need to add a payment method — Fly only allows 1 machine per app on the free tier.

After deploying, run `fly open` to view it in the browser. You're live. --- # Adding a Subscription # Source: https://petal.build/petal-pro/guides/adding-a-subscription # Adding a subscription How to start charging customers in your Petal Pro app. ## Before you start This guide picks up from where the [main tutorial](/petal-pro/guides/creating-a-web-app-from-start-to-finish) leaves off — you should have a Petal Pro app running locally. If you don't, follow that guide first to get a fresh app set up. Or just unzip Petal Pro into a fresh folder, run `mix setup`, start the server, and you're ready. You'll also need: - A [Stripe](https://stripe.com/) account - The [Stripe CLI](https://stripe.com/docs/stripe-cli#install) installed locally - An account on [Fly.io](https://fly.io/) if you want to deploy

ℹ️ Information: Stripe now offers Sandboxes as an alternative to test mode. We recommend using a Sandbox — it's an isolated environment so you can experiment without polluting your real account data.

## Configure Stripe Make sure Stripe is in test mode (or use a Sandbox), then sign in via the CLI: ```shell stripe login ``` ### Create your products Petal Pro comes pre-configured for three plans: **Essential**, **Business**, and **Enterprise** with monthly and yearly prices. You'll create those products in Stripe and grab the IDs. Create the Essential product: ```shell stripe products create --name="Essential" ``` Copy the `id` from the response — it looks like `prod_xxxxx`. Create the monthly price: ```shell stripe prices create \ --unit-amount=1900 \ --currency=usd \ -d "recurring[interval]"=month \ --product="prod_xxxxx" ```

ℹ️ Information: --unit-amount is in cents, not dollars.

Now the yearly price: ```shell stripe prices create \ --unit-amount=19900 \ --currency=usd \ -d "recurring[interval]"=year \ --product="prod_xxxxx" ``` Repeat the whole process for **Business** and **Enterprise**. Suggested pricing: | Product | Essential | Business | Enterprise | | --- | --- | --- | --- | | Monthly | $19 | $49 | $99 | | Yearly | $199 | $499 | $999 | You'll end up with six prices in total. Keep them somewhere — you'll paste them into your Petal Pro config shortly. ### Allow plan switching in the Customer Portal When users want to change plans, Stripe handles it through the Customer Portal. You need to enable plan switching: 1. In Stripe (test mode), click the cog (top right) → **Settings** 2. In **Billing**, click **Customer Portal** 3. Expand **Subscriptions** 4. Enable **Customers can switch plans** 5. Add prices from Essential, Business, and Enterprise via "Find a test product..." You might also want to fill in **Business information** to customise the portal's branding. ## Configure Petal Pro Three things to do locally: 1. Run the Stripe webhook listener 2. Add Stripe secrets to your environment 3. Update the Petal Pro config with your product/price IDs ### Webhook listener ```shell stripe listen --forward-to localhost:4000/webhooks/stripe ``` Output will include a webhook signing secret like `whsec_xxxxxxxxxxxxxxx`. Save it — that's your `STRIPE_WEBHOOK_SECRET`. Keep this command running in a terminal (or in tmux). If you're using Claude Code, ask: ``` run the stripe webhook listener in tmux so it keeps going in the background ``` ### Environment variables You need: - `STRIPE_SECRET` — get it from Stripe → **Developers** → **API keys** → **Reveal test key** - `STRIPE_WEBHOOK_SECRET` — from the `stripe listen` output above Petal Pro uses [direnv](https://direnv.net/) for local environment variables. Install it, then: ```shell cp .envrc.example .envrc ``` Uncomment and fill in the Stripe variables at the bottom of `.envrc`. The `.envrc` file is gitignored — your secrets stay local. Activate them: ```shell direnv allow ``` ### Update the product config Open `config/config.exs` and find `:billing_products`. You'll see placeholder Stripe price IDs like `price_1NLhPDIWVkWpNCp7trePDpmi`. Replace each one with the real IDs from your Stripe account. To list the prices for a product: ```shell stripe prices list --product=prod_xxxxx ``` If you'd rather not chase down IDs manually, ask Claude: ``` I've created Essential, Business, and Enterprise products in Stripe. Update config.exs with the real price IDs by listing prices via the Stripe CLI. ``` ## Test it Sign in to your app as the admin user (`admin@example.com` / `password`). Navigate to **Organizations** in the sidebar. Click your org, then **Subscribe**. You'll see your three plans with pricing. Click **Subscribe** on a plan. You'll be redirected to Stripe's checkout. Use the test card `4242 4242 4242 4242` with any expiry and CVC. Submit. You'll be returned to the billing success page with your subscription active.

ℹ️ Information: If you see a spinner that never resolves, your Stripe webhook listener isn't running. Restart it with stripe listen --forward-to localhost:4000/webhooks/stripe.

To verify subscription-protected routes work, navigate to `/app/org/:org_slug/subscribed_live` — you should see a page that was previously blocked. To add your own subscriber-only routes, edit `lib/petal_pro_web/routes/subscription_routes.ex`. ## Org vs user subscriptions Subscriptions can belong to organizations or individual users. The default is `:org`:
config/config.exs
```elixir # :org is the default. Set to :user to switch. config :petal_pro, :billing_entity, :org ``` The relevant routes for org-based subscriptions: ``` /app/org/:org_slug/subscribe # Pick a plan /app/org/:org_slug/subscribe/success # After purchase /app/org/:org_slug/billing # Manage subscription /app/org/:org_slug/subscribed_live # Subscriber-only example route ``` For user-based subscriptions: ``` /app/subscribe /app/subscribe/success /app/billing /app/subscribed_live ``` In `subscription_routes.ex` there are two scope blocks — one for `:user` mode, one for `:org` mode. Add new subscriber-only routes inside the appropriate block. ## Deploy to production Three steps: 1. Push the app to Fly.io 2. Set up a webhook endpoint on Stripe pointing at your Fly app 3. Set Stripe secrets on Fly.io ### Push to Fly.io Follow the [Deploy to Fly.io guide](/petal-pro/guides/deploy-to-fly.io). ### Stripe webhook endpoint In Stripe (test mode): 1. **Developers** → **Webhooks** → **Add endpoint** 2. **Endpoint URL**: `https://your-app-name.fly.dev/webhooks/stripe` 3. Under **Select events to listen to**, add: - `customer.subscription.created` - `customer.subscription.updated` 4. Click **Add endpoint** ### Fly.io secrets You'll need: - `STRIPE_SECRET` — from **Developers** → **API keys** → **Reveal test key** - `STRIPE_WEBHOOK_SECRET` — from the Stripe webhook endpoint you just created (click **Reveal** under "Signing secret") ```shell fly secrets set \ STRIPE_SECRET="sk_test_xxx" \ STRIPE_WEBHOOK_SECRET="whsec_xxx" \ STRIPE_PRODUCTION_MODE="false" ``` After Fly redeploys, you should be able to subscribe through your live app using test cards. ## Going live Everything so far has been in test mode. To switch to production: ### CLI commands in live mode The Stripe CLI defaults to test mode. To work with live data, append `--live`: ```shell stripe products list --live ``` Not every command supports `--live`, but the ones in this guide do. ### Recreate products in live mode Repeat the [Configure Stripe](#configure-stripe) section in live mode. You'll get new product and price IDs. Before you update production `config.exs`, **copy the existing test-mode billing config to `config/dev.exs`** so your dev environment keeps working with test prices: ```elixir config :petal_pro, :billing_products, [ %{ id: "essential", name: "Essential", # ... your test-mode config } ] ``` Then update `config.exs` with the live-mode product/price IDs. Your dev machine uses test mode, your production server uses live mode. Set `STRIPE_PRODUCTION_MODE=true` on Fly.io once you're ready to take real payments. --- # Metered Usage # Source: https://petal.build/petal-pro/guides/metered-usage # Metered usage How to charge customers based on how much they actually use — instead of fixed monthly tiers. ## Before you start Metered usage is a step beyond a regular subscription. You should have read [Adding a subscription](/petal-pro/guides/adding-a-subscription) first, and have a Petal Pro app running locally. The differences with metered billing: - In **Stripe** you create a **Meter** plus prices configured for usage rather than a fixed amount - In **Petal Pro** you call `Meters.record_event/4` whenever a billable action happens, and a background worker syncs those events to Stripe This guide walks through billing customers per AI token consumed. Petal Pro doesn't ship a user-facing AI chat (the built-in one is admin-only), so you'll build a small one and wire metered usage into it. You'll need: - A working Petal Pro app - A [Stripe](https://stripe.com/) account with the [CLI](https://stripe.com/docs/stripe-cli#install) installed - The Stripe CLI logged in (`stripe login`)

ℹ️ Information: Stripe now offers Sandboxes as an alternative to test mode. We recommend using a Sandbox so you can experiment cleanly without affecting your real account.

## Configure Stripe ### Create a metered product ```shell stripe products create --name="Essential" ``` Save the returned `id` (looks like `prod_xxxxx`). Now create a metered price. The key is `usage_type=metered`: ```shell stripe prices create \ --unit-amount=5 \ --currency=usd \ -d "transform_quantity[divide_by]"=1000 \ -d "transform_quantity[round]"=up \ -d "recurring[interval]"=month \ -d "recurring[usage_type]"=metered \ --product="prod_xxxxx" ``` Translation: 5 cents per 1,000 units, rounded up. So a single use costs at least $0.05.

ℹ️ Information: --unit-amount is in cents.

Repeat the process for **Business** and **Enterprise** at different rates: | Plan | Rate | | --- | --- | | Essential | $0.05 per 1,000 units | | Business | $0.50 per 15,000 units | | Enterprise | $5 per 200,000 units | ### Allow plan switching Same as a regular subscription: 1. Stripe → cog → **Settings** → **Billing** → **Customer Portal** 2. Expand **Subscriptions** 3. Enable **Customers can switch plans** 4. Add the metered prices from each product

ℹ️ Information: If you can't add metered prices, remove all existing prices first then re-add.

### Create a Meter A Meter groups usage events under a feature. We're going to track AI tokens: ```shell stripe billing meters create \ --display-name="AI tokens" \ --event-name=ai_tokens \ -d "default_aggregation[formula]"=sum ```

ℹ️ Information: The billing command is a recent addition to the Stripe CLI. Make sure you're on the latest version.

## Configure Petal Pro Same three steps as a regular subscription: 1. Run the webhook listener (`stripe listen --forward-to localhost:4000/webhooks/stripe`) — keep it running in tmux 2. Set `STRIPE_SECRET` and `STRIPE_WEBHOOK_SECRET` in `.envrc` 3. Update product/price IDs in `config.exs` If you've already done the [subscription guide](/petal-pro/guides/adding-a-subscription), you've already got steps 1 and 2. For step 3, your config will look slightly different — metered prices use `unit_amount` and `per_units` instead of a flat `amount`, and you can drop `trial_days`. In this guide we're using monthly pricing only, so you can also remove `essential-yearly` from the config. When you call Stripe to subscribe a user, you must omit `quantity` for metered prices — passing it returns a Stripe error. To grab your meter and price IDs: ```shell stripe billing meters list stripe prices list --product=prod_xxxxx ``` Or just ask Claude: ``` I've created Essential, Business, Enterprise products in Stripe with metered prices, plus an "ai_tokens" meter. Update config.exs with the real IDs. ``` ### Enable the CollectMeterEvents GenServer Recording events shouldn't block the calling process. Petal Pro queues events through `CollectMeterEvents` — uncomment it in `lib/petal_pro/application.ex`:
application.ex
```diff defmodule PetalPro.Application do def start(_type, _args) do children = [ ... - # PetalPro.Billing.Meters.CollectMeterEvents, + PetalPro.Billing.Meters.CollectMeterEvents, ... ] ... end end ``` ### Enable the sync worker `MeterSyncWorker` is the Oban job that uploads queued events to Stripe. Uncomment it in `config.exs`:
config/config.exs
```diff config :petal_pro, Oban, repo: PetalPro.Repo, queues: [default: 5, billing: 5], plugins: [ {Oban.Plugins.Pruner, max_age: 3600 * 24}, {Oban.Plugins.Cron, crontab: [ - # {"@daily", PetalPro.Billing.Providers.Stripe.Workers.MeterSyncWorker}, + {"@daily", PetalPro.Billing.Providers.Stripe.Workers.MeterSyncWorker}, ]} ] ```

ℹ️ Information: Notice the billing queue alongside default. Stripe-related jobs run on the billing queue so they can be monitored separately in Oban Web.

## How metered usage works Two halves: recording events and syncing them to Stripe. ### Recording usage ```elixir alias PetalPro.Billing.Meters Meters.record_event(meter_id, customer_id, subscription_id, quantity) ``` Non-blocking — it queues the event through `CollectMeterEvents`, which writes it to the `billing_meter_events` table in the background. ### Syncing to Stripe Petal Pro is the source of truth for metered events. The Stripe API doesn't let you filter usage by `subscription_id`, but the Petal Pro database does — which is what makes the billing page able to show upcoming charges per subscription. `MeterSyncWorker` runs daily by default and uploads unprocessed events to Stripe. Events are marked processed when uploaded successfully or when an error occurs.

🚨 Heads up: Events with errors won't sync to Stripe. Check the billing_meter_events table for error messages. Clear an event's error_message to make it eligible for re-processing.

For testing in dev, you might want to run the worker more often. Switch the cron schedule:
config/config.exs
```diff - {"@daily", PetalPro.Billing.Providers.Stripe.Workers.MeterSyncWorker} + {"* * * * *", PetalPro.Billing.Providers.Stripe.Workers.MeterSyncWorker} ``` Or trigger one manually in IEx: ```elixir PetalPro.Billing.Providers.Stripe.Workers.MeterSyncWorker.new(%{}) |> Oban.insert() ``` ## Wiring it into AI chat Now to make AI chat actually charge per token. The plan: 1. Remove the month/year toggle on the subscribe page (we're metered now) 2. Build a `UserAiChatLive` and mount it under the subscription routes (we need access to the customer + subscription) 3. Add a menu link 4. Capture token usage from the AI calls 5. Call `Meters.record_event/4` from the LiveView If you'd rather skip the manual steps, ask Claude: ``` Add a metered user AI chat: remove the interval selector from the subscribe page, create a UserAiChatLive mounted at /ai-chat in SubscriptionRoutes, add a menu link in menus.ex, and record token usage via Meters.record_event/4 in it. ``` The rest of this section walks through it manually. ### Remove the month/year toggle In `subscribe_live.ex`, drop the `interval_selector` attribute:
subscribe_live.ex
```diff - + ``` ### Move AI chat behind subscription Recording usage needs `customer_id` and `subscription_id`. The simplest way to have those in the LiveView's assigns is to mount under `SubscriptionRoutes`. Petal Pro doesn't ship a user-facing AI chat. The built-in chat is the admin-only one at `/admin/chat`. So for this part you'll build your own `UserAiChatLive` (the `/new-liveview` skill is a good start) and mount it under `SubscriptionRoutes` from day one. There's no route to remove from `router.ex`. Add it inside `SubscriptionRoutes`, in both the `:user` and `:org` blocks:
subscription_routes.ex
```diff live_session :subscription_authenticated_user, ... do live "/subscribed_live", SubscribedLive + live "/ai-chat", UserAiChatLive end live_session :subscription_authenticated_org, ... do live "/subscribed_live", SubscribedLive + live "/ai-chat", UserAiChatLive end ``` For `:user` subscriptions the URL is `http://localhost:4000/app/ai-chat`. For `:org` subscriptions it becomes `http://localhost:4000/app/org/your-org-slug/ai-chat`. Either way the LiveView mounts with `customer` and `subscription` already in assigns. ### Update the menu There's no AI chat link in `menus.ex` to remove. Add one to the org menu (assuming you're using `:org` subscriptions). Then add a `get_link/2` clause for `:org_chat_ai` pointing to the new path. ### Capture token usage Petal Pro v4 uses [Jido AI](https://hex.pm/packages/jido_ai) (replacing LangChain). Cost tracking happens automatically — every API call is logged to the `ai_call_logs` table with token counts via a Req plugin. For metered billing, you also need that data inside the LiveView so you can call `Meters.record_event/4`. Configure the AI client's token usage callback to send a message back to `self()`. ### Record the event Add a `handle_info` callback to the `UserAiChatLive` you created above: ```elixir @impl true def handle_info({:token_usage, %{input: input, output: output}}, socket) do meter = PetalPro.Billing.Meters.get_meter_by_event_name("ai_tokens") total_tokens = input + output PetalPro.Billing.Meters.record_event( meter.id, socket.assigns.customer.id, socket.assigns.subscription.id, total_tokens ) {:noreply, socket} end ``` Because the LiveView is mounted under the subscription routes, `customer` and `subscription` are already in assigns. We just look up the meter and record the event. ## Testing it Sign in as admin (`admin@example.com` / `password`). 1. Go to **Organizations** → click your org → **Subscribe** 2. Pick a plan, complete checkout with `4242 4242 4242 4242` 3. Once subscribed, click the **AI Chat** link you added to the org menu 4. Ask the AI a question Verify the event was recorded by querying `billing_meter_events`. Or ask Claude: ``` Use IEx to show me the latest billing_meter_events ``` To see the upcoming charges in Stripe, run `MeterSyncWorker` (or wait for the cron), then go to your org → **Org Settings** → **Billing**. You should see the upcoming amount and your AI Tokens usage.

ℹ️ Information: Stripe takes a moment to update upcoming invoices — give it 30 seconds.

## Deploy Same as a regular subscription — see the [subscription deployment section](/petal-pro/guides/adding-a-subscription#deploy-to-production). The Stripe webhook events you need are the same: - `customer.subscription.created` - `customer.subscription.updated` The metered billing happens server-side via the `MeterSyncWorker` cron — make sure your Fly.io app is keeping its workers alive. ## Going live Same flow as the [subscription guide's "Going live"](/petal-pro/guides/adding-a-subscription#going-live) — recreate your products and the meter in Stripe live mode, copy your test-mode billing config to `config/dev.exs` so dev keeps working with test prices, then update `config.exs` with the live IDs and set `STRIPE_PRODUCTION_MODE=true` on Fly. --- # Creating Your Own API # Source: https://petal.build/petal-pro/guides/creating-your-own-api # Creating your own API Petal Pro ships with a JSON REST API for user management — register, sign in, and update profile. It's documented with OpenAPI/Swagger out of the box. This guide shows how to extend it with your own endpoints. For background on the included API, see [REST API fundamentals](/petal-pro/fundamentals/rest-api). ## Using the Swagger UI Petal Pro generates an interactive Swagger UI for the API at: ``` http://localhost:4000/dev/swaggerui ``` To call an endpoint: 1. Expand a route (e.g. `/api/register`) 2. Click **Try it out** 3. Fill in parameters and request body 4. Click **Execute** Some routes are protected — calling them without authentication returns `401 Unauthorized`. To authenticate: 1. Run `/api/sign-in` with an email and password 2. Copy the `token` from the response 3. Click **Authorize** at the top of the page 4. Paste the bearer token and click **Authorize** again The token is valid for 30 days by default. ## Generating the OpenAPI spec To export the spec as JSON: ```shell mix openapi.spec.json --spec PetalProApi.ApiSpec ``` You can also save it from the Swagger UI — click the link under the "Petal Pro API" heading and use your browser's "Save As". ## Extending the API Let's add an endpoint that returns the list of organizations a user belongs to. The path forward: 1. Build the controller 2. Add the route 3. Write a test 4. Add authentication checks 5. Add OpenAPI documentation If you'd rather just describe what you want and let Claude do the typing, drop this into Claude Code: ``` Add an API endpoint at GET /api/user/:id/orgs that returns a list of organization names for the user. Protect it so users can only fetch their own orgs (admins can fetch any user's orgs). Add tests and OpenAPI docs. ``` Claude knows the conventions from the CLAUDE.md files. The rest of this guide walks through what gets built. ### The controller Create `lib/petal_pro_api/controllers/membership_controller.ex`:
membership_controller.ex
```elixir defmodule PetalProApi.MembershipController do use PetalProWeb, :controller alias PetalPro.Accounts alias PetalPro.Orgs action_fallback PetalProWeb.FallbackController def list(conn, %{"id" => id}) do user = Accounts.get_user!(id) org_names = user |> Orgs.list_orgs() |> Enum.map(& &1.name) json(conn, org_names) end end ``` ### The route Add to `lib/petal_pro_api/routes.ex` inside the existing scope:
routes.ex
```elixir scope "/api", PetalProApi do pipe_through [:api, :api_authenticated] get "/user/:id", ProfileController, :show patch "/user/:id/update", ProfileController, :update_profile post "/user/:id/request-new-email", ProfileController, :request_new_email post "/user/:id/change-password", ProfileController, :change_password get "/user/:id/orgs", MembershipController, :list # add this end ``` ### A test Create `test/petal_pro_api/membership_controller_test.exs`:
membership_controller_test.exs
```elixir defmodule PetalProApi.MembershipControllerTest do use PetalProWeb.ConnCase setup %{conn: conn} do user = PetalPro.AccountsFixtures.confirmed_user_fixture() org = PetalPro.OrgsFixtures.org_fixture(user) membership = PetalPro.Orgs.get_membership!(user, org.slug) {:ok, conn: put_req_header(conn, "accept", "application/json"), user: user, org: org, membership: membership} end describe "list" do test "returns the user's organizations", %{conn: conn, user: user} do conn = get(conn, ~p"/api/user/#{user.id}/orgs") assert orgs = json_response(conn, 200) assert Enum.count(orgs) > 0 end end end ``` If you run it now: ```shell mix test test/petal_pro_api/membership_controller_test.exs ``` It fails: ``` 1) test list returns the user's organizations ** (RuntimeError) expected response with status 200, got: 401 ``` That's because the route is in the `:api_authenticated` pipeline and our test hasn't set up a bearer token. ### Authenticating in tests `put_bearer_token/2` is a helper in `/test/support/conn_case.ex`. It generates a bearer token for a user and adds it to the request as an `Authorization` header. Update the test: ```elixir test "returns the user's organizations", %{conn: conn, user: user} do conn = conn |> put_bearer_token(user) |> get(~p"/api/user/#{user.id}/orgs") assert orgs = json_response(conn, 200) assert Enum.count(orgs) > 0 end ``` Now `mix test` passes. ### Authorization (not just authentication) A bearer token proves *who* the user is. But you usually also want to check *what they're allowed to do*. In our case, users should only be able to fetch their own orgs — unless they're admins, in which case they can fetch anyone's. `PetalProApi.ProfileController` has a `match_current_user` function plug that does exactly this. It compares the URL's `:id` with the authenticated user's ID. If they match (or the authenticated user is an admin), the plug puts the user into `conn.assigns.user`. Otherwise it returns `403 Forbidden`. A function plug has to live in the controller that uses it, so copy it into yours and wire it up:
membership_controller.ex
```elixir defmodule PetalProApi.MembershipController do use PetalProWeb, :controller alias PetalPro.Accounts alias PetalPro.Accounts.Permissions alias PetalPro.Orgs action_fallback PetalProWeb.FallbackController plug :match_current_user def list(conn, _params) do org_names = conn.assigns.user |> Orgs.list_orgs() |> Enum.map(& &1.name) json(conn, org_names) end def match_current_user(conn, _params) do user_id = conn.params["id"] user = Accounts.get_user!(user_id) current_user = conn.assigns.current_user if current_user.id == user_id || Permissions.can_access_user_profiles?(current_user) do assign(conn, :user, user) else conn |> put_status(:forbidden) |> put_view(html: PetalProWeb.ErrorHTML, json: PetalProWeb.ErrorJSON) |> render(:"403") |> halt() end end end ``` The `list` function now reads the user from `conn.assigns.user` instead of looking it up from the URL — by the time the action runs, the plug has already validated and set it. Add tests for the authorization logic: ```elixir setup %{conn: conn} do user = PetalPro.AccountsFixtures.confirmed_user_fixture() other_user = PetalPro.AccountsFixtures.confirmed_user_fixture() admin_user = PetalPro.AccountsFixtures.admin_fixture() org = PetalPro.OrgsFixtures.org_fixture(user) {:ok, conn: put_req_header(conn, "accept", "application/json"), user: user, other_user: other_user, admin_user: admin_user, org: org} end describe "list" do test "user can fetch their own orgs", %{conn: conn, user: user} do conn = conn |> put_bearer_token(user) |> get(~p"/api/user/#{user.id}/orgs") assert json_response(conn, 200) end test "user cannot fetch another user's orgs", %{conn: conn, other_user: other, user: user} do conn = conn |> put_bearer_token(other) |> get(~p"/api/user/#{user.id}/orgs") assert json_response(conn, 403) end test "admin can fetch any user's orgs", %{conn: conn, admin_user: admin, user: user} do conn = conn |> put_bearer_token(admin) |> get(~p"/api/user/#{user.id}/orgs") assert json_response(conn, 200) end end ``` All three pass. The endpoint is now correctly authenticated *and* authorized. ## Adding it to the OpenAPI spec Your endpoint works, but it doesn't show up in the Swagger UI yet. Petal Pro uses [OpenApiSpex](https://github.com/open-api-spex/open_api_spex) — you describe each endpoint with metadata in the controller. In `membership_controller.ex` add: ```elixir defmodule PetalProApi.MembershipController do use PetalProWeb, :controller use OpenApiSpex.ControllerSpecs alias OpenApiSpex.Reference alias OpenApiSpex.Schema alias PetalPro.Accounts alias PetalPro.Accounts.Permissions alias PetalPro.Orgs action_fallback PetalProWeb.FallbackController plug :match_current_user tags(["Memberships"]) security([%{"authorization" => []}]) operation(:list, summary: "List user's organizations", description: "Returns the names of all organizations the user belongs to.", parameters: [ id: [in: :path, type: :string, description: "User ID", required: true] ], responses: [ ok: {"List of organization names", "application/json", OrganisationNames}, unauthorized: %Reference{"$ref": "#/components/responses/unauthorised"}, forbidden: %Reference{"$ref": "#/components/responses/forbidden"} ] ) def list(conn, _params) do org_names = conn.assigns.user |> Orgs.list_orgs() |> Enum.map(& &1.name) json(conn, org_names) end def match_current_user(conn, _params) do user_id = conn.params["id"] user = Accounts.get_user!(user_id) current_user = conn.assigns.current_user if current_user.id == user_id || Permissions.can_access_user_profiles?(current_user) do assign(conn, :user, user) else conn |> put_status(:forbidden) |> put_view(html: PetalProWeb.ErrorHTML, json: PetalProWeb.ErrorJSON) |> render(:"403") |> halt() end end end ``` A quick walk-through of what each piece does: - `tags(["Memberships"])` groups this controller's endpoints under "Memberships" in the Swagger UI - `security([%{"authorization" => []}])` tells OpenAPI that endpoints here use bearer auth (the `"authorization"` key references a `securityScheme` defined in `lib/petal_pro_api/api_spec.ex`) - `operation(:list, ...)` describes the `list` action — its summary, parameters, and possible responses Now define the response schema. Add to `lib/petal_pro_api/schemas.ex`:
schemas.ex
```elixir defmodule OrganisationNames do alias OpenApiSpex.Schema OpenApiSpex.schema(%{ title: "OrganisationNames", description: "List of organisation names for a user", type: :array, items: %Schema{description: "name", type: :string}, example: ["Acme Inc", "Globex Corp"] }) end ``` That's it. Restart the server, refresh `/dev/swaggerui`, and your endpoint shows up under "Memberships" with full documentation, the padlock indicating it requires auth, and an interactive request form. --- # Content Editor Plugin # Source: https://petal.build/petal-pro/guides/content-editor-adding-your-own-plug-in # Content Editor — adding your own plug-in Adding an Editor.js plug-in to Petal Pro and wiring up the renderer. ## Introduction The [Content Editor component](https://petal.build/components/content-editor) wraps [Editor.js](https://editorjs.io/), which is plug-in based. Petal Pro ships with a [set of plug-ins](/petal-pro/fundamentals/blog-cms#pre-installed-editor-js-plug-ins) for the common stuff — text, lists, tables, images, etc. When you want to add your own plug-in, there are two pieces: 1. The plug-in itself (a JavaScript class) 2. An update to the Petal Pro renderer so it knows how to display the data your plug-in produces Both are easier than they look. ## What we'll build A Markdown plug-in. Requirements: - User pastes markdown into a textarea inside the editor - The markdown is stored as-is in the Editor.js JSON - When the post is rendered, the markdown is converted to HTML using [Earmark](https://hexdocs.pm/earmark) If you'd rather skip the manual steps, drop this into Claude Code: ``` Add a custom Editor.js plug-in for Markdown. The plug-in should let users paste markdown into a textarea, save it as-is in the editor JSON, and render it as HTML using Earmark. Wire it into the Content Editor renderer. ``` The rest of this guide is the same flow, manually. ## Folder layout The relevant files for Editor.js in Petal Pro: ``` ├── assets │ ├── css │ │ └── editorjs.css │ ├── js │ │ ├── editorjs │ │ │ └── petal-image.js # Built-in plug-in for File Browser │ │ └── hooks │ │ └── editorjs-hook.js # The Phoenix LiveView hook │ └── package.json # Where you install Editor.js plug-ins └── lib └── petal_pro_web └── components └── pro_components └── content_editor.ex # Component + renderer ``` Your new plug-in will sit alongside `petal-image.js`. ## Build the plug-in Create `assets/js/editorjs/petal-markdown.js`:
petal-markdown.js
```javascript export default class PetalMarkdown { static get toolbox() { return { title: "Markdown", icon: '', }; } constructor({ data, block }) { this.data = data; this.block = block; this.wrapper = undefined; } render() { this.wrapper = document.createElement("div"); const markdown_input = document.createElement("textarea"); markdown_input.placeholder = "Paste your markdown here..."; markdown_input.value = this.data.markdown || ""; markdown_input.classList.add("petal-markdown"); this.wrapper.append(markdown_input); return this.wrapper; } save(blockContent) { const markdown_input = blockContent.querySelector("textarea"); return { markdown: markdown_input ? markdown_input.value : "", }; } } ``` Three methods worth understanding: - **`toolbox()`** — Defines what shows up in the "+" block menu inside the editor. Title and icon. - **`render()`** — Returns the DOM the user interacts with. Here, just a textarea. - **`save()`** — Returns the data structure to persist into the editor's JSON output. We save the raw markdown. ## Style the textarea Add to `assets/css/editorjs.css`:
editorjs.css
```css .codex-editor textarea.petal-markdown { @apply w-full rounded-md min-h-32 bg-gray-100 dark:bg-gray-950 dark:text-gray-400 border-gray-200 dark:border-gray-600 ring-0; } ``` ## Register it in the hook In `assets/js/hooks/editorjs-hook.js`, import the plug-in and add it to the `tools` config:
editorjs-hook.js
```javascript import EditorJS from "@editorjs/editorjs"; import PetalMarkdown from "../editorjs/petal-markdown"; // add this const EditorJsHook = { mounted() { this.editor = new EditorJS({ tools: { petalMarkdown: PetalMarkdown, // add this // ... other tools }, }); }, }; export default EditorJsHook; ``` Reload your editor, click the "+" button, pick **Markdown**, and a textarea appears. Type or paste markdown into it. The first two requirements are done — the plug-in works inside the editor and saves data correctly. ## Update the renderer Now we need Petal Pro to actually render the markdown as HTML when displaying a post. Open `lib/petal_pro_web/components/pro_components/content_editor.ex`. You'll find a `content/1` function that decodes the JSON and dispatches each block to a `block/1` function: ```elixir attr :json, :string, required: true def content(assigns) do json_object = decode_json(assigns.json) blocks = case json_object do %{"blocks" => blocks} -> MapExt.atomize_keys(blocks) _ -> [] end assigns = assign(assigns, :blocks, blocks) ~H""" <.block :for={block <- @blocks} block={block} /> """ end ``` `block/1` uses pattern matching to render different block types. Add a clause for our plug-in *above* the catch-all:
content_editor.ex
```elixir defp block(%{block: %{type: "petalMarkdown", data: %{markdown: markdown}}} = assigns) do assigns = assign(assigns, :markdown, markdown) ~H""" """ end # Catch-all (must come after the specific clauses) defp block(assigns) do ~H"" end ``` `PetalProWeb.Markdown.pretty_markdown/1` uses Earmark under the hood. That's the third requirement done — markdown saved by your plug-in now renders as styled HTML on the public side. ## Installing third-party plug-ins To use one of the [community plug-ins](https://github.com/editor-js/awesome-editorjs), install it via npm: ```shell cd assets npm add @editorjs/checklist ``` Then register it in `editorjs-hook.js` the same way as our custom plug-in: ```javascript import Checklist from "@editorjs/checklist"; // In tools: checklist: { class: Checklist, inlineToolbar: true, } ``` And add a `block/1` clause in `content_editor.ex` to render whatever data structure the plug-in saves. Each plug-in's docs tell you the shape of its output JSON.