From a679f8bb9e9b77c976b8b83c16e7ce0ec4251b5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Ogle?= Date: Sat, 28 Nov 2026 13:23:17 -0500 Subject: [PATCH 01/15] docs: add governance task pool and progress log Records the architecture scan findings and the baseline, so each refactoring round can be tracked against them. --- docs/governance/PROGRESS.md | 16 ++++++++++++++ docs/governance/TASKS.md | 43 +++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 docs/governance/PROGRESS.md create mode 100644 docs/governance/TASKS.md diff --git a/docs/governance/PROGRESS.md b/docs/governance/PROGRESS.md new file mode 100644 index 0000000..4c3c489 --- /dev/null +++ b/docs/governance/PROGRESS.md @@ -0,0 +1,16 @@ +# Governance Progress Log + +Branch: `andre/architecture-governance`. One entry per round. Each round +ends with `mix precommit` green and its own commit. + +## Baseline (2026-11-28) + +- `mix precommit`: green. 250 ExUnit tests (15 doctests), 11 node unit tests, + Biome strict, tsc, credo strict + ExSlop, `i18n.check`, `routes.gen --check`. +- Scan covered: every module under `lib/`, `assets/js/`, `assets/build/`, + config, CI workflow, scripts, test support. Findings in `TASKS.md`. +- Overall: low entropy. The template already enforces most rules (Biome + `preset: all`, credo strict, generated routes and page registries, i18n + parity). Remaining entropy is concentrated in cross-cutting concepts that + are spread over several modules (locale, safe redirects, session key) and + in repeated form markup on the frontend. diff --git a/docs/governance/TASKS.md b/docs/governance/TASKS.md new file mode 100644 index 0000000..909e2f7 --- /dev/null +++ b/docs/governance/TASKS.md @@ -0,0 +1,43 @@ +# Governance Task Pool + +Findings from the architecture scan, ranked by value. Status: `todo`, +`done` (with commit subject), `pending` (needs a product or architecture +decision — see the bottom section), `rejected` (with the reason). + +## Backend + +| # | Finding | Fix | Status | +| --- | --- | --- | --- | +| B1 | Three "safe redirect" implementations with different strictness: `UserAuth.local_path?/1` rejects `//`, `\`, tabs, newlines; `LocaleController.safe_referer/1` and `FallbackController.referer_path/1` only check for a leading `/` | One `ElixirReactStarterWeb.LocalPath` module; all three callers use it | todo | +| B2 | Locale concept spread over five modules: `:supported_locales` read by `User`, `UserAuth`, `LocaleController`; `"en"` fallback hardcoded in `SharedData`; `"locale"` cookie written by `LocaleController`, read by `UserAuth`; locale resolution lives inside the auth plug | `ElixirReactStarter.Locale` (list, default, guard) + `Plugs.Locale` (resolution, cookie) | todo | +| B3 | `SharedData.serialize_user/1` is an ad-hoc serializer, against the `*_json.ex` rule | `UserJSON.data/1` | todo | +| B4 | `SettingsController` writes the `"user_token"` session key itself; `UserAuth` owns it | `UserAuth.renew_user_session/2`, used by `log_in_user/2`, `SettingsController`, `ConnCase` | todo | +| B5 | Link-token contexts are free strings; a typo issues a token no verifier accepts. `UserToken` builds link tokens in two near-identical functions and repeats the hash 5 times | Guard contexts against a closed list; one link-token builder; one `hash/1` | todo | +| B6 | Mail delivery: `Email.x(...) \|> Mailer.deliver()` inline in two controllers, with the "fire and forget" rule stated once in a private helper; `Email` logs "Sending …" at build time, before (and regardless of) delivery | `Email.deliver/1` wrapper owning delivery + logging | todo | +| B7 | `AuthController` repeats the "invalid or expired reset link" redirect three times; `SettingsController` repeats the email-change failure redirect twice | One private helper per controller | todo | +| B8 | `FallbackController` clauses for `:unauthorized`, `:bad_request`, `:not_found`, changeset have no producer in the app today | Keep: they pair with `Context`'s `*_ok` functions and are the template's documented extension point | rejected | + +## Frontend + +| # | Finding | Fix | Status | +| --- | --- | --- | --- | +| F1 | The label + input + error triad is hand-written 11 times across 6 pages. Errors are not linked to inputs (`aria-invalid`, `aria-describedby` missing), against the a11y rule | `components/TextField.tsx`; migrate every page; delete `components/ui.ts` | todo | +| F2 | `LocaleSelector` hand-rolls a `ChevronDown` SVG (lucide ships one, `AppLayout` uses it) and has an untranslated `aria-label="Change language"` | Use lucide `ChevronDown`; `t('common.changeLanguage')` | todo | +| F3 | Frontend locale list exists twice: `i18n/index.ts` resources and `LocaleSelector`'s list | Low value — `mix i18n.check` already catches locale-file drift | todo | +| F4 | `components/syncLocale.ts` is not a component (rule: `components/` holds UI primitives) | Move to `i18n/syncLocale.ts` | todo | + +## Tooling / enforcement + +| # | Finding | Fix | Status | +| --- | --- | --- | --- | +| T1 | Layering rules (domain never depends on web; controllers never touch `Repo`) are unwritten and unchecked | `test/architecture_test.exs` (AST-based) | todo | +| T2 | No machine check that pages use `TextField` instead of raw inputs | Architecture contract test | todo | +| T3 | No architecture map for agents to find owners of a concept | `docs/architecture.md` | todo | + +## Pending confirmation (product / breaking decisions) + +| # | Item | Why it waits | +| --- | --- | --- | +| P1 | Unused shipped code: `ElixirReactStarter.Timezones`, `components/TimezoneSelect.tsx`, `components/Select.tsx`, `components/Spinner.tsx`, `assets/js/dates.ts` have no callers | `AGENTS.md` lists `Select`/`Spinner` as shipped primitives of the template. Deleting is a product call: keep them as starter kit, or delete until a project needs them | +| P2 | SSR Sentry config (`ssr.tsx`) re-derives environment/release from env vars (`DEPLOY_ENV`, `SENTRY_RELEASE`, `RENDER_GIT_COMMIT`) with the same defaults as `config/runtime.exs` | Two runtimes (BEAM, Node) read the same env; unifying needs the Node pool to receive config from Elixir — a deploy-contract change | +| P3 | `Accounts` context mixes six flows in one 340-line module | Fine at today's size. Split (e.g. `Accounts.Sessions`) only when a project adds flows; splitting now adds forwarding layers | From af9c9475f68dc50cd9ef4d2272cdf51ac9065480 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Ogle?= Date: Sat, 28 Nov 2026 13:24:57 -0500 Subject: [PATCH 02/15] refactor: route every redirect check through LocalPath UserAuth, LocaleController and FallbackController each validated user-controlled redirect targets with their own rules. The two referer-based ones accepted protocol-relative paths (//host), which made Phoenix raise instead of falling back to /. LocalPath is now the single implementation. test/architecture_test.exs pins it, along with the domain/web and Repo layering rules (ADR 0001). --- ...001-enforce-architecture-with-ast-tests.md | 35 ++++++++ docs/architecture.md | 78 ++++++++++++++++ docs/governance/PROGRESS.md | 13 +++ docs/governance/TASKS.md | 4 +- .../controllers/fallback_controller.ex | 15 +--- .../controllers/locale_controller.ex | 12 +-- lib/elixir_react_starter_web/local_path.ex | 48 ++++++++++ .../plugs/user_auth.ex | 17 +--- test/architecture_test.exs | 88 +++++++++++++++++++ .../local_path_test.exs | 52 +++++++++++ 10 files changed, 324 insertions(+), 38 deletions(-) create mode 100644 docs/adr/0001-enforce-architecture-with-ast-tests.md create mode 100644 docs/architecture.md create mode 100644 lib/elixir_react_starter_web/local_path.ex create mode 100644 test/architecture_test.exs create mode 100644 test/elixir_react_starter_web/local_path_test.exs diff --git a/docs/adr/0001-enforce-architecture-with-ast-tests.md b/docs/adr/0001-enforce-architecture-with-ast-tests.md new file mode 100644 index 0000000..740dd89 --- /dev/null +++ b/docs/adr/0001-enforce-architecture-with-ast-tests.md @@ -0,0 +1,35 @@ +# ADR 0001: Enforce architecture rules with AST-based tests + +Status: accepted (2026-11-28) + +## Context + +The template documents its boundaries in `AGENTS.md`, but most of them are +checked only by review. Agents working in parallel reintroduce removed +patterns (a second redirect validator, a controller calling `Repo`) because +nothing fails when they do. + +Options considered: + +1. Custom Credo checks — idiomatic, but each rule needs a module with + Credo's check API, and Credo runs on `lib/` with its own config surface. +2. `boundary` (hex library) — strong layering, but adds a compiler and a + dependency for two layers. +3. One ExUnit file that parses source files and asserts rules over the AST. + +## Decision + +Option 3: `test/architecture_test.exs`. It runs in `mix test` (so in +`mix precommit` and CI) with no new dependency. Each rule is one test that +names its exceptions by path with the reason inline. Checks read the AST, so +comments and prose never trigger them. + +Frontend rules use Biome (`assets/biome.jsonc`) where a lint rule exists, and +the node contract tests (`npm run test:unit`) where none does. + +## Consequences + +- Adding a rule is a few lines; removing an exception shows up in review. +- The checks are syntactic. They catch aliases and literals, not dynamic + module references — acceptable, since the codebase never builds module + names at runtime outside the `Context` macro. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..fdd7dfc --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,78 @@ +# Architecture Map + +How the template is put together: which module owns which concept, which way +dependencies point, and where each rule lives. Read this before adding a +feature, so the change lands in the module that already owns the concept. + +Conventions and critical invariants live in `AGENTS.md` (`CLAUDE.md` is a +symlink to it). Decisions behind the structure are in `docs/adr/`. The running +governance log is in `docs/governance/`. + +## Layers and dependency direction + +``` +assets/js (React pages, layouts, components) + │ Inertia props (JSON) · routes.ts (generated from the router) + ▼ +ElixirReactStarterWeb (router, plugs, controllers, channels, emails, *_json views) + │ calls context functions; never touches Repo or schemas' queries directly + ▼ +ElixirReactStarter (contexts: Accounts · shared infra: Locale, Log, RateLimit, Ecto.*) + │ + ▼ +Repo / Postgres · Oban · Swoosh adapter · Sentry +``` + +Rules (enforced by `test/architecture_test.exs` where noted): + +- `ElixirReactStarter.*` never references `ElixirReactStarterWeb.*`, except + `Gettext` for translating changeset error messages. *(enforced)* +- Controllers call contexts, not `Repo`. *(enforced)* +- The frontend reaches the server only through Inertia props, `routes.ts`, and + the realtime socket. It has no knowledge of server modules. + +## Ownership map + +| Concept | Owner (single source of truth) | Consumers | +| --- | --- | --- | +| User record, password hashing, validation | `Accounts.User` | `Accounts` | +| Token shapes, hashing, expiry windows | `Accounts.UserToken` | `Accounts` | +| Account flows (register, confirm, reset, change email/password, delete) | `Accounts` | `AuthController`, `SettingsController`, `E2EFixtures` | +| Session cookie, log in/out, auth gates | `ElixirReactStarterWeb.UserAuth` | router, controllers, `ConnCase` | +| Supported / default locales | `ElixirReactStarter.Locale` (reads `:supported_locales`, `:default_locale`) | `User`, `Plugs.Locale`, `LocaleController`, `SharedData` | +| Request-locale resolution + `locale` cookie | `ElixirReactStarterWeb.Plugs.Locale` | router, `LocaleController` | +| Safe redirect targets (`Referer`, return-to) | `ElixirReactStarterWeb.LocalPath` | `UserAuth`, `LocaleController`, `FallbackController` | +| User wire shape sent to the frontend | `ElixirReactStarterWeb.UserJSON` | `Plugs.SharedData` | +| Shared Inertia props | `Plugs.SharedData` | every page (`types/inertia.d.ts` mirrors it) | +| Transactional email content | `ElixirReactStarterWeb.Email` + `email_html/` / `email_text/` templates | controllers | +| Rate limits | `Plugs.RateLimit` (backed by `ElixirReactStarter.RateLimit`) | `AuthController` | +| CSP | `Plugs.ContentSecurityPolicy` (+ `:csp_extra_sources`) | router `:csp` pipeline | +| Client IP behind proxies | `Plugs.ClientIp` | endpoint | +| Frontend URLs | `assets/js/routes.ts`, generated by `mix routes.gen` | all pages/components | +| Page registries | `_pages.ts` / `_ssr_pages.ts`, generated by `build/generate-ssr-pages.cjs` | `app.tsx`, `ssr.tsx` | +| Form fields (label, input, error, a11y wiring) | `components/TextField.tsx` | pages | +| Async error handling | `assets/js/result.ts` (`go`, `goSync`) | all frontend code | +| Toasts | `components/toast.ts` (store) + `Toaster.tsx` (view) | `app.tsx` flash bridge | +| Theme | `assets/js/theme.ts` + inline bootstrap in `root.html.heex` | `ThemeToggle` | +| Realtime | `UserSocket` / channels ↔ `assets/js/realtime/` | `AppProviders` | +| Translations | `priv/gettext` (server), `assets/js/i18n/locales/*.ts` (client); parity checked by `mix i18n.check` | everything user-facing | +| Toolchain versions | `mise.toml` | CI, `scripts/check-tool-versions.sh` | + +## Request lifecycle (browser) + +`Endpoint` → `Plugs.ClientIp` → `Router :browser` (session, CSRF, `Inertia.Plug`, +`UserAuth.fetch_current_user`, `Plugs.Locale`, `Plugs.SharedData`) → `:csp` → +optional auth gate (`require_authenticated_user` / `redirect_if_user_is_authenticated`) +→ controller → `render_inertia` (SSR via `Inertia.SSR` Node pool for `pages/ssr/*`) +or `redirect` (validation errors travel via `assign_errors` + session). + +## Where new things go + +- New domain concept → a context module (`use ElixirReactStarter.Context`) plus + schema plus factory in `test/support/factories/`. +- New wire shape → `lib/elixir_react_starter_web/controllers/_json.ex`. +- New page → `assets/js/pages/ssr/` (public) or `pages/client/` (authenticated). +- New form input → `TextField`; new interactive widget → a Radix wrapper in + `assets/js/components/`. +- New architectural rule → a test in `test/architecture_test.exs` (Elixir) or a + Biome rule (`assets/biome.jsonc`) so it can't regress. diff --git a/docs/governance/PROGRESS.md b/docs/governance/PROGRESS.md index 4c3c489..9a9cb2c 100644 --- a/docs/governance/PROGRESS.md +++ b/docs/governance/PROGRESS.md @@ -14,3 +14,16 @@ ends with `mix precommit` green and its own commit. parity). Remaining entropy is concentrated in cross-cutting concepts that are spread over several modules (locale, safe redirects, session key) and in repeated form markup on the frontend. + +## Round 1 — safe redirects (B1, T1) + +- Added `ElixirReactStarterWeb.LocalPath` (`local?/1`, `referer/1`). Migrated + `UserAuth`, `LocaleController`, `FallbackController`; deleted their three + private validators. +- Behaviour change (security fix): the two referer-based redirects used to + accept `//host/...` paths, which made Phoenix raise (500). They now fall + back to `/` like any other non-local referer. +- Added `test/architecture_test.exs` with three rules: domain never + references web (except Gettext), web never touches `Repo` (except the + readiness probe), only `LocalPath` reads `Referer`. ADR 0001. +- Verified: rules fail when their exceptions are removed. `mix precommit` green. diff --git a/docs/governance/TASKS.md b/docs/governance/TASKS.md index 909e2f7..3beeef3 100644 --- a/docs/governance/TASKS.md +++ b/docs/governance/TASKS.md @@ -8,7 +8,7 @@ decision — see the bottom section), `rejected` (with the reason). | # | Finding | Fix | Status | | --- | --- | --- | --- | -| B1 | Three "safe redirect" implementations with different strictness: `UserAuth.local_path?/1` rejects `//`, `\`, tabs, newlines; `LocaleController.safe_referer/1` and `FallbackController.referer_path/1` only check for a leading `/` | One `ElixirReactStarterWeb.LocalPath` module; all three callers use it | todo | +| B1 | Three "safe redirect" implementations with different strictness: `UserAuth.local_path?/1` rejects `//`, `\`, tabs, newlines; `LocaleController.safe_referer/1` and `FallbackController.referer_path/1` only check for a leading `/` | One `ElixirReactStarterWeb.LocalPath` module; all three callers use it | done — `refactor: route every redirect check through LocalPath` | | B2 | Locale concept spread over five modules: `:supported_locales` read by `User`, `UserAuth`, `LocaleController`; `"en"` fallback hardcoded in `SharedData`; `"locale"` cookie written by `LocaleController`, read by `UserAuth`; locale resolution lives inside the auth plug | `ElixirReactStarter.Locale` (list, default, guard) + `Plugs.Locale` (resolution, cookie) | todo | | B3 | `SharedData.serialize_user/1` is an ad-hoc serializer, against the `*_json.ex` rule | `UserJSON.data/1` | todo | | B4 | `SettingsController` writes the `"user_token"` session key itself; `UserAuth` owns it | `UserAuth.renew_user_session/2`, used by `log_in_user/2`, `SettingsController`, `ConnCase` | todo | @@ -30,7 +30,7 @@ decision — see the bottom section), `rejected` (with the reason). | # | Finding | Fix | Status | | --- | --- | --- | --- | -| T1 | Layering rules (domain never depends on web; controllers never touch `Repo`) are unwritten and unchecked | `test/architecture_test.exs` (AST-based) | todo | +| T1 | Layering rules (domain never depends on web; controllers never touch `Repo`) are unwritten and unchecked | `test/architecture_test.exs` (AST-based), ADR 0001 | done — same commit as B1 | | T2 | No machine check that pages use `TextField` instead of raw inputs | Architecture contract test | todo | | T3 | No architecture map for agents to find owners of a concept | `docs/architecture.md` | todo | diff --git a/lib/elixir_react_starter_web/controllers/fallback_controller.ex b/lib/elixir_react_starter_web/controllers/fallback_controller.ex index ffc927b..ee27f03 100644 --- a/lib/elixir_react_starter_web/controllers/fallback_controller.ex +++ b/lib/elixir_react_starter_web/controllers/fallback_controller.ex @@ -8,10 +8,12 @@ defmodule ElixirReactStarterWeb.FallbackController do use ElixirReactStarterWeb, :controller + alias ElixirReactStarterWeb.LocalPath + def call(conn, {:error, %Ecto.Changeset{} = changeset}) do # Per CLAUDE.md, validation errors should redirect — this fallback # only fires when the action forgot to handle it explicitly. - back = referer_path(conn) || ~p"/" + back = LocalPath.referer(conn) || ~p"/" conn |> assign_errors(changeset) @@ -42,15 +44,4 @@ defmodule ElixirReactStarterWeb.FallbackController do |> put_flash(:error, message) |> redirect(to: ~p"/") end - - # Trust only same-host paths starting with `/` (see CLAUDE.md security - # rules on user-controlled redirect targets). - defp referer_path(conn) do - with [referer | _] <- get_req_header(conn, "referer"), - %URI{path: "/" <> _ = path} <- URI.parse(referer) do - path - else - _ -> nil - end - end end diff --git a/lib/elixir_react_starter_web/controllers/locale_controller.ex b/lib/elixir_react_starter_web/controllers/locale_controller.ex index 12dfd49..60f645f 100644 --- a/lib/elixir_react_starter_web/controllers/locale_controller.ex +++ b/lib/elixir_react_starter_web/controllers/locale_controller.ex @@ -17,6 +17,7 @@ defmodule ElixirReactStarterWeb.LocaleController do use ElixirReactStarterWeb, :controller alias ElixirReactStarter.Accounts + alias ElixirReactStarterWeb.LocalPath action_fallback ElixirReactStarterWeb.FallbackController @@ -33,7 +34,7 @@ defmodule ElixirReactStarterWeb.LocaleController do http_only: false, same_site: "Lax" ) - |> redirect(to: safe_referer(List.first(get_req_header(conn, "referer")))) + |> redirect(to: LocalPath.referer(conn) || ~p"/") {:error, _changeset} -> {:error, {:bad_request, dgettext("app", "Unsupported locale")}} @@ -52,13 +53,4 @@ defmodule ElixirReactStarterWeb.LocaleController do {:error, changeset} -> {:error, changeset} end end - - defp safe_referer(nil), do: ~p"/" - - defp safe_referer(referer) do - case URI.parse(referer) do - %URI{path: "/" <> _ = path} -> path - _ -> ~p"/" - end - end end diff --git a/lib/elixir_react_starter_web/local_path.ex b/lib/elixir_react_starter_web/local_path.ex new file mode 100644 index 0000000..005fd32 --- /dev/null +++ b/lib/elixir_react_starter_web/local_path.ex @@ -0,0 +1,48 @@ +defmodule ElixirReactStarterWeb.LocalPath do + @moduledoc """ + The one place that decides whether a user-controlled value is safe to + redirect to. Every redirect whose target comes from the request (the + `Referer` header, a stored return-to path) goes through here, so the + open-redirect defence has a single implementation. + + A target is local when it starts with `/` but not `//` (a + protocol-relative URL such as `//evil.com/x` names another host), and it + holds none of the characters a browser strips or treats as a separator + (`\\`, tab, newline). + """ + + import Plug.Conn, only: [get_req_header: 2] + + @doc """ + True when `path` is a same-origin path that is safe to redirect to. + + iex> ElixirReactStarterWeb.LocalPath.local?("/settings?tab=email") + true + + iex> ElixirReactStarterWeb.LocalPath.local?("//evil.com/settings") + false + + iex> ElixirReactStarterWeb.LocalPath.local?("https://evil.com") + false + """ + @spec local?(term()) :: boolean() + def local?("//" <> _), do: false + def local?("/" <> _ = path), do: not String.contains?(path, ["\\", "/%09", "/\t", "\n", "\r"]) + def local?(_), do: false + + @doc """ + The path of the request's `Referer` header when it is local, otherwise + `nil`. Only the path is kept: the host of the referer is ignored, so + the redirect always stays on this origin. + """ + @spec referer(Plug.Conn.t()) :: String.t() | nil + def referer(conn) do + with [referer | _] <- get_req_header(conn, "referer"), + %URI{path: path} <- URI.parse(referer), + true <- local?(path) do + path + else + _ -> nil + end + end +end diff --git a/lib/elixir_react_starter_web/plugs/user_auth.ex b/lib/elixir_react_starter_web/plugs/user_auth.ex index 4529f40..489b75f 100644 --- a/lib/elixir_react_starter_web/plugs/user_auth.ex +++ b/lib/elixir_react_starter_web/plugs/user_auth.ex @@ -40,6 +40,7 @@ defmodule ElixirReactStarterWeb.UserAuth do router: ElixirReactStarterWeb.Router alias ElixirReactStarter.Accounts + alias ElixirReactStarterWeb.LocalPath @session_key "user_token" # Where we stash the URL the user was trying to reach when we bounced @@ -122,23 +123,11 @@ defmodule ElixirReactStarterWeb.UserAuth do defp maybe_store_return_to(%Plug.Conn{method: "GET"} = conn) do path = current_path(conn) - if local_path?(path), do: put_session(conn, @return_to_key, path), else: conn + if LocalPath.local?(path), do: put_session(conn, @return_to_key, path), else: conn end defp maybe_store_return_to(conn), do: conn - # Local paths only: must start with "/" but not "//" (protocol-relative - # URLs like "//evil.com/path" parse as the host "evil.com", which the - # browser would treat as an external redirect). - defp local_path?("//" <> _), do: false - - defp local_path?("/" <> _ = path) do - # Reject characters a browser removes or reinterprets as URL separators. - not String.contains?(path, ["\\", "/%09", "/\t", "\n", "\r"]) - end - - defp local_path?(_), do: false - @doc """ Redirects authenticated users away from guest-only pages (login, register). @@ -167,7 +156,7 @@ defmodule ElixirReactStarterWeb.UserAuth do def log_in_user(conn, user) do token = Accounts.generate_user_session_token(user) return_to = get_session(conn, @return_to_key) - redirect_path = if local_path?(return_to), do: return_to, else: ~p"/dashboard" + redirect_path = if LocalPath.local?(return_to), do: return_to, else: ~p"/dashboard" conn |> renew_session() diff --git a/test/architecture_test.exs b/test/architecture_test.exs new file mode 100644 index 0000000..27470e8 --- /dev/null +++ b/test/architecture_test.exs @@ -0,0 +1,88 @@ +defmodule ElixirReactStarter.ArchitectureTest do + @moduledoc """ + Machine-checked architecture rules. Each test pins one boundary from + `docs/architecture.md` so a later change can't quietly reintroduce what a + refactor removed. The checks walk the source AST (comments and docs never + count), and every exception is listed by path with its reason. + """ + + use ExUnit.Case, async: true + + @domain_files "lib/elixir_react_starter/**/*.ex" + @web_files "lib/elixir_react_starter_web/**/*.ex" + + test "the domain layer never depends on the web layer" do + # application.ex is the composition root: it starts the Endpoint. + # Gettext is the translation backend that changeset messages use. + offenders = + for path <- files(@domain_files, except: ["lib/elixir_react_starter/application.ex"]), + [:ElixirReactStarterWeb | rest] <- aliases(path), + rest != [:Gettext], + uniq: true, + do: "#{path}: #{inspect(Module.concat([ElixirReactStarterWeb | rest]))}" + + assert offenders == [], + "domain modules reference the web layer:\n" <> Enum.join(offenders, "\n") + end + + test "web modules reach the database only through contexts" do + # The readiness probe checks the pool itself, below any context. + offenders = + for path <- + files(@web_files, + except: ["lib/elixir_react_starter_web/controllers/health_controller.ex"] + ), + segments <- aliases(path), + match?([:Repo], segments) or match?([:ElixirReactStarter, :Repo], segments), + uniq: true, + do: path + + assert offenders == [], "web modules use Repo directly:\n" <> Enum.join(offenders, "\n") + end + + test "only LocalPath reads the Referer header" do + offenders = + for path <- files(@web_files, except: ["lib/elixir_react_starter_web/local_path.ex"]), + "referer" in strings(path), + do: path + + assert offenders == [], + "validate redirect targets with ElixirReactStarterWeb.LocalPath:\n" <> + Enum.join(offenders, "\n") + end + + # --------------------------------------------------------------------------- + # AST helpers + # --------------------------------------------------------------------------- + defp files(glob, except: excluded), do: Path.wildcard(glob) -- excluded + + defp ast(path), do: path |> File.read!() |> Code.string_to_quoted!(file: path) + + # Every alias written in the file (`Foo.Bar` → `[:Foo, :Bar]`). + defp aliases(path) do + collect(path, fn + {:__aliases__, _, segments} -> {:ok, segments} + _node -> :skip + end) + end + + # Every string literal in the file. + defp strings(path) do + collect(path, fn + string when is_binary(string) -> {:ok, string} + _node -> :skip + end) + end + + defp collect(path, picker) do + {_ast, found} = + Macro.prewalk(ast(path), [], fn node, acc -> + case picker.(node) do + {:ok, value} -> {node, [value | acc]} + :skip -> {node, acc} + end + end) + + found + end +end diff --git a/test/elixir_react_starter_web/local_path_test.exs b/test/elixir_react_starter_web/local_path_test.exs new file mode 100644 index 0000000..04eae72 --- /dev/null +++ b/test/elixir_react_starter_web/local_path_test.exs @@ -0,0 +1,52 @@ +defmodule ElixirReactStarterWeb.LocalPathTest do + use ExUnit.Case, async: true + + import Plug.Conn + import Plug.Test + + alias ElixirReactStarterWeb.LocalPath + + doctest LocalPath + + describe "local?/1" do + test "accepts same-origin paths" do + for path <- ["/", "/settings", "/a/b?c=d#e"] do + assert LocalPath.local?(path), path + end + end + + test "rejects anything that can leave the origin" do + for target <- [ + nil, + "", + "settings", + "https://evil.com", + "//evil.com", + "/\\evil.com", + "/%09/evil.com", + "/\t/evil.com", + "/a\nb", + "/a\rb" + ] do + refute LocalPath.local?(target), inspect(target) + end + end + end + + describe "referer/1" do + defp with_referer(referer), do: conn(:get, "/") |> put_req_header("referer", referer) + + test "returns the path of a referer, dropping its host and query" do + assert LocalPath.referer(with_referer("https://other.example/login?x=1")) == "/login" + end + + test "returns nil without a referer" do + assert LocalPath.referer(conn(:get, "/")) == nil + end + + test "returns nil for a referer without a local path" do + assert LocalPath.referer(with_referer("mailto:nobody@example.com")) == nil + assert LocalPath.referer(with_referer("https://example.com//evil.com/x")) == nil + end + end +end From ff6f05c7b54c045605d96e68a2a63da1f0233d19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Ogle?= Date: Sat, 28 Nov 2026 13:26:11 -0500 Subject: [PATCH 03/15] refactor: give the locale concept one owner per layer Supported locales were read from config in three modules, the default was hardcoded in two more, and request-locale resolution lived inside the auth plug while its cookie was written by LocaleController. ElixirReactStarter.Locale now owns the list and the default; Plugs.Locale owns resolution and the cookie. An architecture test keeps the config reads in one place. --- AGENTS.md | 5 +- docs/governance/PROGRESS.md | 14 ++++ docs/governance/TASKS.md | 2 +- lib/elixir_react_starter/accounts.ex | 2 +- lib/elixir_react_starter/accounts/user.ex | 12 +-- lib/elixir_react_starter/locale.ex | 25 +++++++ .../components/layouts/root.html.heex | 2 +- .../controllers/locale_controller.ex | 15 ++-- lib/elixir_react_starter_web/plugs/locale.ex | 73 +++++++++++++++++++ .../plugs/shared_data.ex | 8 +- .../plugs/user_auth.ex | 49 +------------ lib/elixir_react_starter_web/router.ex | 1 + test/architecture_test.exs | 24 ++++++ .../plugs/locale_test.exs | 68 +++++++++++++++++ .../plugs/user_auth_test.exs | 47 ------------ 15 files changed, 229 insertions(+), 118 deletions(-) create mode 100644 lib/elixir_react_starter/locale.ex create mode 100644 lib/elixir_react_starter_web/plugs/locale.ex create mode 100644 test/elixir_react_starter_web/plugs/locale_test.exs diff --git a/AGENTS.md b/AGENTS.md index 9df83d2..9024cdf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -129,8 +129,9 @@ The template already includes these — extend them, don't rebuild them. **Realtime** (`ElixirReactStarterWeb.{UserSocket, GlobalChannel, UserChannel}` + `assets/js/realtime/`) - Token-authed socket at `/socket`. The provider (mounted in `app-providers.tsx`) auto-joins `global` and `user:` and survives Inertia navigation (keyed on user id, not the rotating token). Hooks: `useConnectionStatus`, `useGlobalChannel`, `useUserChannel`, `useChannel`, `use{Global,User}Event`, `pushChannel` -**Locale** (`ElixirReactStarterWeb.LocaleController`, `PUT /locale`) -- Precedence: `user.locale` (authed) → `locale` cookie (anonymous, 1-year) → `Accept-Language` → `:default_locale`. The public endpoint sets the cookie and, when signed in, also writes `user.locale`. Frontend strings go through `react-i18next` (`useTranslation`); locale files are `assets/js/i18n/locales/{en,es}.ts` +**Locale** (`ElixirReactStarter.Locale`, `ElixirReactStarterWeb.Plugs.Locale`, `LocaleController` at `PUT /locale`) +- `ElixirReactStarter.Locale` is the only reader of `:supported_locales` / `:default_locale` (`supported/0`, `default/0`, guard `is_supported/1`); an architecture test enforces it. +- `Plugs.Locale` resolves the request locale with precedence `user.locale` (authed) → `locale` cookie (anonymous, 1-year) → `Accept-Language` → default, and owns the cookie (`put_cookie/2`). The public endpoint sets the cookie and, when signed in, also writes `user.locale`. Frontend strings go through `react-i18next` (`useTranslation`); locale files are `assets/js/i18n/locales/{en,es}.ts` **Theme** (`assets/js/theme.ts`, `ThemeToggle`) - light / dark / system, stored in a `theme` cookie. An inline bootstrap in `root.html.heex` applies the `dark` class before first paint (no flash). Dark mode is class-based (`@custom-variant dark`) diff --git a/docs/governance/PROGRESS.md b/docs/governance/PROGRESS.md index 9a9cb2c..9672354 100644 --- a/docs/governance/PROGRESS.md +++ b/docs/governance/PROGRESS.md @@ -27,3 +27,17 @@ ends with `mix precommit` green and its own commit. references web (except Gettext), web never touches `Repo` (except the readiness probe), only `LocalPath` reads `Referer`. ADR 0001. - Verified: rules fail when their exceptions are removed. `mix precommit` green. + +## Round 2 — locale (B2) + +- `ElixirReactStarter.Locale`: the only reader of `:supported_locales` and + `:default_locale` (`supported/0`, `default/0`, guard `is_supported/1`). + `User`, `LocaleController`, `SharedData`, root layout migrated; three + `compile_env` copies and two hardcoded `"en"` fallbacks deleted. +- `ElixirReactStarterWeb.Plugs.Locale`: request-locale resolution moved out of + `UserAuth` (auth plug now only does auth + Sentry user context); owns the + `locale` cookie name and lifetime (`put_cookie/2`). Router runs it right + after `fetch_current_user`. +- Locale precedence tests moved from `user_auth_test` to `plugs/locale_test` + (plus a no-supported-language case and a cookie-attributes case). +- New architecture rule: only `Locale` reads the locale config keys. diff --git a/docs/governance/TASKS.md b/docs/governance/TASKS.md index 3beeef3..d635dd3 100644 --- a/docs/governance/TASKS.md +++ b/docs/governance/TASKS.md @@ -9,7 +9,7 @@ decision — see the bottom section), `rejected` (with the reason). | # | Finding | Fix | Status | | --- | --- | --- | --- | | B1 | Three "safe redirect" implementations with different strictness: `UserAuth.local_path?/1` rejects `//`, `\`, tabs, newlines; `LocaleController.safe_referer/1` and `FallbackController.referer_path/1` only check for a leading `/` | One `ElixirReactStarterWeb.LocalPath` module; all three callers use it | done — `refactor: route every redirect check through LocalPath` | -| B2 | Locale concept spread over five modules: `:supported_locales` read by `User`, `UserAuth`, `LocaleController`; `"en"` fallback hardcoded in `SharedData`; `"locale"` cookie written by `LocaleController`, read by `UserAuth`; locale resolution lives inside the auth plug | `ElixirReactStarter.Locale` (list, default, guard) + `Plugs.Locale` (resolution, cookie) | todo | +| B2 | Locale concept spread over five modules: `:supported_locales` read by `User`, `UserAuth`, `LocaleController`; `"en"` fallback hardcoded in `SharedData`; `"locale"` cookie written by `LocaleController`, read by `UserAuth`; locale resolution lives inside the auth plug | `ElixirReactStarter.Locale` (list, default, guard) + `Plugs.Locale` (resolution, cookie) | done — `refactor: give the locale concept one owner per layer` | | B3 | `SharedData.serialize_user/1` is an ad-hoc serializer, against the `*_json.ex` rule | `UserJSON.data/1` | todo | | B4 | `SettingsController` writes the `"user_token"` session key itself; `UserAuth` owns it | `UserAuth.renew_user_session/2`, used by `log_in_user/2`, `SettingsController`, `ConnCase` | todo | | B5 | Link-token contexts are free strings; a typo issues a token no verifier accepts. `UserToken` builds link tokens in two near-identical functions and repeats the hash 5 times | Guard contexts against a closed list; one link-token builder; one `hash/1` | todo | diff --git a/lib/elixir_react_starter/accounts.ex b/lib/elixir_react_starter/accounts.ex index 375e008..3b199df 100644 --- a/lib/elixir_react_starter/accounts.ex +++ b/lib/elixir_react_starter/accounts.ex @@ -139,7 +139,7 @@ defmodule ElixirReactStarter.Accounts do # ============================================================================= @doc """ Updates the user's preferred locale. Rejects values that aren't in - `:supported_locales`. + `ElixirReactStarter.Locale.supported/0`. """ def update_user_locale(user, attrs) do user diff --git a/lib/elixir_react_starter/accounts/user.ex b/lib/elixir_react_starter/accounts/user.ex index 468f184..66c611c 100644 --- a/lib/elixir_react_starter/accounts/user.ex +++ b/lib/elixir_react_starter/accounts/user.ex @@ -13,18 +13,18 @@ defmodule ElixirReactStarter.Accounts.User do use Gettext, backend: ElixirReactStarterWeb.Gettext + alias ElixirReactStarter.Locale + @type t :: %__MODULE__{} @primary_key {:id, ElixirReactStarter.Ecto.UUIDv7, autogenerate: true} @foreign_key_type ElixirReactStarter.Ecto.UUIDv7 - @supported_locales Application.compile_env(:elixir_react_starter, :supported_locales, ["en"]) - schema "users" do field :email, :string, redact: true field :password, :string, virtual: true, redact: true field :hashed_password, :string, redact: true - field :locale, :string, default: "en" + field :locale, :string, default: Locale.default() field :confirmed_at, :utc_datetime timestamps(type: :utc_datetime) @@ -32,7 +32,7 @@ defmodule ElixirReactStarter.Accounts.User do @doc """ Changeset for creating a user with email and password. Locale is - optional; defaults to "en" via the schema. + optional; defaults to `ElixirReactStarter.Locale.default/0` via the schema. """ def registration_changeset(user, attrs) do user @@ -66,7 +66,7 @@ defmodule ElixirReactStarter.Accounts.User do @doc """ Changeset for updating only the locale. Rejects values that aren't - in `:supported_locales`. + in `ElixirReactStarter.Locale.supported/0`. """ def locale_changeset(user, attrs) do user @@ -121,7 +121,7 @@ defmodule ElixirReactStarter.Accounts.User do end defp validate_locale(changeset) do - validate_inclusion(changeset, :locale, @supported_locales, + validate_inclusion(changeset, :locale, Locale.supported(), message: dgettext("errors", "is not a supported locale") ) end diff --git a/lib/elixir_react_starter/locale.ex b/lib/elixir_react_starter/locale.ex new file mode 100644 index 0000000..d5f6a2f --- /dev/null +++ b/lib/elixir_react_starter/locale.ex @@ -0,0 +1,25 @@ +defmodule ElixirReactStarter.Locale do + @moduledoc """ + The locales the app speaks. Reads `:supported_locales` and + `:default_locale` from the application config — the only module that + does, so every other module asks here instead of keeping its own copy. + + Adding a locale: append it to `:supported_locales` in `config/config.exs`, + add `priv/gettext//` and `assets/js/i18n/locales/.ts`, then + run `mix i18n.check`. + """ + + @supported Application.compile_env(:elixir_react_starter, :supported_locales, ["en"]) + @default Application.compile_env(:elixir_react_starter, :default_locale, "en") + + @doc "Every supported locale code." + @spec supported() :: [String.t(), ...] + def supported, do: @supported + + @doc "The locale used when nothing else decides." + @spec default() :: String.t() + def default, do: @default + + @doc "Guard: true when `locale` is a supported locale code." + defguard is_supported(locale) when locale in @supported +end diff --git a/lib/elixir_react_starter_web/components/layouts/root.html.heex b/lib/elixir_react_starter_web/components/layouts/root.html.heex index a1a0851..6b5aa41 100644 --- a/lib/elixir_react_starter_web/components/layouts/root.html.heex +++ b/lib/elixir_react_starter_web/components/layouts/root.html.heex @@ -1,5 +1,5 @@ - + diff --git a/lib/elixir_react_starter_web/controllers/locale_controller.ex b/lib/elixir_react_starter_web/controllers/locale_controller.ex index 60f645f..75b8fe2 100644 --- a/lib/elixir_react_starter_web/controllers/locale_controller.ex +++ b/lib/elixir_react_starter_web/controllers/locale_controller.ex @@ -16,24 +16,19 @@ defmodule ElixirReactStarterWeb.LocaleController do use ElixirReactStarterWeb, :controller + import ElixirReactStarter.Locale, only: [is_supported: 1] + alias ElixirReactStarter.Accounts alias ElixirReactStarterWeb.LocalPath + alias ElixirReactStarterWeb.Plugs.Locale action_fallback ElixirReactStarterWeb.FallbackController - @supported_locales Application.compile_env(:elixir_react_starter, :supported_locales, ["en"]) - # 1 year, in seconds. - @cookie_max_age 60 * 60 * 24 * 365 - - def update(conn, %{"locale" => locale}) when locale in @supported_locales do + def update(conn, %{"locale" => locale}) when is_supported(locale) do case maybe_update_user(conn.assigns[:current_user], locale) do :ok -> conn - |> put_resp_cookie("locale", locale, - max_age: @cookie_max_age, - http_only: false, - same_site: "Lax" - ) + |> Locale.put_cookie(locale) |> redirect(to: LocalPath.referer(conn) || ~p"/") {:error, _changeset} -> diff --git a/lib/elixir_react_starter_web/plugs/locale.ex b/lib/elixir_react_starter_web/plugs/locale.ex new file mode 100644 index 0000000..20d91ed --- /dev/null +++ b/lib/elixir_react_starter_web/plugs/locale.ex @@ -0,0 +1,73 @@ +defmodule ElixirReactStarterWeb.Plugs.Locale do + @moduledoc """ + Resolves the request locale, hands it to Gettext, and assigns it as + `conn.assigns.locale`. Owns the `locale` cookie: `put_cookie/2` is how + the locale switcher remembers an anonymous visitor's choice. + + Precedence: + + 1. `user.locale` — the signed-in user's saved preference, which + follows them across devices. + 2. The `locale` cookie — an anonymous visitor's last choice. It + outlives logout, so the next visit honours it. + 3. The first supported language in `Accept-Language`. + 4. `ElixirReactStarter.Locale.default/0`. + + Runs after `UserAuth.fetch_current_user/2` in the browser pipeline. + """ + + @behaviour Plug + + import Plug.Conn + import ElixirReactStarter.Locale, only: [is_supported: 1] + + alias ElixirReactStarter.Locale + + @cookie "locale" + # 1 year, in seconds. + @cookie_max_age 60 * 60 * 24 * 365 + + @impl true + def init(opts), do: opts + + @impl true + def call(conn, _opts) do + conn = fetch_cookies(conn) + locale = resolve(conn, conn.assigns[:current_user]) + _ = Gettext.put_locale(ElixirReactStarterWeb.Gettext, locale) + assign(conn, :locale, locale) + end + + @doc """ + Remembers `locale` in a 1-year cookie. Readable from JavaScript + (`http_only: false`) so the frontend can see the choice too. + """ + @spec put_cookie(Plug.Conn.t(), String.t()) :: Plug.Conn.t() + def put_cookie(conn, locale) when is_supported(locale) do + put_resp_cookie(conn, @cookie, locale, + max_age: @cookie_max_age, + http_only: false, + same_site: "Lax" + ) + end + + defp resolve(_conn, %{locale: locale}) when is_supported(locale), do: locale + + defp resolve(conn, _user) do + case conn.cookies[@cookie] do + locale when is_supported(locale) -> locale + _ -> conn |> get_req_header("accept-language") |> from_accept_language() + end + end + + defp from_accept_language([header | _]) do + header + |> String.split(",") + |> Enum.map(fn tag -> + tag |> String.split(";") |> hd() |> String.trim() |> String.slice(0, 2) + end) + |> Enum.find(Locale.default(), &(&1 in Locale.supported())) + end + + defp from_accept_language([]), do: Locale.default() +end diff --git a/lib/elixir_react_starter_web/plugs/shared_data.ex b/lib/elixir_react_starter_web/plugs/shared_data.ex index 052f64a..108d0a8 100644 --- a/lib/elixir_react_starter_web/plugs/shared_data.ex +++ b/lib/elixir_react_starter_web/plugs/shared_data.ex @@ -3,7 +3,7 @@ defmodule ElixirReactStarterWeb.Plugs.SharedData do Inertia plug that assigns the props every page receives: * `current_user` — `%{id, email, locale}`, or `nil` when anonymous. - * `locale` — the resolved request locale (defaults to `"en"`). + * `locale` — the request locale resolved by `Plugs.Locale`. * `socket_token` — a short-lived signed token the React realtime provider hands to `Phoenix.Socket` on connect; `nil` when anonymous so the frontend skips wiring up the socket. @@ -11,8 +11,8 @@ defmodule ElixirReactStarterWeb.Plugs.SharedData do The flash isn't a prop: Inertia puts `conn.assigns.flash` on the page object itself (`page.flash` on the frontend). - Runs after `:fetch_current_user` in the browser pipeline so - `conn.assigns[:current_user]` and `:locale` are populated. + Runs after `:fetch_current_user` and `Plugs.Locale` in the browser + pipeline so `conn.assigns[:current_user]` and `:locale` are populated. """ import Inertia.Controller @@ -34,7 +34,7 @@ defmodule ElixirReactStarterWeb.Plugs.SharedData do Application.get_env(:elixir_react_starter, :sentry_client) ) |> assign_prop(:current_user, fn -> serialize_user(user) end) - |> assign_prop(:locale, conn.assigns[:locale] || "en") + |> assign_prop(:locale, conn.assigns.locale) # Sign only when the response includes the token. Redirects and partial # reloads that omit it need no new token. |> assign_prop(:socket_token, fn -> socket_token_for(user) end) diff --git a/lib/elixir_react_starter_web/plugs/user_auth.ex b/lib/elixir_react_starter_web/plugs/user_auth.ex index 489b75f..0ddfa07 100644 --- a/lib/elixir_react_starter_web/plugs/user_auth.ex +++ b/lib/elixir_react_starter_web/plugs/user_auth.ex @@ -7,7 +7,7 @@ defmodule ElixirReactStarterWeb.UserAuth do * `fetch_current_user/2` — resolves the session token to a user (sliding the 60-day expiry forward on activity) and assigns - `:current_user` and `:locale`. + `:current_user`. * `require_authenticated_user/2` — gate for authenticated routes; redirects to `/login`, stashing the requested GET path so log-in can return the user there afterwards. @@ -23,11 +23,6 @@ defmodule ElixirReactStarterWeb.UserAuth do open redirects, and only GET requests are stored so a redirect can't replay a state-changing action. - ## Locale precedence - - `fetch_current_user/2` resolves the request locale as: `user.locale` - (authenticated) → `locale` cookie → first supported `Accept-Language` - match → the configured default, then hands it to Gettext. """ import Plug.Conn @@ -47,57 +42,19 @@ defmodule ElixirReactStarterWeb.UserAuth do # them to /login. Read once by `log_in_user/2`, then cleared by # `renew_session/1` (which wipes the whole session). @return_to_key "user_return_to" - @supported_locales Application.compile_env(:elixir_react_starter, :supported_locales, ["en"]) - @default_locale Application.compile_env(:elixir_react_starter, :default_locale, "en") # ============================================================================= # Plugs # ============================================================================= @doc """ Reads the session token and assigns the current user (or nil) to the - conn. Resolves the request locale and hands it to Gettext. + conn. Tags Sentry events from this request with the user's id. """ def fetch_current_user(conn, _opts) do token = get_session(conn, @session_key) user = token && Accounts.get_user_by_session_token(token) - conn = fetch_cookies(conn) - locale = request_locale(conn, user) - _ = Gettext.put_locale(ElixirReactStarterWeb.Gettext, locale) Sentry.Context.set_user_context(%{id: user && user.id}) - - conn - |> assign(:current_user, user) - |> assign(:locale, locale) - end - - # Precedence: - # 1. user.locale — persisted preference, follows authenticated - # users across devices and sessions. - # 2. "locale" cookie — anonymous users' last choice; also persists - # across logout so the next visit honours it. - # 3. Accept-Language header — first supported-locale match. - # 4. @default_locale fallback. - defp request_locale(_conn, %{locale: locale}) when locale in @supported_locales, do: locale - - defp request_locale(conn, _user) do - case conn.cookies["locale"] do - locale when locale in @supported_locales -> - locale - - _ -> - case get_req_header(conn, "accept-language") do - [header | _] -> parse_accept_language(header) - _ -> @default_locale - end - end - end - - defp parse_accept_language(header) do - header - |> String.split(",") - |> Enum.map(&String.trim/1) - |> Enum.map(fn tag -> tag |> String.split(";") |> List.first() |> String.slice(0, 2) end) - |> Enum.find(@default_locale, &(&1 in @supported_locales)) + assign(conn, :current_user, user) end @doc """ diff --git a/lib/elixir_react_starter_web/router.ex b/lib/elixir_react_starter_web/router.ex index b7fc4b6..3c57949 100644 --- a/lib/elixir_react_starter_web/router.ex +++ b/lib/elixir_react_starter_web/router.ex @@ -12,6 +12,7 @@ defmodule ElixirReactStarterWeb.Router do plug :put_secure_browser_headers plug Inertia.Plug plug :fetch_current_user + plug ElixirReactStarterWeb.Plugs.Locale plug ElixirReactStarterWeb.Plugs.SharedData end diff --git a/test/architecture_test.exs b/test/architecture_test.exs index 27470e8..99175c7 100644 --- a/test/architecture_test.exs +++ b/test/architecture_test.exs @@ -51,6 +51,22 @@ defmodule ElixirReactStarter.ArchitectureTest do Enum.join(offenders, "\n") end + test "only ElixirReactStarter.Locale reads the locale config" do + # i18n.check is a build-time Mix task; it reads config before the app compiles. + offenders = + for path <- + files("lib/**/*.ex", + except: ["lib/elixir_react_starter/locale.ex", "lib/mix/tasks/i18n_check.ex"] + ), + atom <- atoms(path), + atom in [:supported_locales, :default_locale], + uniq: true, + do: path + + assert offenders == [], + "ask ElixirReactStarter.Locale instead:\n" <> Enum.join(offenders, "\n") + end + # --------------------------------------------------------------------------- # AST helpers # --------------------------------------------------------------------------- @@ -66,6 +82,14 @@ defmodule ElixirReactStarter.ArchitectureTest do end) end + # Every atom literal in the file. + defp atoms(path) do + collect(path, fn + atom when is_atom(atom) -> {:ok, atom} + _node -> :skip + end) + end + # Every string literal in the file. defp strings(path) do collect(path, fn diff --git a/test/elixir_react_starter_web/plugs/locale_test.exs b/test/elixir_react_starter_web/plugs/locale_test.exs new file mode 100644 index 0000000..6151cea --- /dev/null +++ b/test/elixir_react_starter_web/plugs/locale_test.exs @@ -0,0 +1,68 @@ +defmodule ElixirReactStarterWeb.Plugs.LocaleTest do + use ElixirReactStarterWeb.ConnCase, async: true + + alias ElixirReactStarterWeb.Plugs.Locale + + defp resolve(conn, user \\ nil) do + conn |> assign(:current_user, user) |> Locale.call([]) + end + + describe "call/2" do + test "picks the first supported language from Accept-Language", %{conn: conn} do + conn = conn |> put_req_header("accept-language", "fr-FR,es-ES;q=0.9,en;q=0.5") |> resolve() + assert conn.assigns.locale == "es" + assert Gettext.get_locale(ElixirReactStarterWeb.Gettext) == "es" + end + + test "falls back to the default locale without Accept-Language", %{conn: conn} do + assert resolve(conn).assigns.locale == "en" + end + + test "falls back to the default locale when no language is supported", %{conn: conn} do + conn = conn |> put_req_header("accept-language", "fr-FR,de;q=0.9") |> resolve() + assert conn.assigns.locale == "en" + end + + test "prefers user.locale over the cookie and Accept-Language", %{conn: conn} do + user = :user |> build(locale: "es") |> insert() + + conn = + conn + |> put_req_cookie("locale", "en") + |> put_req_header("accept-language", "en") + |> resolve(user) + + assert conn.assigns.locale == "es" + end + + test "anonymous: the locale cookie beats Accept-Language", %{conn: conn} do + conn = + conn + |> put_req_cookie("locale", "es") + |> put_req_header("accept-language", "fr-FR,fr;q=0.9,en;q=0.5") + |> resolve() + + assert conn.assigns.locale == "es" + end + + test "anonymous: an unsupported cookie value is ignored", %{conn: conn} do + conn = + conn + |> put_req_cookie("locale", "fr") + |> put_req_header("accept-language", "es-ES,es;q=0.9") + |> resolve() + + assert conn.assigns.locale == "es" + end + end + + describe "put_cookie/2" do + test "writes a year-long cookie the frontend can read", %{conn: conn} do + cookie = Locale.put_cookie(conn, "es").resp_cookies["locale"] + + assert cookie.value == "es" + assert cookie.max_age == 60 * 60 * 24 * 365 + assert cookie.http_only == false + end + end +end diff --git a/test/elixir_react_starter_web/plugs/user_auth_test.exs b/test/elixir_react_starter_web/plugs/user_auth_test.exs index d269567..9e8e2e4 100644 --- a/test/elixir_react_starter_web/plugs/user_auth_test.exs +++ b/test/elixir_react_starter_web/plugs/user_auth_test.exs @@ -42,53 +42,6 @@ defmodule ElixirReactStarterWeb.UserAuthTest do assert conn.assigns.current_user == nil end - - test "assigns the request locale from Accept-Language", %{conn: conn} do - conn = - conn - |> put_req_header("accept-language", "es-ES,es;q=0.9,en;q=0.5") - |> UserAuth.fetch_current_user([]) - - assert conn.assigns.locale == "es" - end - - test "falls back to the default locale without Accept-Language", %{conn: conn} do - conn = UserAuth.fetch_current_user(conn, []) - assert conn.assigns.locale == "en" - end - - test "prefers user.locale over Accept-Language for authenticated users", %{conn: conn} do - es_user = :user |> build(locale: "es") |> confirmed() |> insert() - token = Accounts.generate_user_session_token(es_user) - - conn = - conn - |> put_session(@session_key, token) - |> put_req_header("accept-language", "fr-FR,fr;q=0.9,en;q=0.5") - |> UserAuth.fetch_current_user([]) - - assert conn.assigns.locale == "es" - end - - test "anonymous: locale cookie beats Accept-Language", %{conn: conn} do - conn = - conn - |> put_req_cookie("locale", "es") - |> put_req_header("accept-language", "fr-FR,fr;q=0.9,en;q=0.5") - |> UserAuth.fetch_current_user([]) - - assert conn.assigns.locale == "es" - end - - test "anonymous: unsupported cookie value is ignored", %{conn: conn} do - conn = - conn - |> put_req_cookie("locale", "fr") - |> put_req_header("accept-language", "es-ES,es;q=0.9") - |> UserAuth.fetch_current_user([]) - - assert conn.assigns.locale == "es" - end end describe "require_authenticated_user/2" do From 12146f1ff87aec3d22a544908332a15ac6427777 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Ogle?= Date: Sat, 28 Nov 2026 13:27:02 -0500 Subject: [PATCH 04/15] refactor: make UserAuth and UserJSON the only owners of session and user shape SettingsController and ConnCase wrote the "user_token" session key themselves; UserAuth.put_user_session/2 now does it for all callers. SharedData's private serialize_user/1 becomes UserJSON.data/1, per the *_json.ex rule, which an architecture test now enforces. --- docs/governance/PROGRESS.md | 13 ++++++++++ docs/governance/TASKS.md | 4 ++-- .../controllers/settings_controller.ex | 3 +-- .../controllers/user_json.ex | 15 ++++++++++++ .../plugs/shared_data.ex | 11 +++------ .../plugs/user_auth.ex | 21 ++++++++++++---- test/architecture_test.exs | 24 +++++++++++++++++++ .../plugs/user_auth_test.exs | 10 ++++++++ test/support/conn_case.ex | 5 ++-- 9 files changed, 87 insertions(+), 19 deletions(-) create mode 100644 lib/elixir_react_starter_web/controllers/user_json.ex diff --git a/docs/governance/PROGRESS.md b/docs/governance/PROGRESS.md index 9672354..223ce1b 100644 --- a/docs/governance/PROGRESS.md +++ b/docs/governance/PROGRESS.md @@ -41,3 +41,16 @@ ends with `mix precommit` green and its own commit. - Locale precedence tests moved from `user_auth_test` to `plugs/locale_test` (plus a no-supported-language case and a cookie-attributes case). - New architecture rule: only `Locale` reads the locale config keys. + +## Round 3 — session key and user wire shape (B3, B4) + +- `UserAuth.put_user_session/2` (renew + new token). `log_in_user/2`, + `SettingsController.update_password/2` and `ConnCase.log_in_user/2` use it; + the `"user_token"` key no longer appears outside `UserAuth` in `lib/` or + test support. Controller tests still assert the literal key on purpose: it + is a persistence contract (renaming it signs everyone out). +- `UserJSON.data/1` replaces `SharedData.serialize_user/1`. Only `data/1` + exists: no JSON endpoint renders users, so `index/1`/`show/1` would have no + caller (add them with the first JSON API). +- New architecture rule: no `serialize*` functions or `*Serializer`/`*Props` + modules in the web layer. diff --git a/docs/governance/TASKS.md b/docs/governance/TASKS.md index d635dd3..674e045 100644 --- a/docs/governance/TASKS.md +++ b/docs/governance/TASKS.md @@ -10,8 +10,8 @@ decision — see the bottom section), `rejected` (with the reason). | --- | --- | --- | --- | | B1 | Three "safe redirect" implementations with different strictness: `UserAuth.local_path?/1` rejects `//`, `\`, tabs, newlines; `LocaleController.safe_referer/1` and `FallbackController.referer_path/1` only check for a leading `/` | One `ElixirReactStarterWeb.LocalPath` module; all three callers use it | done — `refactor: route every redirect check through LocalPath` | | B2 | Locale concept spread over five modules: `:supported_locales` read by `User`, `UserAuth`, `LocaleController`; `"en"` fallback hardcoded in `SharedData`; `"locale"` cookie written by `LocaleController`, read by `UserAuth`; locale resolution lives inside the auth plug | `ElixirReactStarter.Locale` (list, default, guard) + `Plugs.Locale` (resolution, cookie) | done — `refactor: give the locale concept one owner per layer` | -| B3 | `SharedData.serialize_user/1` is an ad-hoc serializer, against the `*_json.ex` rule | `UserJSON.data/1` | todo | -| B4 | `SettingsController` writes the `"user_token"` session key itself; `UserAuth` owns it | `UserAuth.renew_user_session/2`, used by `log_in_user/2`, `SettingsController`, `ConnCase` | todo | +| B3 | `SharedData.serialize_user/1` is an ad-hoc serializer, against the `*_json.ex` rule | `UserJSON.data/1` | done — `refactor: make UserAuth and UserJSON the only owners of session and user shape` | +| B4 | `SettingsController` writes the `"user_token"` session key itself; `UserAuth` owns it | `UserAuth.put_user_session/2`, used by `log_in_user/2`, `SettingsController`, `ConnCase` | done — same commit as B3 | | B5 | Link-token contexts are free strings; a typo issues a token no verifier accepts. `UserToken` builds link tokens in two near-identical functions and repeats the hash 5 times | Guard contexts against a closed list; one link-token builder; one `hash/1` | todo | | B6 | Mail delivery: `Email.x(...) \|> Mailer.deliver()` inline in two controllers, with the "fire and forget" rule stated once in a private helper; `Email` logs "Sending …" at build time, before (and regardless of) delivery | `Email.deliver/1` wrapper owning delivery + logging | todo | | B7 | `AuthController` repeats the "invalid or expired reset link" redirect three times; `SettingsController` repeats the email-change failure redirect twice | One private helper per controller | todo | diff --git a/lib/elixir_react_starter_web/controllers/settings_controller.ex b/lib/elixir_react_starter_web/controllers/settings_controller.ex index c1c9d1d..0c0d5e9 100644 --- a/lib/elixir_react_starter_web/controllers/settings_controller.ex +++ b/lib/elixir_react_starter_web/controllers/settings_controller.ex @@ -110,8 +110,7 @@ defmodule ElixirReactStarterWeb.SettingsController do # a fresh one for the current browser so they stay logged in; # other devices are signed out as intended. conn - |> UserAuth.renew_session() - |> put_session("user_token", Accounts.generate_user_session_token(updated_user)) + |> UserAuth.put_user_session(updated_user) |> put_flash(:info, dgettext("app", "Password updated.")) |> redirect(to: ~p"/settings") diff --git a/lib/elixir_react_starter_web/controllers/user_json.ex b/lib/elixir_react_starter_web/controllers/user_json.ex new file mode 100644 index 0000000..9627069 --- /dev/null +++ b/lib/elixir_react_starter_web/controllers/user_json.ex @@ -0,0 +1,15 @@ +defmodule ElixirReactStarterWeb.UserJSON do + @moduledoc """ + Wire shape of a user, as the frontend sees it (`CurrentUser` in + `assets/js/types.ts`). Only the fields a page needs: never the password + hash or token data. + """ + + alias ElixirReactStarter.Accounts.User + + @doc "The user as a JSON-ready map." + @spec data(User.t()) :: %{id: String.t(), email: String.t(), locale: String.t()} + def data(%User{} = user) do + %{id: user.id, email: user.email, locale: user.locale} + end +end diff --git a/lib/elixir_react_starter_web/plugs/shared_data.ex b/lib/elixir_react_starter_web/plugs/shared_data.ex index 108d0a8..165a8f5 100644 --- a/lib/elixir_react_starter_web/plugs/shared_data.ex +++ b/lib/elixir_react_starter_web/plugs/shared_data.ex @@ -2,7 +2,7 @@ defmodule ElixirReactStarterWeb.Plugs.SharedData do @moduledoc """ Inertia plug that assigns the props every page receives: - * `current_user` — `%{id, email, locale}`, or `nil` when anonymous. + * `current_user` — `UserJSON.data/1`, or `nil` when anonymous. * `locale` — the request locale resolved by `Plugs.Locale`. * `socket_token` — a short-lived signed token the React realtime provider hands to `Phoenix.Socket` on connect; `nil` when @@ -18,6 +18,7 @@ defmodule ElixirReactStarterWeb.Plugs.SharedData do import Inertia.Controller alias ElixirReactStarterWeb.Endpoint + alias ElixirReactStarterWeb.UserJSON alias ElixirReactStarterWeb.UserSocket def init(opts), do: opts @@ -33,19 +34,13 @@ defmodule ElixirReactStarterWeb.Plugs.SharedData do :sentry_client, Application.get_env(:elixir_react_starter, :sentry_client) ) - |> assign_prop(:current_user, fn -> serialize_user(user) end) + |> assign_prop(:current_user, fn -> user && UserJSON.data(user) end) |> assign_prop(:locale, conn.assigns.locale) # Sign only when the response includes the token. Redirects and partial # reloads that omit it need no new token. |> assign_prop(:socket_token, fn -> socket_token_for(user) end) end - defp serialize_user(nil), do: nil - - defp serialize_user(user) do - %{id: user.id, email: user.email, locale: user.locale} - end - # Signs a short-lived token the React realtime provider hands to # Phoenix.Socket on connect. `nil` for anonymous requests so the # provider can branch on `socket_token === null` and skip wiring up diff --git a/lib/elixir_react_starter_web/plugs/user_auth.ex b/lib/elixir_react_starter_web/plugs/user_auth.ex index 0ddfa07..d86f4c5 100644 --- a/lib/elixir_react_starter_web/plugs/user_auth.ex +++ b/lib/elixir_react_starter_web/plugs/user_auth.ex @@ -103,22 +103,33 @@ defmodule ElixirReactStarterWeb.UserAuth do # Helpers for controllers # ============================================================================= @doc """ - Logs the user in by generating a session token, renewing the session, - and redirecting either to `user_return_to` (if `require_authenticated_user` + Logs the user in (`put_user_session/2`) and redirects either to `user_return_to` (if `require_authenticated_user` stored one) or to /dashboard. - Reads `user_return_to` BEFORE `renew_session/1`, which clears the + Reads `user_return_to` before the session is renewed, which clears the whole session, including that key. """ def log_in_user(conn, user) do - token = Accounts.generate_user_session_token(user) return_to = get_session(conn, @return_to_key) redirect_path = if LocalPath.local?(return_to), do: return_to, else: ~p"/dashboard" + conn + |> put_user_session(user) + |> redirect(to: redirect_path) + end + + @doc """ + Starts a fresh session for `user` without redirecting: renews the + session (new id, cleared data) and stores a new session token. Use it + to keep the current browser signed in after an action that revoked the + user's tokens, such as a password change. + """ + def put_user_session(conn, user) do + token = Accounts.generate_user_session_token(user) + conn |> renew_session() |> put_session(@session_key, token) - |> redirect(to: redirect_path) end @doc """ diff --git a/test/architecture_test.exs b/test/architecture_test.exs index 99175c7..afa44bb 100644 --- a/test/architecture_test.exs +++ b/test/architecture_test.exs @@ -67,6 +67,19 @@ defmodule ElixirReactStarter.ArchitectureTest do "ask ElixirReactStarter.Locale instead:\n" <> Enum.join(offenders, "\n") end + test "wire shapes live in *_json.ex view modules, not ad-hoc serializers" do + offenders = + for path <- files(@web_files, except: []), + name <- + definitions(path) ++ Enum.map(aliases(path), &(&1 |> List.last() |> Atom.to_string())), + String.starts_with?(name, "serialize") or + String.ends_with?(name, ["Serializer", "Props"]), + uniq: true, + do: "#{path}: #{name}" + + assert offenders == [], "use a *_json.ex module's data/1:\n" <> Enum.join(offenders, "\n") + end + # --------------------------------------------------------------------------- # AST helpers # --------------------------------------------------------------------------- @@ -82,6 +95,17 @@ defmodule ElixirReactStarter.ArchitectureTest do end) end + # Names of every function defined in the file. + defp definitions(path) do + collect(path, fn + {kind, _, [{name, _, _} | _]} when kind in [:def, :defp] and is_atom(name) -> + {:ok, Atom.to_string(name)} + + _node -> + :skip + end) + end + # Every atom literal in the file. defp atoms(path) do collect(path, fn diff --git a/test/elixir_react_starter_web/plugs/user_auth_test.exs b/test/elixir_react_starter_web/plugs/user_auth_test.exs index 9e8e2e4..00dc4df 100644 --- a/test/elixir_react_starter_web/plugs/user_auth_test.exs +++ b/test/elixir_react_starter_web/plugs/user_auth_test.exs @@ -98,6 +98,16 @@ defmodule ElixirReactStarterWeb.UserAuthTest do end end + describe "put_user_session/2" do + test "renews the session and stores a token for the user", %{conn: conn, user: user} do + conn = conn |> put_session(:stale, "data") |> UserAuth.put_user_session(user) + + assert get_session(conn, :stale) == nil + assert Accounts.get_user_by_session_token(get_session(conn, @session_key)).id == user.id + refute conn.halted + end + end + describe "log_in_user/2" do test "rejects unsafe stored destinations and clears them on login", %{conn: conn, user: user} do for destination <- [ diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex index ec3c88a..2f9818e 100644 --- a/test/support/conn_case.ex +++ b/test/support/conn_case.ex @@ -48,7 +48,8 @@ defmodule ElixirReactStarterWeb.ConnCase do scenarios). """ def log_in_user(conn, user) do - token = ElixirReactStarter.Accounts.generate_user_session_token(user) - Phoenix.ConnTest.init_test_session(conn, %{"user_token" => token}) + conn + |> Phoenix.ConnTest.init_test_session(%{}) + |> ElixirReactStarterWeb.UserAuth.put_user_session(user) end end From 4e106914ed68d52fcb17b9aa67a60132006d4a24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Ogle?= Date: Sat, 28 Nov 2026 13:32:55 -0500 Subject: [PATCH 05/15] refactor: guard link-token contexts and build every link token one way Link-token contexts were free strings, so a typo silently issued a token no verifier would accept. Both UserToken and the Accounts API now guard against a closed list. build_email_change_token/2 folds into build_link_token/3, and the SHA3-256 call lives in one private hash/1. Stored token format is unchanged. --- docs/governance/PROGRESS.md | 12 ++++ docs/governance/TASKS.md | 2 +- lib/elixir_react_starter/accounts.ex | 13 ++-- .../accounts/user_token.ex | 67 ++++++++----------- test/elixir_react_starter/accounts_test.exs | 12 ++++ 5 files changed, 62 insertions(+), 44 deletions(-) diff --git a/docs/governance/PROGRESS.md b/docs/governance/PROGRESS.md index 223ce1b..43a2db4 100644 --- a/docs/governance/PROGRESS.md +++ b/docs/governance/PROGRESS.md @@ -54,3 +54,15 @@ ends with `mix precommit` green and its own commit. caller (add them with the first JSON API). - New architecture rule: no `serialize*` functions or `*Serializer`/`*Props` modules in the web layer. + +## Round 4 — link tokens (B5) + +- `UserToken.build_link_token/3` (optional `sent_to`) replaces the + near-duplicate `build_email_change_token/2`; one private `hash/1` replaces + five inline `:crypto.hash(:sha3_256, …)` calls. Token format, hashing and + stored context strings are unchanged, so existing tokens stay valid. +- Context strings are now a closed list. `UserToken` guards on all three; + `Accounts.generate_user_link_token/2` / `verify_user_link_token/2` accept + only the two emailed contexts. A misspelt context raises + `FunctionClauseError` instead of minting a token nothing will verify + (regression test added). diff --git a/docs/governance/TASKS.md b/docs/governance/TASKS.md index 674e045..38122cd 100644 --- a/docs/governance/TASKS.md +++ b/docs/governance/TASKS.md @@ -12,7 +12,7 @@ decision — see the bottom section), `rejected` (with the reason). | B2 | Locale concept spread over five modules: `:supported_locales` read by `User`, `UserAuth`, `LocaleController`; `"en"` fallback hardcoded in `SharedData`; `"locale"` cookie written by `LocaleController`, read by `UserAuth`; locale resolution lives inside the auth plug | `ElixirReactStarter.Locale` (list, default, guard) + `Plugs.Locale` (resolution, cookie) | done — `refactor: give the locale concept one owner per layer` | | B3 | `SharedData.serialize_user/1` is an ad-hoc serializer, against the `*_json.ex` rule | `UserJSON.data/1` | done — `refactor: make UserAuth and UserJSON the only owners of session and user shape` | | B4 | `SettingsController` writes the `"user_token"` session key itself; `UserAuth` owns it | `UserAuth.put_user_session/2`, used by `log_in_user/2`, `SettingsController`, `ConnCase` | done — same commit as B3 | -| B5 | Link-token contexts are free strings; a typo issues a token no verifier accepts. `UserToken` builds link tokens in two near-identical functions and repeats the hash 5 times | Guard contexts against a closed list; one link-token builder; one `hash/1` | todo | +| B5 | Link-token contexts are free strings; a typo issues a token no verifier accepts. `UserToken` builds link tokens in two near-identical functions and repeats the hash 5 times | Guard contexts against a closed list; one link-token builder; one `hash/1` | done — `refactor: guard link-token contexts and build every link token one way` | | B6 | Mail delivery: `Email.x(...) \|> Mailer.deliver()` inline in two controllers, with the "fire and forget" rule stated once in a private helper; `Email` logs "Sending …" at build time, before (and regardless of) delivery | `Email.deliver/1` wrapper owning delivery + logging | todo | | B7 | `AuthController` repeats the "invalid or expired reset link" redirect three times; `SettingsController` repeats the email-change failure redirect twice | One private helper per controller | todo | | B8 | `FallbackController` clauses for `:unauthorized`, `:bad_request`, `:not_found`, changeset have no producer in the app today | Keep: they pair with `Context`'s `*_ok` functions and are the template's documented extension point | rejected | diff --git a/lib/elixir_react_starter/accounts.ex b/lib/elixir_react_starter/accounts.ex index 3b199df..47ba353 100644 --- a/lib/elixir_react_starter/accounts.ex +++ b/lib/elixir_react_starter/accounts.ex @@ -30,6 +30,10 @@ defmodule ElixirReactStarter.Accounts do alias ElixirReactStarter.Accounts.{User, UserToken} alias ElixirReactStarter.Repo + # Link tokens issued by generate_user_link_token/2. Email-change tokens + # have their own flow (request_email_change/3, apply_email_change/2). + @emailed_link_contexts ~w(email_confirmation password_reset) + # ============================================================================= # Registration # ============================================================================= @@ -114,7 +118,7 @@ defmodule ElixirReactStarter.Accounts do Invalidates any previous tokens for the same user + context so a resend doesn't accumulate active tokens. """ - def generate_user_link_token(user, context) do + def generate_user_link_token(user, context) when context in @emailed_link_contexts do Repo.delete_all(UserToken.delete_user_tokens_by_context_query(user.id, context)) {raw_token, user_token} = UserToken.build_link_token(user, context) @@ -126,13 +130,14 @@ defmodule ElixirReactStarter.Accounts do Verifies a raw link token for the given context. Returns the user if the token is valid (and not expired), or `nil` otherwise. """ - def verify_user_link_token(raw_token, context) when is_binary(raw_token) do + def verify_user_link_token(raw_token, context) + when is_binary(raw_token) and context in @emailed_link_contexts do raw_token |> UserToken.verify_link_token_query(context) |> Repo.one() end - def verify_user_link_token(_, _), do: nil + def verify_user_link_token(_raw_token, context) when context in @emailed_link_contexts, do: nil # ============================================================================= # Locale @@ -186,7 +191,7 @@ defmodule ElixirReactStarter.Accounts do |> case do %{valid?: true} -> Repo.delete_all(UserToken.delete_user_tokens_by_context_query(user.id, "email_change")) - {raw_token, user_token} = UserToken.build_email_change_token(user, new_email) + {raw_token, user_token} = UserToken.build_link_token(user, "email_change", new_email) Repo.insert!(user_token) Logger.info("Email change requested for user #{user.id}") {:ok, raw_token} diff --git a/lib/elixir_react_starter/accounts/user_token.ex b/lib/elixir_react_starter/accounts/user_token.ex index 657fb55..e8ad684 100644 --- a/lib/elixir_react_starter/accounts/user_token.ex +++ b/lib/elixir_react_starter/accounts/user_token.ex @@ -27,6 +27,15 @@ defmodule ElixirReactStarter.Accounts.UserToken do @session_refresh_after_days 1 @link_validity_in_hours 1 + # Every context a link token can carry. Guarded so a typo fails loudly + # instead of issuing a token no verifier will ever accept. + @link_contexts ~w(email_confirmation password_reset email_change) + + @typedoc "Purpose of a link token. `\"email_change\"` tokens also carry `sent_to`." + @type link_context :: String.t() + + defguardp is_link_context(context) when context in @link_contexts + schema "user_tokens" do field :token, :binary, redact: true field :context, :string @@ -54,7 +63,7 @@ defmodule ElixirReactStarter.Accounts.UserToken do {token, %__MODULE__{ - token: :crypto.hash(:sha3_256, token), + token: hash(token), context: "session", user_id: user.id, refreshed_at: now @@ -66,7 +75,7 @@ defmodule ElixirReactStarter.Accounts.UserToken do token is still valid (within #{@session_validity_in_days} days). """ def verify_session_token_query(token) do - hashed = :crypto.hash(:sha3_256, token) + hashed = hash(token) from t in __MODULE__, where: t.token == ^hashed and t.context == "session", @@ -82,7 +91,7 @@ defmodule ElixirReactStarter.Accounts.UserToken do inactive sessions expire after #{@session_validity_in_days} days. """ def refresh_session_token_query(token) do - hashed = :crypto.hash(:sha3_256, token) + hashed = hash(token) now = DateTime.utc_now() |> DateTime.truncate(:second) from t in __MODULE__, @@ -92,7 +101,7 @@ defmodule ElixirReactStarter.Accounts.UserToken do end # ============================================================================= - # Email-link tokens (confirmation, password reset) + # Email-link tokens (confirmation, password reset, email change) # ============================================================================= @doc """ Builds a URL-safe link token for the given user and context. Returns @@ -100,17 +109,21 @@ defmodule ElixirReactStarter.Accounts.UserToken do (e.g. `https://app.example/confirm-email?token=...`), the struct (with SHA3-256 hash) is inserted into the DB. - Context should be `"email_confirmation"` or `"password_reset"`. + `sent_to` is the pending new address of an `"email_change"` token, so + the click handler knows what to change the email to; the link is mailed + to that address to prove the user controls it. """ - def build_link_token(user, context) do + @spec build_link_token(%{id: term()}, link_context(), String.t() | nil) :: + {String.t(), %__MODULE__{}} + def build_link_token(user, context, sent_to \\ nil) when is_link_context(context) do raw_token = @rand_size |> :crypto.strong_rand_bytes() |> Base.url_encode64(padding: false) - hashed = :crypto.hash(:sha3_256, raw_token) now = DateTime.utc_now() |> DateTime.truncate(:second) {raw_token, %__MODULE__{ - token: hashed, + token: hash(raw_token), context: context, + sent_to: sent_to, user_id: user.id, refreshed_at: now }} @@ -121,40 +134,15 @@ defmodule ElixirReactStarter.Accounts.UserToken do provided the token is still valid (within #{@link_validity_in_hours} hour). """ - def verify_link_token_query(raw_token, context) when is_binary(raw_token) do - hashed = :crypto.hash(:sha3_256, raw_token) - + def verify_link_token_query(raw_token, context) + when is_binary(raw_token) and is_link_context(context) do from t in __MODULE__, - where: t.token == ^hashed and t.context == ^context, + where: t.token == ^hash(raw_token) and t.context == ^context, where: t.inserted_at > ago(^@link_validity_in_hours, "hour"), join: u in assoc(t, :user), select: u end - # ============================================================================= - # Email-change tokens - # ============================================================================= - @doc """ - Builds an email-change link token. Like a regular link token but - stashes the requested new address in `sent_to` so the click handler - knows what to change the email to. The link is mailed to the *new* - address to prove the user controls it. - """ - def build_email_change_token(user, new_email) do - raw_token = @rand_size |> :crypto.strong_rand_bytes() |> Base.url_encode64(padding: false) - hashed = :crypto.hash(:sha3_256, raw_token) - now = DateTime.utc_now() |> DateTime.truncate(:second) - - {raw_token, - %__MODULE__{ - token: hashed, - context: "email_change", - sent_to: new_email, - user_id: user.id, - refreshed_at: now - }} - end - @doc """ Query that finds the email-change token for the given raw token, scoped to a specific `user_id`, provided it's still valid (within @@ -162,10 +150,9 @@ defmodule ElixirReactStarter.Accounts.UserToken do caller can read `sent_to`. """ def verify_email_change_token_query(raw_token, user_id) when is_binary(raw_token) do - hashed = :crypto.hash(:sha3_256, raw_token) - from t in __MODULE__, - where: t.token == ^hashed and t.context == "email_change" and t.user_id == ^user_id, + where: + t.token == ^hash(raw_token) and t.context == "email_change" and t.user_id == ^user_id, where: t.inserted_at > ago(^@link_validity_in_hours, "hour") end @@ -178,4 +165,6 @@ defmodule ElixirReactStarter.Accounts.UserToken do from t in __MODULE__, where: t.user_id == ^user_id and t.context == ^context end + + defp hash(token), do: :crypto.hash(:sha3_256, token) end diff --git a/test/elixir_react_starter/accounts_test.exs b/test/elixir_react_starter/accounts_test.exs index a17dab3..a4e8751 100644 --- a/test/elixir_react_starter/accounts_test.exs +++ b/test/elixir_react_starter/accounts_test.exs @@ -144,6 +144,18 @@ defmodule ElixirReactStarter.AccountsTest do refute Accounts.verify_user_link_token("garbage", "email_confirmation") end + test "rejects an unknown context instead of issuing an unverifiable token" do + user = :user |> build() |> insert() + + assert_raise FunctionClauseError, fn -> + Accounts.generate_user_link_token(user, "pasword_reset") + end + + assert_raise FunctionClauseError, fn -> + Accounts.verify_user_link_token("token", "pasword_reset") + end + end + test "expired tokens are rejected", %{user: user} do token = Accounts.generate_user_link_token(user, "email_confirmation") From eb1c75a24af897f025e2c19e53e8fe634003cded Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Ogle?= Date: Sat, 28 Nov 2026 13:34:06 -0500 Subject: [PATCH 06/15] refactor: send all mail through Email.deliver/1 Controllers piped emails into Mailer.deliver/1 and discarded the result, so delivery failures vanished, and the builders logged "Sending" before anything was sent. Email.deliver/1 now sends, logs the outcome with the recipient redacted, and returns :ok. An architecture test keeps it the only caller of the mailer. Also folds the repeated invalid-link redirects in AuthController and SettingsController into one helper each. --- docs/governance/PROGRESS.md | 15 ++++++++ docs/governance/TASKS.md | 4 +-- .../controllers/auth_controller.ex | 34 ++++++++---------- .../controllers/settings_controller.ex | 13 ++++--- lib/elixir_react_starter_web/email.ex | 36 ++++++++++++++----- test/architecture_test.exs | 18 ++++++++++ test/elixir_react_starter_web/email_test.exs | 22 +++++++++++- 7 files changed, 104 insertions(+), 38 deletions(-) diff --git a/docs/governance/PROGRESS.md b/docs/governance/PROGRESS.md index 43a2db4..6d0b52f 100644 --- a/docs/governance/PROGRESS.md +++ b/docs/governance/PROGRESS.md @@ -66,3 +66,18 @@ ends with `mix precommit` green and its own commit. only the two emailed contexts. A misspelt context raises `FunctionClauseError` instead of minting a token nothing will verify (regression test added). + +## Round 5 — mail delivery (B6, B7) + +- `Email.deliver/1` is the single path to `Mailer`: sends, logs the outcome + with the recipient redacted, always returns `:ok` (fire-and-forget is now a + property of the function, not a comment in one caller). +- Fixes two observability defects: the builders logged "Sending …" whether + or not anything was sent, and delivery errors were discarded with `_ =` + (the old comment claimed "the mailer logs failures"; Swoosh does not). + Failures now log at error level, which the Sentry logger handler captures. +- Repeated "invalid link" redirects collapsed into one private helper per + controller (3 → 1 in `AuthController`, 2 → 1 in `SettingsController`). +- New architecture rule: only `Email` references `Mailer`. +- Not covered by a test: the error-log branch (the Swoosh test adapter cannot + fail a delivery). diff --git a/docs/governance/TASKS.md b/docs/governance/TASKS.md index 38122cd..9a9a5da 100644 --- a/docs/governance/TASKS.md +++ b/docs/governance/TASKS.md @@ -13,8 +13,8 @@ decision — see the bottom section), `rejected` (with the reason). | B3 | `SharedData.serialize_user/1` is an ad-hoc serializer, against the `*_json.ex` rule | `UserJSON.data/1` | done — `refactor: make UserAuth and UserJSON the only owners of session and user shape` | | B4 | `SettingsController` writes the `"user_token"` session key itself; `UserAuth` owns it | `UserAuth.put_user_session/2`, used by `log_in_user/2`, `SettingsController`, `ConnCase` | done — same commit as B3 | | B5 | Link-token contexts are free strings; a typo issues a token no verifier accepts. `UserToken` builds link tokens in two near-identical functions and repeats the hash 5 times | Guard contexts against a closed list; one link-token builder; one `hash/1` | done — `refactor: guard link-token contexts and build every link token one way` | -| B6 | Mail delivery: `Email.x(...) \|> Mailer.deliver()` inline in two controllers, with the "fire and forget" rule stated once in a private helper; `Email` logs "Sending …" at build time, before (and regardless of) delivery | `Email.deliver/1` wrapper owning delivery + logging | todo | -| B7 | `AuthController` repeats the "invalid or expired reset link" redirect three times; `SettingsController` repeats the email-change failure redirect twice | One private helper per controller | todo | +| B6 | Mail delivery: `Email.x(...) \|> Mailer.deliver()` inline in two controllers, with the "fire and forget" rule stated once in a private helper; `Email` logs "Sending …" at build time, before (and regardless of) delivery | `Email.deliver/1` wrapper owning delivery + logging | done — `refactor: send all mail through Email.deliver/1` | +| B7 | `AuthController` repeats the "invalid or expired reset link" redirect three times; `SettingsController` repeats the email-change failure redirect twice | One private helper per controller | done — same commit as B6 | | B8 | `FallbackController` clauses for `:unauthorized`, `:bad_request`, `:not_found`, changeset have no producer in the app today | Keep: they pair with `Context`'s `*_ok` functions and are the template's documented extension point | rejected | ## Frontend diff --git a/lib/elixir_react_starter_web/controllers/auth_controller.ex b/lib/elixir_react_starter_web/controllers/auth_controller.ex index 64140c3..d28bf69 100644 --- a/lib/elixir_react_starter_web/controllers/auth_controller.ex +++ b/lib/elixir_react_starter_web/controllers/auth_controller.ex @@ -197,11 +197,10 @@ defmodule ElixirReactStarterWeb.AuthController do def forgot_password(conn, %{"email" => email}) do user = Accounts.get_user_by_email(email) - _ = - if user && User.confirmed?(user) do - raw_token = Accounts.generate_user_link_token(user, "password_reset") - Email.password_reset_email(user, raw_token) |> ElixirReactStarter.Mailer.deliver() - end + if user && User.confirmed?(user) do + raw_token = Accounts.generate_user_link_token(user, "password_reset") + user |> Email.password_reset_email(raw_token) |> Email.deliver() + end # Always claim success — don't leak which addresses are registered. conn @@ -222,29 +221,21 @@ defmodule ElixirReactStarterWeb.AuthController do def reset_password_page(conn, %{"token" => raw_token}) do case Accounts.verify_user_link_token(raw_token, "password_reset") do nil -> - conn - |> put_flash(:error, dgettext("app", "Invalid or expired reset link.")) - |> redirect(to: ~p"/forgot-password") + invalid_reset_link(conn) _user -> render_inertia(conn, "Auth/ResetPassword", %{token: raw_token}) end end - def reset_password_page(conn, _params) do - conn - |> put_flash(:error, dgettext("app", "Invalid or expired reset link.")) - |> redirect(to: ~p"/forgot-password") - end + def reset_password_page(conn, _params), do: invalid_reset_link(conn) def reset_password(conn, %{"token" => raw_token, "password" => password}) do # Re-verify the token at submit time — the page render might have # happened up to an hour ago. case Accounts.verify_user_link_token(raw_token, "password_reset") do nil -> - conn - |> put_flash(:error, dgettext("app", "Invalid or expired reset link.")) - |> redirect(to: ~p"/forgot-password") + invalid_reset_link(conn) user -> case Accounts.reset_user_password(user, %{password: password}) do @@ -272,9 +263,12 @@ defmodule ElixirReactStarterWeb.AuthController do # ============================================================================= defp send_confirmation_link(user) do raw_token = Accounts.generate_user_link_token(user, "email_confirmation") - # Fire-and-forget: a delivery error must not stall the auth flow. - # The mailer logs failures; callers don't need to react. - _ = Email.confirmation_email(user, raw_token) |> ElixirReactStarter.Mailer.deliver() - :ok + user |> Email.confirmation_email(raw_token) |> Email.deliver() + end + + defp invalid_reset_link(conn) do + conn + |> put_flash(:error, dgettext("app", "Invalid or expired reset link.")) + |> redirect(to: ~p"/forgot-password") end end diff --git a/lib/elixir_react_starter_web/controllers/settings_controller.ex b/lib/elixir_react_starter_web/controllers/settings_controller.ex index 0c0d5e9..faa56f5 100644 --- a/lib/elixir_react_starter_web/controllers/settings_controller.ex +++ b/lib/elixir_react_starter_web/controllers/settings_controller.ex @@ -16,7 +16,6 @@ defmodule ElixirReactStarterWeb.SettingsController do use ElixirReactStarterWeb, :controller alias ElixirReactStarter.Accounts - alias ElixirReactStarter.Mailer alias ElixirReactStarterWeb.Email alias ElixirReactStarterWeb.UserAuth @@ -37,8 +36,8 @@ defmodule ElixirReactStarterWeb.SettingsController do # Confirmation goes to the new address (proves ownership); the # old address gets a heads-up so the owner is alerted to the # change even if they never see the new inbox. - _ = Email.email_change_confirmation(new_email, raw_token) |> Mailer.deliver() - _ = Email.email_change_notification(user.email, new_email) |> Mailer.deliver() + new_email |> Email.email_change_confirmation(raw_token) |> Email.deliver() + user.email |> Email.email_change_notification(new_email) |> Email.deliver() conn |> put_flash( @@ -83,13 +82,13 @@ defmodule ElixirReactStarterWeb.SettingsController do |> redirect(to: ~p"/settings") {:error, _reason} -> - conn - |> put_flash(:error, dgettext("app", "That email change link is invalid or has expired.")) - |> redirect(to: ~p"/settings") + invalid_email_change_link(conn) end end - def confirm_email(conn, _params) do + def confirm_email(conn, _params), do: invalid_email_change_link(conn) + + defp invalid_email_change_link(conn) do conn |> put_flash(:error, dgettext("app", "That email change link is invalid or has expired.")) |> redirect(to: ~p"/settings") diff --git a/lib/elixir_react_starter_web/email.ex b/lib/elixir_react_starter_web/email.ex index de887f2..37f0dd2 100644 --- a/lib/elixir_react_starter_web/email.ex +++ b/lib/elixir_react_starter_web/email.ex @@ -40,6 +40,7 @@ defmodule ElixirReactStarterWeb.Email do router: ElixirReactStarterWeb.Router alias ElixirReactStarter.Log + alias ElixirReactStarter.Mailer alias ElixirReactStarterWeb.EmailHTML alias ElixirReactStarterWeb.EmailText alias ElixirReactStarterWeb.Endpoint @@ -66,8 +67,6 @@ defmodule ElixirReactStarterWeb.Email do dgettext("app", "If you didn't create this account, you can safely ignore this email.") } - Logger.info("Sending confirmation email to #{Log.redact_email(email)}") - new() |> to(email) |> from(@from) @@ -97,8 +96,6 @@ defmodule ElixirReactStarterWeb.Email do security: dgettext("app", "For your security, never share this link with anyone.") } - Logger.info("Sending password reset email to #{Log.redact_email(email)}") - new() |> to(email) |> from(@from) @@ -127,8 +124,6 @@ defmodule ElixirReactStarterWeb.Email do dgettext("app", "If you didn't request this change, you can safely ignore this email.") } - Logger.info("Sending email-change confirmation to #{Log.redact_email(new_email)}") - new() |> to(new_email) |> from(@from) @@ -158,8 +153,6 @@ defmodule ElixirReactStarterWeb.Email do ) } - Logger.info("Sending email-change notification to #{Log.redact_email(old_email)}") - new() |> to(old_email) |> from(@from) @@ -168,6 +161,33 @@ defmodule ElixirReactStarterWeb.Email do |> text_body(render_to_string(EmailText.email_change_notification(assigns))) end + @doc """ + Sends `email` and logs the outcome (recipient redacted). The only path + from the web layer to the mailer. + + Fire-and-forget: always returns `:ok`, because a delivery failure must not + stall the flow that triggered it (and, for the anti-enumeration + endpoints, must not change the response). Failures are logged at error + level, so they reach Sentry. + """ + @spec deliver(Swoosh.Email.t()) :: :ok + def deliver(%Swoosh.Email{} = email) do + recipient = email.to |> List.first() |> recipient_for_log() + + case Mailer.deliver(email) do + {:ok, _metadata} -> + Logger.info("Sent \"#{email.subject}\" to #{recipient}") + + {:error, reason} -> + Logger.error("Failed to send \"#{email.subject}\" to #{recipient}: #{inspect(reason)}") + end + + :ok + end + + defp recipient_for_log({_name, address}), do: Log.redact_email(address) + defp recipient_for_log(_recipient), do: Log.redact_email(nil) + defp render_to_string(template) do template |> Safe.to_iodata() diff --git a/test/architecture_test.exs b/test/architecture_test.exs index afa44bb..d611d5f 100644 --- a/test/architecture_test.exs +++ b/test/architecture_test.exs @@ -80,6 +80,24 @@ defmodule ElixirReactStarter.ArchitectureTest do assert offenders == [], "use a *_json.ex module's data/1:\n" <> Enum.join(offenders, "\n") end + test "only Email.deliver/1 talks to the mailer" do + offenders = + for path <- + files("lib/**/*.ex", + except: [ + "lib/elixir_react_starter_web/email.ex", + "lib/elixir_react_starter/mailer.ex" + ] + ), + segments <- aliases(path), + segments in [[:Mailer], [:ElixirReactStarter, :Mailer]], + uniq: true, + do: path + + assert offenders == [], + "send mail with ElixirReactStarterWeb.Email.deliver/1:\n" <> Enum.join(offenders, "\n") + end + # --------------------------------------------------------------------------- # AST helpers # --------------------------------------------------------------------------- diff --git a/test/elixir_react_starter_web/email_test.exs b/test/elixir_react_starter_web/email_test.exs index f0f6644..5ee8523 100644 --- a/test/elixir_react_starter_web/email_test.exs +++ b/test/elixir_react_starter_web/email_test.exs @@ -1,9 +1,14 @@ defmodule ElixirReactStarterWeb.EmailTest do use ExUnit.Case, async: true - # Email building logs an info line per send; keep test output clean. + # deliver/1 logs an info line per send; keep test output clean. @moduletag :capture_log + import ExUnit.CaptureLog + + require Logger + import Swoosh.TestAssertions + alias ElixirReactStarterWeb.Email @recipient %{email: "person@example.com"} @@ -68,4 +73,19 @@ defmodule ElixirReactStarterWeb.EmailTest do refute email.html_body =~ "token=" end end + + describe "deliver/1" do + test "sends the email and logs the recipient redacted" do + email = Email.confirmation_email(@recipient, @token) + # The test config logs warnings and up; let Email's info line through. + Logger.put_module_level(Email, :info) + on_exit(fn -> Logger.delete_module_level(Email) end) + + log = capture_log([level: :info], fn -> assert Email.deliver(email) == :ok end) + + assert_email_sent(email) + assert log =~ "p***@example.com" + refute log =~ "person@example.com" + end + end end From 7805feb90452859e488f238230a18f8f02187f44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Ogle?= Date: Sat, 28 Nov 2026 13:35:44 -0500 Subject: [PATCH 07/15] refactor: build every form field with TextField Six pages hand-wrote the same label, input and error markup eleven times, and none linked the error to its input. TextField owns that markup plus aria-invalid and aria-describedby, and replaces the shared inputClass string (components/ui.ts, deleted). A node contract test keeps raw inputs out of pages and layouts. --- AGENTS.md | 4 +- assets/js/architecture.test.ts | 22 ++++ assets/js/components/TextField.tsx | 54 ++++++++ assets/js/components/ui.ts | 3 - assets/js/pages/client/Settings.tsx | 118 +++++++----------- assets/js/pages/ssr/Auth/ForgotPassword.tsx | 29 ++--- assets/js/pages/ssr/Auth/Login.tsx | 51 +++----- assets/js/pages/ssr/Auth/Register.tsx | 54 +++----- .../js/pages/ssr/Auth/ResendConfirmation.tsx | 29 ++--- assets/js/pages/ssr/Auth/ResetPassword.tsx | 30 ++--- docs/architecture.md | 11 +- docs/governance/PROGRESS.md | 16 +++ docs/governance/TASKS.md | 4 +- 13 files changed, 222 insertions(+), 203 deletions(-) create mode 100644 assets/js/architecture.test.ts create mode 100644 assets/js/components/TextField.tsx delete mode 100644 assets/js/components/ui.ts diff --git a/AGENTS.md b/AGENTS.md index 9024cdf..a1abc43 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,8 +30,8 @@ These are the rules that must not be forgotten or looked up — they're the ones - Props that query the database, read storage, or do expensive work must be zero-argument functions (`assign_prop(conn, :items, fn -> ... end)`) so partial reloads skip excluded work. Keep authentication and authorization outside these callbacks so they run on every request. Inertia must stay on 3.1 or newer; 3.0.1 evaluates excluded callbacks. - Page components are **always** `.tsx` (TypeScript), under `assets/js/pages/` in one of two strategy dirs: **`pages/ssr/`** (server-rendered: public / SEO / first-paint pages) or **`pages/client/`** (client-only: authenticated, interactive, heavy pages — kept out of the Node SSR bundle). The strategy dir is stripped from the Inertia page name, so `render_inertia("Dashboard")` maps to `pages/client/Dashboard.tsx`. The `_pages.ts` / `_ssr_pages.ts` registries are auto-generated from these dirs by `build/generate-ssr-pages.cjs` — never edit them by hand. New public page → `ssr/`; new authed page → `client/` - Layout components live in `assets/js/layouts/` (e.g. `AppLayout`, `AuthLayout`) -- Reusable UI primitives live flat in `assets/js/components/` (`Button`, `Spinner`, `Select`, `DropdownMenu`, `AlertDialog`, …) — no sub-folders -- Forms use Inertia's `useForm` hook; errors come from `assign_errors(conn, changeset)` on the server +- Reusable UI primitives live flat in `assets/js/components/` (`Button`, `TextField`, `Spinner`, `Select`, `DropdownMenu`, `AlertDialog`, …) — no sub-folders +- Forms use Inertia's `useForm` hook; errors come from `assign_errors(conn, changeset)` on the server. Every text input is a `TextField` (`label`, `value`, `onChange`, `error={errors.}`; `hideLabel` for a visually hidden label) — it wires `htmlFor`, `aria-invalid` and `aria-describedby`. Pages and layouts never render a raw ``/`