--- url: /saas-starter/latest/guide/generate.md --- # Generate an app The template creates a complete app from one command. Its options decide what goes in it: whether it has accounts and organisations, how it stores data, and whether it comes with tests and an Aspire AppHost. What you get is your own code, with only the parts you chose: there's no package to update later, and nothing to switch off. ## The command Install the template once, then generate an app with the options you want: ```bash dotnet new install LibreSharp.Templates.SaasStarter dotnet new saas-starter -n MyApp --Auth identity --Persistence efcore cd MyApp git init && git add -A && git commit -m "Generated from LibreSharp.Templates.SaasStarter" ``` Leave an option out to take its default. `dotnet new saas-starter --help` lists them, and [Get started](../getting-started.md) has what you need installed first. ## The options | Option | Values | Default | What it decides | |---|---|---|---| | [`--Auth`](#auth) (`-A`) | `none`, `identity`, `saas` | `saas` | Accounts, and whether they belong to organisations | | [`--Persistence`](#persistence) (`-P`) | `marten`, `efcore` | `marten` | How data is stored in PostgreSQL | | [`--IncludeTests`](#includetests) (`-I`) | `true`, `false` | `true` | The API and end-to-end tests | | [`--Aspire`](#aspire) (`-As`) | `true`, `false` | `false` | An Aspire AppHost that starts everything for development | | [`--DisplayName`](#displayname) (`-D`) | text | the `-n` name | The name people see | `-n` gives the app's name, used for its solution, project, namespaces and container image (a C# name, such as `MyApp` or `Acme.Crm`; the current folder's name if you leave it out). `-o` says where to put it (a folder named after the app by default). Every combination is built and tested in the template's CI on every change, so any of them is a working app. ## Accounts and organisations: `--Auth` {#auth} How much of a SaaS app you get. Each choice adds to the one before. ### No accounts ```bash dotnet new saas-starter -n MyApp --Auth none ``` For an internal tool, or to start small and add sign-in yourself. Everyone shares the same data. * **The Todo example:** endpoints, validation, a background handler, scheduled reminders and live updates over SignalR, to copy for your own features. * **Messaging:** a transactional outbox and durable queues. * **File storage:** local disk, any S3-compatible store or Azure Blob Storage. * **Production:** a container image, Docker Compose with Caddy, health checks, OpenTelemetry and strict security headers. ### Accounts ```bash dotnet new saas-starter -n MyApp --Auth identity ``` For an app where each person has their own data. Everything under **No accounts**, and: * **Sign-in:** email and password, passkeys, Google and GitHub, two-factor authentication. * **Account security:** email confirmation, sessions, lockout, and emails about new devices and changes. * **Settings:** profile picture, email, password, sign-in methods, notifications, download your data, delete the account. * **Back office:** users, roles, invitations, an audit log, and failed messages to replay. ### Accounts and organisations ```bash dotnet new saas-starter -n MyApp ``` For a SaaS sold to teams: data belongs to an organisation, not a person. Everything under **Accounts**, and: * **Organisations:** each account gets one; members with Owner, Admin and Member roles, invitations by email, a switcher, and data kept apart per organisation. * **Billing:** plans, a reverse trial, features and limits per plan, and Stripe Checkout, the customer portal and webhooks. * **Integrations:** API keys, an MCP endpoint for AI assistants, signed webhooks, and encrypted secrets. * **Back office:** organisations, revenue and feature flags too. Not sure? Take the smallest that covers what you'll need in the first months. Adding organisations to an app later means moving its data under them, so if you'll sell to teams, start with `saas`. ## Data: `--Persistence` {#persistence} Both store everything in PostgreSQL, and both run the same features, tests and docs. They differ in how you write data access. | | `marten` (default) | `efcore` | |---|---|---| | **What it is** | [Marten](https://martendb.io/): documents stored as JSON, and event sourcing | Entity Framework Core: classes mapped to tables | | **Schema changes** | None to write: Marten updates its tables when the app starts | A migration for each change, applied when the app starts ([how](./how-to/add-a-migration.md)) | | **The Todo example** | Each Todo is an event stream, with a snapshot to query | Each Todo is a row | | **Choose it when** | You want to move fast, or keep a history of changes | Your team knows EF Core, or you want a relational schema to report on | ## Tests: `--IncludeTests` {#includetests} With `true` (the default), the app has `tests/ApiHost.Tests`, which runs the real app against a throwaway PostgreSQL in Docker (xUnit, Alba and Testcontainers), and `tests/e2e`, which drives it in Chrome (Playwright), including accessibility checks. The client's unit tests (Vitest) are always there, next to the code. See [Testing](./testing.md). Set it to `false` only if you'll write your own: the tests are also the best examples of how to test a new feature. ## Aspire: `--Aspire` {#aspire} With `true`, the app also has `src/ApiHost.AppHost`, an [Aspire](https://aspire.dev/) AppHost: `dotnet run --project src/ApiHost.AppHost` starts PostgreSQL, Mailpit, the API and the dev server, and opens a dashboard with their logs, traces and metrics. It's for development only; production is unchanged. Without it, `docker compose up -d` and two terminals do the same ([run it](./overview.md#run-it), [with Aspire](./how-to/run-with-aspire.md)). ## The name people see: `--DisplayName` {#displayname} `-n` must be a C# name, so `-n HairyNotes` would show "HairyNotes" everywhere people see the app's name. `--DisplayName "Hairy Notes"` sets that name instead: page titles, the header and sidebar, the link-preview tags, the name authenticator apps show (`Accounts:TwoFactorIssuer`) and, in development, the email sender (`Email:Smtp:From`; set yours for production). In the code it's `appName` in `src/Client/src/components/PageMeta.tsx`. Leave it out to use the `-n` name. ## After generating * **Commit the app as generated,** before changing it. Upgrading to a later version of the template applies the template's changes as a patch, which works best when that first commit is in your history ([Upgrading](../upgrading/)). * **Keep `.saas-starter.json`.** It records the template version, the app's name and the options you chose, so an upgrade needs only the version you want. * **Run it:** [A generated app](./overview.md) shows how, and what's in it. --- --- url: /saas-starter/latest/guide/overview.md --- # A generated app ::: tip What this page covers Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says which options a part is for. The copy in your app's `docs/` folder has only the parts for yours. `ApiHost` stands for your app's name. ::: What `dotnet new saas-starter` creates: a [Wolverine](https://wolverinefx.net/) API on ASP.NET Core and a React frontend (Vite, TypeScript, Tailwind CSS and [shadcn/ui](https://ui.shadcn.com/)), with data in PostgreSQL. In production the API also serves the built React app, so it deploys as one service. Which features it has depends on the options you generated it with: see [Generate an app](./generate.md). ## Run it You need the .NET 11 SDK, Node.js 22.22 or later, and Docker with the Compose plugin. ```bash docker compose up -d # PostgreSQL on localhost:5432 dotnet run --project src/ApiHost # the API on http://localhost:5133 ``` In a second terminal: ```bash cd src/Client npm install npm run dev # open http://localhost:5173 ``` The Vite dev server forwards `/api` (including the SignalR WebSocket) to the API, so the browser only talks to one origin. If something doesn't start, see [Troubleshooting](./troubleshooting.md). ::: info With Aspire **Or with Aspire:** one command starts the database, the API and the dev server, and opens a dashboard with their logs and traces ([how](./how-to/run-with-aspire.md)): ```bash cd src/Client && npm install && cd ../.. dotnet run --project src/ApiHost.AppHost # then open http://localhost:5173 ``` ::: ::: info With accounts Log in as **demo@example.com** / **Demo123!**. This user is created at startup in Development only, is an admin (so `/admin` works), and the dev server pre-fills the login form with it. Change it under `DevelopmentUser` in `src/ApiHost/appsettings.Development.json` and in `src/Client/.env.development`. `docker compose up -d` also starts [Mailpit](https://mailpit.axllent.org/), which catches every email the app sends in Development (confirmation, password reset, invitations): read them at http://localhost:8025. New accounts must confirm their email before they can log in; the demo user is already confirmed. ::: To try the API without the UI, open `src/ApiHost/ApiHost.http` in Visual Studio, Rider, or VS Code with the REST Client extension, and run the requests in order. Or browse the interactive API reference at http://localhost:5133/scalar (Development only), generated from the OpenAPI document at `/openapi/v1.json`. ## Project layout ``` src/ApiHost/ Program.cs All wiring: Wolverine, persistence, validation, SignalR, auth (With accounts) Program.cs All wiring: Wolverine, persistence, validation, SignalR (Without accounts) Features/Todos/ The example feature: endpoints, messages, handler, model Features/Auth/ Log in (password, Google/GitHub, passkey, two-factor code), register, confirm email, reset password (With accounts) Features/Account/ The signed-in user: profile, password, sign-in methods, passkeys, two-factor, delete account (With accounts) Features/Admin/ Admin endpoints: users, roles, locks and invitations (With accounts) Features/Organisations/ Organisations: switching, members and roles, invitations, joining (With organisations) Organisations/ The organisation model, its store, and choosing a session's organisation (With organisations) Realtime/AppHub.cs SignalR hub that pushes messages to browsers Storage/ File storage (IFileStorage): local disk, S3-compatible or Azure Blob Analytics/ Google Tag Manager settings, for the client's cookie banner Data/Marten/ Marten setup: event store, projections, indexes (Marten) Data/EfCore/ AppDbContext, migrations, and migrate-on-startup (EF Core) Identity/ Users, JWT and refresh tokens, roles, lockout, two-factor, rate limits (used by the features) (With accounts) Identity/Email/ Account emails: messages, their handler, and the SMTP sender (MailKit) (With accounts) Identity/External/ Google and GitHub set-up, and linking a provider's account to a user (With accounts) Identity/Passkeys/ Passkey set-up (Identity's WebAuthn support) (With accounts) src/ApiHost.AppHost/ Aspire AppHost: starts everything for development, with the dashboard (With Aspire) src/Client/src/ root.tsx, App.tsx The HTML document (with the description and link-preview tags), and the page frame routes.ts, routes/ Each URL and the route module for its page, with the page's title pages.ts Every page's path, and which are public: pre-rendered, and in sitemap.xml components/ Layout (header or sidebar, navigation, footer), Page, home and not-found pages features/todos/ Todo page, TanStack Query hooks, SignalR hook (useTodoRealtime) features/auth/ Login, register, email confirmation and password reset pages, route guards (With accounts) features/account/ Settings page, the sidebar's navigation and user menu (With accounts) features/admin/ Admin page (/admin): users, roles, locks and invitations (With accounts) features/organisations/ The organisation switcher, /organisation and its tabs (general, members, billing), and /join (With organisations) lib/api/ Typed API client generated from the OpenAPI document test/ Unit test setup: the fake API (MSW) and render helpers docs/ Documentation and how-to guides deploy/ Production docker-compose, Caddy, and a server guide tests/ApiHost.Tests/ Integration tests against a real PostgreSQL (With the tests) tests/e2e/ End-to-end tests in a real browser (Playwright) (With the tests) ``` ## Common tasks | Task | Command | |---|---| | Run the API tests (Docker must be running) | `dotnet test` | | Run the client's unit tests | `npm test` in `src/Client` | | Run the end-to-end tests ([how](./testing.md#end-to-end-tests)) | `npm test` in `tests/e2e`, with the app running | | Update the client's API types | `npm run gen:api` in `src/Client`, with the API running | | Lint the client | `npm run lint` in `src/Client` | | Add a database migration ([how](./how-to/add-a-migration.md)) | `dotnet ef migrations add --project src/ApiHost --output-dir Data/EfCore/Migrations` | | List the app's command-line tools (code generation, database, diagnostics) | `dotnet run --project src/ApiHost -- help` | | Publish for production ([deployment](./deployment.md)) | `dotnet publish src/ApiHost -c Release -o publish` | --- --- url: /saas-starter/latest/guide.md --- # Documentation ::: tip What this page covers Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says which options a part is for. The copy in your app's `docs/` folder has only the parts for yours. `ApiHost` stands for your app's name. ::: How ApiHost works, how to change it, and how to run it in production. ## Start here * [Tutorial: build a feature](./tutorial.md): a Contacts feature from start to finish: data, endpoints, validation, a background handler, live updates, the React page, and tests. * [Architecture](./architecture.md): how the example feature works, pattern by pattern. * [Troubleshooting](./troubleshooting.md): problems people run into, by what you see. ## Guides * [Accounts](./accounts.md): sign-in, emails, settings, lockout, roles and the admin page, Google/GitHub, passkeys and two-factor authentication. * [Plans, trials and limits](./billing.md): the plan catalogue, the reverse trial, feature flags, and checking features and limits. * [Integrations](./integrations.md): API keys, the MCP endpoint for AI assistants, webhooks (sent and received) and encrypted secrets. * [File storage](./file-storage.md): uploads to local disk, any S3-compatible store or Azure Blob Storage, with signed URLs. * [Analytics and cookie consent](./analytics.md): Google Tag Manager behind a consent banner, and adding Google Analytics, Datadog or Rollbar. * [Security](./security.md): what the app does to protect users and data, and what's left to you. [OWASP ASVS level 2](./asvs.md) maps it to the standard, requirement by requirement. * [Testing](./testing.md): the test suites, how to run them, and how to add tests. * [Observability](./observability.md): health checks, traces, metrics and logs. * [Deployment](./deployment.md): publishing, configuration, and running in production. For a step-by-step guide to a small server, see [deploy/README.md](./deploy-to-a-server.md). ## How-to guides * [Add a feature](./how-to/add-a-feature.md): from its data to its page and tests, step by step * [Where to add things](./extending.md): the places an app or a library plugs in, so its code survives updates from the template * [Run everything with Aspire](./how-to/run-with-aspire.md) * [Put Cloudflare in front](./how-to/put-cloudflare-in-front.md) * [Change the database schema (EF Core migrations)](./how-to/add-a-migration.md) * [Send email through your email provider](./how-to/configure-email.md) * [Set up "Continue with Google" and "Continue with GitHub"](./how-to/set-up-external-sign-in.md) * [Add a role](./how-to/add-a-role.md) * [Make someone an admin](./how-to/make-an-admin.md) * [Change the JWT signing key](./how-to/rotate-the-signing-key.md) * [Sign in from a mobile or desktop app](./how-to/sign-in-from-a-mobile-app.md) ## Reference * [Configuration](./reference/configuration.md): every setting, with its default. * [HTTP endpoints](./reference/endpoints.md): every endpoint, and who can call it. * [Messages](./reference/messages.md): the background messages and their handlers, and what's sent to browsers. --- --- url: /saas-starter/latest/guide/tutorial.md --- # Tutorial: build a feature ::: tip What this page covers Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says which options a part is for. The copy in your app's `docs/` folder has only the parts for yours. `ApiHost` stands for your app's name. ::: This tutorial adds a real feature to ApiHost from start to finish: **Contacts**, a small address book. ::: info With organisations Contacts belong to an organisation, so every member sees the same list. ::: ::: info With accounts, without organisations Each user has their own contacts. ::: ::: info Without accounts Everyone shares one list of contacts. ::: By the end, you'll have: * the data, stored as JSON documents with Marten; * the data, stored with EF Core, with a migration; * HTTP endpoints to add, list and delete contacts, with validation; * a message handled in the background, through Wolverine's transactional outbox; * live updates, so every open tab shows a new contact at once; * a React page with TanStack Query; * API tests and a client test. Each step shows the code to write and explains why it's written that way. The Todo feature uses the same patterns, with more besides; [Architecture](./architecture.md) goes through it. ## Before you start Have the app running as the [README](./overview.md) describes: `docker compose up -d`, the API (`dotnet run --project src/ApiHost`) and the client (`npm run dev` in `src/Client`). Development generates Wolverine's code at runtime, so the API only needs restarting when you add files, not to pick up every change. All paths below are from the repository root. The new files go in `src/ApiHost/Features/Contacts/` and `src/Client/src/features/contacts/`: a feature keeps its code together, and nothing needs registering, because Wolverine finds endpoints by their attributes and handlers by their names. ## 1. The data A contact has a name and, optionally, an email address. ::: info With organisations It belongs to an organisation. The app never sets or checks the organisation itself: a class that implements `ITenanted` gets a tenant id, which Wolverine fills in from the request's organisation and adds to every query. One organisation can't see another's contacts, even by mistake. ::: ::: info With accounts, without organisations It belongs to the user who added it, by their user id. Every query filters on the owner, so one user can't see another's contacts. ::: ::: code-group ```csharp [With organisations] using System.Text.Json.Serialization; using JasperFx.MultiTenancy; namespace ApiHost.Features.Contacts; // ITenanted: each contact belongs to an organisation (the tenant). Wolverine sets TenantId when a // contact is stored, and only finds the request's organisation's contacts. public class Contact : ITenanted { public Guid Id { get; set; } [JsonIgnore] public string? TenantId { get; set; } public string Name { get; set; } = string.Empty; public string? Email { get; set; } } ``` ```csharp [With accounts, without organisations] namespace ApiHost.Features.Contacts; public class Contact { public Guid Id { get; set; } public string OwnerId { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; public string? Email { get; set; } } ``` ```csharp [Without accounts] namespace ApiHost.Features.Contacts; public class Contact { public Guid Id { get; set; } public string Name { get; set; } = string.Empty; public string? Email { get; set; } } ``` ::: :::: info Marten Marten stores each contact as a JSON document in its own table, which it creates when the app starts. ::: info With organisations Tell Marten that contacts belong to organisations, in `src/ApiHost/Data/Marten/MartenPersistence.cs`. It adds a tenant id column, next to the Todos' line: ```csharp using ApiHost.Features.Contacts; using ApiHost.Features.Todos; ``` ```csharp opts.Schema.For().MultiTenanted(); opts.Schema.For().MultiTenanted(); ``` ::: ::: info With accounts, without organisations Index the owner, so listing a user's contacts stays fast, in `src/ApiHost/Data/Marten/MartenPersistence.cs`: ```csharp using ApiHost.Features.Contacts; using ApiHost.Features.Todos; ``` ```csharp opts.Schema.For() .Index(t => t.OwnerId); opts.Schema.For() .Index(c => c.OwnerId); ``` ::: ::: info Without accounts There's nothing to configure. ::: :::: :::: info EF Core EF Core needs a table for contacts. Add a `DbSet` to `src/ApiHost/Data/EfCore/AppDbContext.cs`: ```csharp using ApiHost.Features.Contacts; using ApiHost.Features.Todos; ``` ```csharp public DbSet Todos => Set(); public DbSet Contacts => Set(); ``` ::: info With organisations Wolverine adds a tenant id column to every `ITenanted` entity and filters on it, so there's nothing else to configure. ::: ::: info With accounts, without organisations In the same file's `OnModelCreating`, index the owner, so listing a user's contacts stays fast: ```csharp modelBuilder.Entity() .HasIndex(t => t.OwnerId); modelBuilder.Entity() .HasIndex(c => c.OwnerId); ``` ::: Then create the migration that adds the table. Install the EF Core tools once with `dotnet tool install --global dotnet-ef`, then: ```bash dotnet ef migrations add AddContacts --project src/ApiHost --output-dir Data/EfCore/Migrations ``` Read the migration it writes in `src/ApiHost/Data/EfCore/Migrations/`. The app applies it when it starts, here and in production ([more about migrations](./how-to/add-a-migration.md)). :::: ## 2. The request and its validation `POST /api/contacts` takes a name and an email address. A FluentValidation validator checks them before the endpoint runs: Wolverine finds it (`opts.UseFluentValidation()` in `Program.cs`), and answers an invalid request with `400 Bad Request` and a ProblemDetails body that lists the errors, which the client shows. ```csharp using FluentValidation; using Wolverine.Http; namespace ApiHost.Features.Contacts; // The body of POST /api/contacts. public record AddContact(string Name, string? Email); public class AddContactValidator : AbstractValidator { public AddContactValidator() { RuleFor(x => x.Name).NotEmpty().MaximumLength(100); RuleFor(x => x.Email).EmailAddress().MaximumLength(256).When(x => !string.IsNullOrEmpty(x.Email)); } } // The response: 201 Created, with the new contact's id, and its URL in the Location header. public record ContactCreationResponse : CreationResponse { public ContactCreationResponse(Guid id) : base($"/api/contacts/{id}") { Id = id; } public Guid Id { get; } } ``` ## 3. Messages Two messages tell the rest of the app what happened: * `ContactAdded` is for work that shouldn't hold up the request: here, telling open tabs. It's handled in the background (step 5). * `ContactsChanged` goes to browsers over SignalR, so open tabs refresh their list. The client recognises it by the name in `[MessageIdentity]`, `contacts-changed`, not by its .NET name. ::: info With organisations `ContactsChanged` goes only to the organisation's members: each browser connection joins a group for its organisation (`Realtime/RealtimeGroups.cs`). ::: ::: info With accounts, without organisations `ContactsChanged` goes only to the contact's owner: each browser connection joins a group for its user (`Realtime/RealtimeGroups.cs`). ::: ::: code-group ```csharp [With organisations] using ApiHost.Realtime; using Wolverine.Attributes; using Wolverine.SignalR; namespace ApiHost.Features.Contacts; // Published when a contact is added; ContactAddedHandler handles it in the background. public record ContactAdded(Guid ContactId); // Pushed to browsers over SignalR when a contact is added or deleted. [MessageIdentity("contacts-changed")] public record ContactsChanged(Guid ContactId); public static class ContactNotifications { // To every open tab of the organisation's members, and nobody else's. public static object Changed(Guid contactId, string organisationId) => new ContactsChanged(contactId).ToWebSocketGroup(RealtimeGroups.Organisation(organisationId)); } ``` ```csharp [With accounts, without organisations] using ApiHost.Realtime; using Wolverine.Attributes; using Wolverine.SignalR; namespace ApiHost.Features.Contacts; // Published when a contact is added; ContactAddedHandler handles it in the background. public record ContactAdded(Guid ContactId, string OwnerId); // Pushed to browsers over SignalR when a contact is added or deleted. [MessageIdentity("contacts-changed")] public record ContactsChanged(Guid ContactId); public static class ContactNotifications { // To every open tab of the contact's owner, and nobody else's. public static object Changed(Guid contactId, string ownerId) => new ContactsChanged(contactId).ToWebSocketGroup(RealtimeGroups.User(ownerId)); } ``` ```csharp [Without accounts] using Wolverine.Attributes; namespace ApiHost.Features.Contacts; // Published when a contact is added; ContactAddedHandler handles it in the background. public record ContactAdded(Guid ContactId); // Pushed to browsers over SignalR when a contact is added or deleted. [MessageIdentity("contacts-changed")] public record ContactsChanged(Guid ContactId); public static class ContactNotifications { // To every connected browser. public static object Changed(Guid contactId) => new ContactsChanged(contactId); } ``` ::: Route `ContactsChanged` to SignalR in `src/ApiHost/Program.cs`, next to the Todos' messages: ```csharp using ApiHost.Errors; using ApiHost.Features.Contacts; ``` ```csharp opts.PublishMessage().ToSignalR(); opts.PublishMessage().ToSignalR(); ``` ## 4. The endpoints An endpoint is a static method with a route attribute. Wolverine passes in what its parameters ask for: the request body, services such as the database session, the signed-in user, and route values such as `{id}`. What an endpoint returns matters too. The first value is the response; anything after it is a message to send. Wolverine saves the changes and the messages **in one database transaction** (the transactional outbox): if saving fails, no message is sent, and once it succeeds, the messages are delivered even if the app stops straight afterwards. That's why `Add` returns `ContactAdded` rather than doing the follow-up work itself. ::: info With organisations `[Authorize]` means only signed-in users can call them; anyone else gets `401 Unauthorized`. The organisation comes from the user's access token. The session Wolverine passes in is for that organisation, so `List` returns only its contacts, and `Delete` can't find another organisation's contact: it answers `404 Not Found`, as for a contact that doesn't exist. ::: ::: info With accounts, without organisations `[Authorize]` means only signed-in users can call them; anyone else gets `401 Unauthorized`. `Delete` answers `404 Not Found` for someone else's contact, as for one that doesn't exist, so nobody can find out which ids exist. ::: :::: info Marten ::: code-group ```csharp [With organisations] using System.Security.Claims; using ApiHost.Identity; using ApiHost.Organisations; using Marten; using Microsoft.AspNetCore.Authorization; using Wolverine; using Wolverine.Http; namespace ApiHost.Features.Contacts; public static class ContactEndpoints { [Authorize] [WolverinePost("/api/contacts")] public static (ContactCreationResponse, ContactAdded) Add(AddContact request, IDocumentSession session) { var contact = new Contact { Id = Guid.CreateVersion7(), Name = request.Name, Email = request.Email }; // Saved when the endpoint returns, in the same transaction as ContactAdded. session.Store(contact); return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id)); } [Authorize] [WolverineGet("/api/contacts")] public static Task> List(IQuerySession session, CancellationToken cancellationToken) => session.Query().OrderBy(c => c.Name).ToListAsync(cancellationToken); [Authorize] [WolverineDelete("/api/contacts/{id}")] public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, IDocumentSession session, ClaimsPrincipal user, CancellationToken cancellationToken) { var contact = await session.LoadAsync(id, cancellationToken); if (contact is null) { return (Results.NotFound(), []); } session.Delete(contact); return (Results.NoContent(), [ContactNotifications.Changed(contact.Id, user.GetOrganisationId().ToString())]); } } ``` ```csharp [With accounts, without organisations] using System.Security.Claims; using ApiHost.Identity; using Marten; using Microsoft.AspNetCore.Authorization; using Wolverine; using Wolverine.Http; namespace ApiHost.Features.Contacts; public static class ContactEndpoints { [Authorize] [WolverinePost("/api/contacts")] public static (ContactCreationResponse, ContactAdded) Add(AddContact request, IDocumentSession session, ClaimsPrincipal user) { var contact = new Contact { Id = Guid.CreateVersion7(), OwnerId = user.GetUserId(), Name = request.Name, Email = request.Email }; // Saved when the endpoint returns, in the same transaction as ContactAdded. session.Store(contact); return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id, contact.OwnerId)); } [Authorize] [WolverineGet("/api/contacts")] public static Task> List(IQuerySession session, ClaimsPrincipal user, CancellationToken cancellationToken) { var ownerId = user.GetUserId(); return session.Query().Where(c => c.OwnerId == ownerId).OrderBy(c => c.Name).ToListAsync(cancellationToken); } [Authorize] [WolverineDelete("/api/contacts/{id}")] public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, IDocumentSession session, ClaimsPrincipal user, CancellationToken cancellationToken) { var contact = await session.LoadAsync(id, cancellationToken); if (contact is null || contact.OwnerId != user.GetUserId()) { return (Results.NotFound(), []); } session.Delete(contact); return (Results.NoContent(), [ContactNotifications.Changed(contact.Id, contact.OwnerId)]); } } ``` ```csharp [Without accounts] using Marten; using Wolverine; using Wolverine.Http; namespace ApiHost.Features.Contacts; public static class ContactEndpoints { [WolverinePost("/api/contacts")] public static (ContactCreationResponse, ContactAdded) Add(AddContact request, IDocumentSession session) { var contact = new Contact { Id = Guid.CreateVersion7(), Name = request.Name, Email = request.Email }; // Saved when the endpoint returns, in the same transaction as ContactAdded. session.Store(contact); return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id)); } [WolverineGet("/api/contacts")] public static Task> List(IQuerySession session, CancellationToken cancellationToken) => session.Query().OrderBy(c => c.Name).ToListAsync(cancellationToken); [WolverineDelete("/api/contacts/{id}")] public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, IDocumentSession session, CancellationToken cancellationToken) { var contact = await session.LoadAsync(id, cancellationToken); if (contact is null) { return (Results.NotFound(), []); } session.Delete(contact); return (Results.NoContent(), [ContactNotifications.Changed(contact.Id)]); } } ``` ::: :::: :::: info EF Core ::: code-group ```csharp [With organisations] using System.Security.Claims; using ApiHost.Data.EfCore; using ApiHost.Identity; using ApiHost.Organisations; using Microsoft.AspNetCore.Authorization; using Microsoft.EntityFrameworkCore; using Wolverine; using Wolverine.Http; namespace ApiHost.Features.Contacts; public static class ContactEndpoints { [Authorize] [WolverinePost("/api/contacts")] public static (ContactCreationResponse, ContactAdded) Add(AddContact request, AppDbContext db) { var contact = new Contact { Id = Guid.CreateVersion7(), Name = request.Name, Email = request.Email }; // Saved when the endpoint returns, in the same transaction as ContactAdded. db.Contacts.Add(contact); return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id)); } [Authorize] [WolverineGet("/api/contacts")] public static async Task> List(AppDbContext db, CancellationToken cancellationToken) => await db.Contacts.AsNoTracking().OrderBy(c => c.Name).ToListAsync(cancellationToken); [Authorize] [WolverineDelete("/api/contacts/{id}")] public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, AppDbContext db, ClaimsPrincipal user, CancellationToken cancellationToken) { var contact = await db.Contacts.FirstOrDefaultAsync(c => c.Id == id, cancellationToken); if (contact is null) { return (Results.NotFound(), []); } db.Contacts.Remove(contact); return (Results.NoContent(), [ContactNotifications.Changed(contact.Id, user.GetOrganisationId().ToString())]); } } ``` ```csharp [With accounts, without organisations] using System.Security.Claims; using ApiHost.Data.EfCore; using ApiHost.Identity; using Microsoft.AspNetCore.Authorization; using Microsoft.EntityFrameworkCore; using Wolverine; using Wolverine.Http; namespace ApiHost.Features.Contacts; public static class ContactEndpoints { [Authorize] [WolverinePost("/api/contacts")] public static (ContactCreationResponse, ContactAdded) Add(AddContact request, AppDbContext db, ClaimsPrincipal user) { var contact = new Contact { Id = Guid.CreateVersion7(), OwnerId = user.GetUserId(), Name = request.Name, Email = request.Email }; // Saved when the endpoint returns, in the same transaction as ContactAdded. db.Contacts.Add(contact); return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id, contact.OwnerId)); } [Authorize] [WolverineGet("/api/contacts")] public static async Task> List(AppDbContext db, ClaimsPrincipal user, CancellationToken cancellationToken) { var ownerId = user.GetUserId(); return await db.Contacts.AsNoTracking().Where(c => c.OwnerId == ownerId).OrderBy(c => c.Name).ToListAsync(cancellationToken); } [Authorize] [WolverineDelete("/api/contacts/{id}")] public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, AppDbContext db, ClaimsPrincipal user, CancellationToken cancellationToken) { var contact = await db.Contacts.FirstOrDefaultAsync(c => c.Id == id, cancellationToken); if (contact is null || contact.OwnerId != user.GetUserId()) { return (Results.NotFound(), []); } db.Contacts.Remove(contact); return (Results.NoContent(), [ContactNotifications.Changed(contact.Id, contact.OwnerId)]); } } ``` ```csharp [Without accounts] using ApiHost.Data.EfCore; using Microsoft.EntityFrameworkCore; using Wolverine; using Wolverine.Http; namespace ApiHost.Features.Contacts; public static class ContactEndpoints { [WolverinePost("/api/contacts")] public static (ContactCreationResponse, ContactAdded) Add(AddContact request, AppDbContext db) { var contact = new Contact { Id = Guid.CreateVersion7(), Name = request.Name, Email = request.Email }; // Saved when the endpoint returns, in the same transaction as ContactAdded. db.Contacts.Add(contact); return (new ContactCreationResponse(contact.Id), new ContactAdded(contact.Id)); } [WolverineGet("/api/contacts")] public static async Task> List(AppDbContext db, CancellationToken cancellationToken) => await db.Contacts.AsNoTracking().OrderBy(c => c.Name).ToListAsync(cancellationToken); [WolverineDelete("/api/contacts/{id}")] public static async Task<(IResult, OutgoingMessages)> Delete(Guid id, AppDbContext db, CancellationToken cancellationToken) { var contact = await db.Contacts.FirstOrDefaultAsync(c => c.Id == id, cancellationToken); if (contact is null) { return (Results.NotFound(), []); } db.Contacts.Remove(contact); return (Results.NoContent(), [ContactNotifications.Changed(contact.Id)]); } } ``` ::: :::: ## 5. Background work `ContactAdded` is handled by a class whose name ends in `Handler`, which is how Wolverine finds it. Its `Handle` method runs after the request has finished, from a durable queue in PostgreSQL: if it fails, Wolverine retries it, and if the app stops first, it runs after the restart. This handler only tells open tabs, but this is the place for anything slow or unreliable that follows from adding a contact: sending an email, calling another service, or updating a search index. What it returns is sent on as messages, as with the endpoints. ::: code-group ```csharp [With organisations] using JasperFx.MultiTenancy; namespace ApiHost.Features.Contacts; public class ContactAddedHandler { // tenantId: the organisation the contact belongs to. Wolverine carries it on every message // sent while handling a request. public static object Handle(ContactAdded message, TenantId tenantId, ILogger logger) { logger.LogInformation("Contact {ContactId} was added", message.ContactId); return ContactNotifications.Changed(message.ContactId, tenantId.Value); } } ``` ```csharp [With accounts, without organisations] namespace ApiHost.Features.Contacts; public class ContactAddedHandler { public static object Handle(ContactAdded message, ILogger logger) { logger.LogInformation("Contact {ContactId} was added", message.ContactId); return ContactNotifications.Changed(message.ContactId, message.OwnerId); } } ``` ```csharp [Without accounts] namespace ApiHost.Features.Contacts; public class ContactAddedHandler { public static object Handle(ContactAdded message, ILogger logger) { logger.LogInformation("Contact {ContactId} was added", message.ContactId); return ContactNotifications.Changed(message.ContactId); } } ``` ::: ::::: info With accounts ### Deleting the data with its owner ::: info With organisations When an organisation is deleted, its contacts must go too. The app publishes `OrganisationDeleted` for that organisation, and any feature can handle it: ::: ::: info Without organisations When someone deletes their account, their contacts must go too. The app publishes `AccountDeleted`, and any feature can handle it: ::: :::: info Marten ::: code-group ```csharp [With organisations] using ApiHost.Organisations; using Marten; namespace ApiHost.Features.Contacts; // The message is sent for the deleted organisation, so the session only finds its contacts. public static class DeleteContactsOfDeletedOrganisationHandler { public static async Task Handle(OrganisationDeleted message, IDocumentSession session, CancellationToken cancellationToken) { var ids = await session.Query().Select(c => c.Id).ToListAsync(cancellationToken); foreach (var id in ids) { session.Delete(id); } } } ``` ```csharp [Without organisations] using ApiHost.Identity; using Marten; namespace ApiHost.Features.Contacts; public static class DeleteContactsOfDeletedAccountHandler { public static void Handle(AccountDeleted message, IDocumentSession session) => session.DeleteWhere(c => c.OwnerId == message.UserId); } ``` ::: :::: :::: info EF Core ::: code-group ```csharp [With organisations] using ApiHost.Data.EfCore; using ApiHost.Organisations; using Microsoft.EntityFrameworkCore; namespace ApiHost.Features.Contacts; // The message is sent for the deleted organisation, so the DbContext only sees its contacts; the // filter on TenantId is a second guard. public static class DeleteContactsOfDeletedOrganisationHandler { public static async Task Handle(OrganisationDeleted message, AppDbContext db, CancellationToken cancellationToken) { var organisationId = message.OrganisationId.ToString(); await db.Contacts.Where(c => c.TenantId == organisationId).ExecuteDeleteAsync(cancellationToken); } } ``` ```csharp [Without organisations] using ApiHost.Data.EfCore; using ApiHost.Identity; using Microsoft.EntityFrameworkCore; namespace ApiHost.Features.Contacts; public static class DeleteContactsOfDeletedAccountHandler { public static async Task Handle(AccountDeleted message, AppDbContext db, CancellationToken cancellationToken) => await db.Contacts.Where(c => c.OwnerId == message.UserId).ExecuteDeleteAsync(cancellationToken); } ``` ::: :::: ::::: ## 6. Try the API Restart the API, since you added files, and open the API reference at http://localhost:5133/scalar/, which lists the new endpoints. You can call them from there, or go straight on to the page. ::: info With accounts They need an access token: sign in with `POST /api/auth/login` (`demo@example.com`, `Demo123!`) and use the `accessToken` it returns. ::: ## 7. The client's API types The client calls the API through a typed client (`src/Client/src/lib/api/client.ts`), whose types are generated from the API's OpenAPI document. With the API running, update them: ```bash cd src/Client npm run gen:api ``` `src/Client/src/lib/api/schema.d.ts` now has `/api/contacts`, so TypeScript checks every call's path, parameters and body. ## 8. Queries TanStack Query fetches and caches the list. The add and delete mutations mark it stale when they succeed, and it's fetched again wherever it's shown. ```ts import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api } from '../../lib/api/client' import { problemMessage } from '../../lib/api/problemDetails' // The contact list's cache key: anything that changes contacts invalidates it. export const contactKeys = { all: ['contacts'] as const, } export function useContacts() { return useQuery({ queryKey: contactKeys.all, // Contacts also change in other tabs, so fetch them again whenever the page opens. refetchOnMount: 'always', queryFn: async () => { const { data, response } = await api.GET('/api/contacts') if (!response.ok || !data) throw new Error('Could not load the contacts.') return data }, }) } export function useAddContact() { const queryClient = useQueryClient() return useMutation({ mutationFn: async ({ name, email }: { name: string; email: string }) => { const { error, response } = await api.POST('/api/contacts', { body: { name, email: email || null } }) // A validation failure is a 400 with ProblemDetails: show its message. if (!response.ok) throw new Error(problemMessage(error, 'Could not add the contact.')) }, onSuccess: () => queryClient.invalidateQueries({ queryKey: contactKeys.all }), }) } export function useDeleteContact() { const queryClient = useQueryClient() return useMutation({ mutationFn: async (id: string) => { const { response } = await api.DELETE('/api/contacts/{id}', { params: { path: { id } } }) if (!response.ok) throw new Error('Could not delete the contact.') }, onSuccess: () => queryClient.invalidateQueries({ queryKey: contactKeys.all }), }) } ``` ## 9. The page The page lists the contacts, with a form to add one and a button to delete each. `useRealtime` listens on the tab's connection to the API's SignalR hub: when `contacts-changed` arrives, from this tab or another, the list is fetched again. After a reconnect, it's fetched anyway, in case a change was missed. The components (`Button`, `Input`) are [shadcn/ui](https://ui.shadcn.com/)'s, in `src/Client/src/components/ui/`. ```tsx import { useState } from 'react' import { useQueryClient } from '@tanstack/react-query' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Page } from '../../components/Page' import { useRealtime } from '../../lib/realtime' import { contactKeys, useAddContact, useContacts, useDeleteContact } from './contactQueries' export function ContactsPage() { const [name, setName] = useState('') const [email, setEmail] = useState('') const contacts = useContacts() const addContact = useAddContact() const deleteContact = useDeleteContact() const queryClient = useQueryClient() // Live updates: a contact was added or deleted, here or in another tab. useRealtime( (message) => { if (message.type === 'contacts-changed') void queryClient.invalidateQueries({ queryKey: contactKeys.all }) }, () => void queryClient.invalidateQueries({ queryKey: contactKeys.all }), ) function add(event: React.FormEvent) { event.preventDefault() if (!name.trim()) return addContact.mutate( { name, email }, { onSuccess: () => { setName('') setEmail('') }, }, ) } return (
setName(e.target.value)} placeholder="Name" /> setEmail(e.target.value)} placeholder="Email (optional)" />
{(addContact.error ?? deleteContact.error) && (

{(addContact.error ?? deleteContact.error)?.message}

)} {contacts.isPending ? (

Loading…

) : contacts.isError ? (

{contacts.error.message}

) : contacts.data.length === 0 ? (

No contacts yet.

) : (
    {contacts.data.map((contact) => (
  • {contact.name} {contact.email && {contact.email}}
  • ))}
)}
) } ``` A page also needs a route module, which gives its title: ```tsx import type { PageHandle } from '../components/PageMeta' import { ContactsPage } from '../features/contacts/ContactsPage' export const handle: PageHandle = { title: 'Contacts' } export default ContactsPage ``` Add its URL to `src/Client/src/routes.ts`. ::: info With accounts It goes next to the Todos, inside the `require-auth` layout, which sends signed-out visitors to the login page and back: ```ts route('todos', 'routes/todos.tsx'), route('contacts', 'routes/contacts.tsx'), ``` ::: ::: info Without accounts ```ts route('todos', 'routes/todos.tsx'), route('contacts', 'routes/contacts.tsx'), ``` ::: And to `src/Client/src/pages.ts`, the list of every page that the API and the build read (a unit test checks the two lists match). `index: false` keeps it out of search engines and the sitemap, as it's for signed-in use: ```ts { path: '/todos', index: false }, { path: '/contacts', index: false }, ``` Finally, link to it from the navigation. ::: info With accounts The signed-in links are in the sidebar, set in `src/Client/src/features/account/AccountNavigation.tsx`. The app's own pages go in its first group, next to the Todos, each with an icon from [Lucide](https://lucide.dev/icons): ```tsx ListChecksIcon, ContactIcon, ``` ```tsx Todos Contacts ``` ::: ::: info Without accounts The links are in `src/Client/src/App.tsx`: ```tsx import { Layout, NavItem } from './components/Layout' // The frame around every page (root.tsx renders it): the header, the current page and the footer. export function App() { return ( Todos Contacts } /> ) } ``` ::: Open http://localhost:5173/contacts and add a contact. Open the page in a second tab too: a contact added in one appears in the other, through the background handler and SignalR. ## 10. Tests :::: info With the tests ### The API The API tests run the whole app in memory against a real PostgreSQL in Docker (Testcontainers), with Alba sending the requests. `ExecuteAndWaitAsync` also waits for the messages a request sends to be handled, so a test can check that the background work ran. ::: info With accounts `CreateUserAndGetAccessTokenAsync` registers a new user each time, so each test has its own data, and the last test checks that one user can't see or delete another's contacts. ::: ::: code-group ```csharp [With accounts] using System.Net; using Alba; using ApiHost.Features.Contacts; using Wolverine.Tracking; namespace ApiHost.Tests; [Collection("api")] public class ContactTests { private readonly AppFixture _fixture; public ContactTests(AppFixture fixture) { _fixture = fixture; } private async Task NewUserAsync() => await _fixture.CreateUserAndGetAccessTokenAsync(); private Task Send(string? token, Action configure) => _fixture.Host.Scenario(s => { if (token is not null) { s.WithBearerToken(token); } configure(s); }); private async Task> ListAsync(string? token) { var result = await Send(token, s => { s.Get.Url("/api/contacts"); s.StatusCodeShouldBeOk(); }); return result.ReadAsJson>()!; } [Fact] public async Task add_list_and_delete_a_contact() { var token = await NewUserAsync(); var name = $"Ada Lovelace {Guid.NewGuid()}"; // Waits for ContactAdded to be handled, too. var tracked = await _fixture.Host.ExecuteAndWaitAsync(() => Send(token, s => { s.Post.Json(new AddContact(name, "ada@example.com")).ToUrl("/api/contacts"); s.StatusCodeShouldBe(HttpStatusCode.Created); })); var contact = Assert.Single(await ListAsync(token), c => c.Name == name); Assert.Equal("ada@example.com", contact.Email); Assert.Contains(tracked.Executed.MessagesOf(), m => m.ContactId == contact.Id); await Send(token, s => { s.Delete.Url($"/api/contacts/{contact.Id}"); s.StatusCodeShouldBe(HttpStatusCode.NoContent); }); Assert.DoesNotContain(await ListAsync(token), c => c.Id == contact.Id); await Send(token, s => { s.Delete.Url($"/api/contacts/{contact.Id}"); s.StatusCodeShouldBe(HttpStatusCode.NotFound); }); } [Theory] [InlineData("", null)] [InlineData("Ada", "not an email address")] public async Task an_invalid_contact_is_rejected(string name, string? email) { var token = await NewUserAsync(); await Send(token, s => { s.Post.Json(new AddContact(name, email)).ToUrl("/api/contacts"); s.StatusCodeShouldBe(HttpStatusCode.BadRequest); }); } [Fact] public async Task nobody_else_can_see_or_delete_a_contact() { var owner = await NewUserAsync(); var someoneElse = await NewUserAsync(); var name = $"Private contact {Guid.NewGuid()}"; await Send(owner, s => { s.Post.Json(new AddContact(name, null)).ToUrl("/api/contacts"); s.StatusCodeShouldBe(HttpStatusCode.Created); }); var contact = Assert.Single(await ListAsync(owner), c => c.Name == name); Assert.DoesNotContain(await ListAsync(someoneElse), c => c.Id == contact.Id); await Send(someoneElse, s => { s.Delete.Url($"/api/contacts/{contact.Id}"); s.StatusCodeShouldBe(HttpStatusCode.NotFound); }); await Send(null, s => { s.Get.Url("/api/contacts"); s.StatusCodeShouldBe(HttpStatusCode.Unauthorized); }); } } ``` ```csharp [Without accounts] using System.Net; using Alba; using ApiHost.Features.Contacts; using Wolverine.Tracking; namespace ApiHost.Tests; [Collection("api")] public class ContactTests { private readonly AppFixture _fixture; public ContactTests(AppFixture fixture) { _fixture = fixture; } // Without accounts, nobody signs in. private static Task NewUserAsync() => Task.FromResult(null); private Task Send(string? token, Action configure) => _fixture.Host.Scenario(s => { if (token is not null) { s.WithBearerToken(token); } configure(s); }); private async Task> ListAsync(string? token) { var result = await Send(token, s => { s.Get.Url("/api/contacts"); s.StatusCodeShouldBeOk(); }); return result.ReadAsJson>()!; } [Fact] public async Task add_list_and_delete_a_contact() { var token = await NewUserAsync(); var name = $"Ada Lovelace {Guid.NewGuid()}"; // Waits for ContactAdded to be handled, too. var tracked = await _fixture.Host.ExecuteAndWaitAsync(() => Send(token, s => { s.Post.Json(new AddContact(name, "ada@example.com")).ToUrl("/api/contacts"); s.StatusCodeShouldBe(HttpStatusCode.Created); })); var contact = Assert.Single(await ListAsync(token), c => c.Name == name); Assert.Equal("ada@example.com", contact.Email); Assert.Contains(tracked.Executed.MessagesOf(), m => m.ContactId == contact.Id); await Send(token, s => { s.Delete.Url($"/api/contacts/{contact.Id}"); s.StatusCodeShouldBe(HttpStatusCode.NoContent); }); Assert.DoesNotContain(await ListAsync(token), c => c.Id == contact.Id); await Send(token, s => { s.Delete.Url($"/api/contacts/{contact.Id}"); s.StatusCodeShouldBe(HttpStatusCode.NotFound); }); } [Theory] [InlineData("", null)] [InlineData("Ada", "not an email address")] public async Task an_invalid_contact_is_rejected(string name, string? email) { var token = await NewUserAsync(); await Send(token, s => { s.Post.Json(new AddContact(name, email)).ToUrl("/api/contacts"); s.StatusCodeShouldBe(HttpStatusCode.BadRequest); }); } } ``` ::: Run them with `dotnet test` (Docker must be running). :::: ### The page The client's tests render a component with Vitest and React Testing Library, with the API faked by [MSW](https://mswjs.io/), so they run in a second without the API. The realtime connection is replaced by a stand-in that does nothing. ```tsx import { screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { http, HttpResponse } from 'msw' import { beforeEach, describe, expect, it, vi } from 'vitest' import { server } from '../../test/server' import { renderPage } from '../../test/render' import { ContactsPage } from './ContactsPage' // No SignalR connection in unit tests. vi.mock('../../lib/realtime', () => ({ useRealtime: () => {} })) type Contact = { id: string; name: string; email: string | null } describe('ContactsPage', () => { let contacts: Contact[] beforeEach(() => { contacts = [{ id: '1', name: 'Ada Lovelace', email: 'ada@example.com' }] server.use( http.get('*/api/contacts', () => HttpResponse.json(contacts)), http.post('*/api/contacts', async ({ request }) => { const body = (await request.json()) as { name: string; email: string | null } contacts = [...contacts, { id: '2', ...body }] return HttpResponse.json({ id: '2' }, { status: 201 }) }), http.delete('*/api/contacts/:id', ({ params }) => { contacts = contacts.filter((c) => c.id !== params.id) return new HttpResponse(null, { status: 204 }) }), ) }) it('adds a contact and shows the refreshed list', async () => { renderPage(, '/contacts') await screen.findByText('Ada Lovelace') await userEvent.type(screen.getByPlaceholderText('Name'), 'Grace Hopper') await userEvent.click(screen.getByRole('button', { name: 'Add' })) expect(await screen.findByText('Grace Hopper')).toBeInTheDocument() expect(screen.getByPlaceholderText('Name')).toHaveValue('') }) it('deletes a contact', async () => { renderPage(, '/contacts') await userEvent.click(await screen.findByRole('button', { name: 'Delete Ada Lovelace' })) expect(await screen.findByText('No contacts yet.')).toBeInTheDocument() }) it('shows the validation message when adding fails', async () => { server.use( http.post('*/api/contacts', () => HttpResponse.json({ title: 'Validation failed', errors: { Name: ['Name is too long.'] } }, { status: 400 }), ), ) renderPage(, '/contacts') await screen.findByText('Ada Lovelace') await userEvent.type(screen.getByPlaceholderText('Name'), 'Grace Hopper') await userEvent.click(screen.getByRole('button', { name: 'Add' })) expect(await screen.findByRole('alert')).toHaveTextContent('Name is too long.') }) }) ``` Run them with `npm test` in `src/Client`. See [Testing](./testing.md) for the end-to-end tests and more. ## What's next The feature works. Some things a real feature often adds: * **A plan limit:** count contacts against the organisation's plan and answer `402 Payment Required` when it's full, as `CreateTodoEndpoint` does with `OpenTodos` ([Plans, trials and limits](./billing.md)). * **Webhooks:** tell the organisation's webhooks about new contacts with `WebhookEvents.Raise`, as the Todos do ([Integrations](./integrations.md)). * **The data export:** include contacts in an organisation's data download, like `Features/Todos/TodosOrganisationData.cs`. * **The data export:** include contacts in a user's data download, like `Features/Todos/TodosPersonalData.cs`. * **Event sourcing:** the Todos keep every change as an event, with Marten's event store. Use it when the history matters, such as for an audit trail or undo. * **Event sourcing:** for a history of every change, see how the Todos are built with Marten in the [online documentation](https://libresharp.github.io/saas-starter/latest/guide/architecture). * **Editing a contact:** a `PUT /api/contacts/{id}` endpoint, with its own validator. The [how-to for adding a feature](./how-to/add-a-feature.md) goes through these steps for next time, and [Where to add things](./extending.md) lists the places an app plugs into, so your code survives updates from the template. --- --- url: /saas-starter/latest/guide/architecture.md --- # Architecture ::: tip What this page covers Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says which options a part is for. The copy in your app's `docs/` folder has only the parts for yours. `ApiHost` stands for your app's name. ::: The Todo feature is a working example of each pattern. Copy it when you add your own features (the [tutorial](./tutorial.md) builds one step by step). ## The big picture One ASP.NET Core app serves the API, the realtime connection and the built React client, and PostgreSQL holds both the data and Wolverine's messages, so there's no message broker to run. ```mermaid flowchart TB browser["Browser: the React app"] subgraph host["ASP.NET Core app: one container"] endpoints["HTTP endpoints
Features/*"] handlers["Message handlers
run in the background"] hub["SignalR hub"] client["Built React client
wwwroot"] end db[("PostgreSQL
data, outbox, queues,
scheduled messages")] storage[("File storage
disk, S3 or Azure")] browser -- "HTTPS /api" --> endpoints client -- "pages and scripts" --> browser endpoints -- "changes and messages,
in one transaction" --> db db -- "durable queues" --> handlers handlers -- "messages for browsers" --> hub hub -- "WebSocket" --> browser browser -- "uploads and downloads,
signed URLs" --> storage ``` ## A request, step by step Completing a Todo shows how an endpoint, the outbox, a background handler and the realtime connection work together: ```mermaid sequenceDiagram participant B as Browser participant E as CompleteTodoEndpoint participant DB as PostgreSQL participant H as TodoCompletedHandler participant S as SignalR hub B->>E: POST /api/todos/{id}/complete Note over E: validation and loading run first E->>DB: the change and TodoCompleted, in one transaction E-->>B: 204 No Content DB-->>H: TodoCompleted, from a durable local queue Note over H: retried on failure, survives a restart H->>S: TodoChanged, cascaded from the handler S-->>B: todo-changed Note over B: every open tab refetches its Todos ``` If the transaction rolls back, `TodoCompleted` is never sent; if the app stops before the handler runs, it runs after the restart. ## How messages are delivered What happens to a message after an endpoint or a handler returns it: ```mermaid flowchart LR sent["Returned by an endpoint
or a handler"] -- "in the same transaction
as the data" --> stored[("PostgreSQL
outbox and queues")] stored --> handler["Its handler runs"] handler -- "succeeds" --> done["Done; the messages it
returns go the same way"] handler -- "fails" --> retry["Tried again,
by its retry rules"] retry --> handler retry -- "keeps failing" --> dead[("Dead letters
wolverine_dead_letters")] dead -- "replayed" --> stored ``` * **Stored with the data.** `opts.Policies.AutoApplyTransactions()` commits each endpoint's and handler's changes together with the messages it sends, and `UseDurableLocalQueues()` keeps the queues in PostgreSQL (both in `Program.cs`). A message is never sent for a change that was rolled back, and never lost when the app stops: it's handled after the restart. * **Make handlers safe to repeat.** A handler's changes to the database are committed with the message being marked as handled, but work outside the database, such as an email or a call to another service, can happen again if the app stops at the wrong moment. Check the state first, as `TodoReminderDueHandler` skips a Todo that was completed in the meantime. * **One message, several handlers.** When more than one feature handles a message (such as `AccountDeleted`), each handler gets its own queue, transaction and retries (`MultipleHandlerBehavior.Separated` in `Program.cs`): one feature's failure doesn't undo or hold up another's. With Marten, a handler's session saves once, at the end, recording the message as handled; a handler that must save more than once (through a store that saves after each change) uses a scope of its own, like `LeaveOrganisationsOfDeletedAccountHandler`. * **Retries.** A handler that depends on something that can be briefly unavailable says how to retry in a `Configure(HandlerChain)` method: `Storage/DeleteStoredFiles.cs` tries again after increasing delays when the file store fails. * **Dead letters.** A message that keeps failing is moved to the `wolverine_dead_letters` table, with the exception, and kept there. Admins see them on the back office's **Failed messages** page, and replay them once the cause is fixed, or discard them ([Accounts](./accounts.md#roles-and-the-back-office)). * **Dead letters.** A message that keeps failing is moved to the `wolverine_dead_letters` table, with the exception, and kept there until it's replayed or deleted. * **Scheduled messages** are stored the same way, and are sent when they're due, even across restarts. * **The organisation travels with it.** A message sent while handling a request for an organisation carries its tenant id, so its handler's session or `DbContext` is for the same organisation, and a handler can ask for it as a `TenantId` parameter. Outside a request, say which organisation a message is for: `new DeliveryOptions { TenantId = ... }`, as `OrganisationStore` does when it publishes `OrganisationDeleted`. ::: info With organisations ## Organisations and tenancy Data belongs to an organisation. Nothing in an endpoint filters by it: the organisation travels from the access token to the data layer and through every message. ```mermaid flowchart LR token["Access token
org claim"] --> wolverine["Wolverine
reads the tenant id"] wolverine --> endpoint["Endpoint or handler"] endpoint --> data["Marten or EF Core
conjoined tenancy"] data --> db[("PostgreSQL
rows tagged with the tenant")] endpoint -- "messages carry
the tenant id" --> handler["Background handlers"] handler --> data ``` The access token names the organisation the user is working in (`OrganisationClaims`), checked against their membership when it's issued. `opts.TenantId.DetectWith()` in `Program.cs` makes it each request's tenant id: the app's tenant resolvers are asked in turn, the access token's first (`Organisations/TenantResolution.cs`; add your own, such as by host name, with an `ITenantResolver`). Marten's (or Wolverine's EF Core) conjoined tenancy then adds it to every query and every row, so a forgotten filter can't leak another organisation's data. ::: ## Backend * **Endpoints.** Each endpoint is a static method with `[WolverineGet]` or `[WolverinePost]`. Wolverine finds it automatically and injects what it asks for. See `src/ApiHost/Features/Todos/`. * **Validation.** `CreateTodoValidator` (FluentValidation) runs before the endpoint. An invalid request gets a 400 response with `ProblemDetails`, which the React form displays. * **Messages and the outbox.** Completing a Todo returns a `TodoCompleted` message from the endpoint. Wolverine saves it in the same database transaction as the change (the transactional outbox) and `TodoCompletedHandler` handles it in the background, even after a restart. * **Event sourcing.** A Todo is a stream of events (`TodoCreated`, then `TodoCompleted`). The complete endpoint uses Wolverine's aggregate handler workflow: `[WriteAggregate]` loads the Todo from its events, and the method returns the events to append. An inline snapshot projection keeps a `Todo` document up to date for queries. * **Scheduled messages.** "Remind me…" on a Todo calls `POST /api/todos/{id}/remind`, which schedules a `TodoReminderDue` message for later (`Features/Todos/RemindTodoEndpoint.cs`). Scheduled messages are stored in PostgreSQL, so reminders still fire after a restart. When it's due, `TodoReminderDueHandler` pushes a `todo-reminder` to the browser, unless the Todo was completed in the meantime. * **Realtime updates.** Creating or completing a Todo sends a `todo-changed` message to the browser over SignalR (`TodoChanged`, routed in `Program.cs`), and every open tab refetches. Updates go only to the members of the Todo's organisation. * **Realtime updates.** Creating or completing a Todo sends a `todo-changed` message to the browser over SignalR (`TodoChanged`, routed in `Program.cs`), and every open tab refetches. Each user only receives updates about their own Todos. * **Realtime updates.** Creating or completing a Todo sends a `todo-changed` message to the browser over SignalR (`TodoChanged`, routed in `Program.cs`), and every open tab refetches. * **Code generation.** Wolverine generates code for each endpoint and handler. In Development it does so at runtime, so changes need no extra step; `dotnet publish` generates it ahead of time and Production loads it ready-made, failing at startup if any is missing. * **Accounts.** ASP.NET Core Identity with JWT access tokens and rotating refresh tokens; see [Accounts](./accounts.md). ## Frontend * **Routes.** React Router in framework mode, as a single-page app with no rendering server. `src/Client/src/routes.ts` maps each URL to a route module in `routes/`, which default-exports the page. `root.tsx` is the HTML document, and `App.tsx` the frame around every page (in `components/Layout.tsx`: a header for public pages, and, with accounts, a sidebar for signed-in ones; each page inside uses `components/Page.tsx` for its heading and width). Each page's code loads when it's first visited, so the first page view downloads less JavaScript. * **Pre-rendered public pages.** The build renders the public pages (the home page, by default) into real HTML, so search engines and link previews see their content without running JavaScript, and a CDN can cache them. The app then takes over in the browser (hydration). Every other page starts from a fallback page. Code that runs while a public page renders must not use `window` or `document`, since pre-rendering runs it in Node; use them in effects and event handlers. * **Page titles and search engines.** Each route module's `handle` sets its page title and whether search engines may index it (`components/PageMeta.tsx`); only the home page may by default, and every other page gets `noindex`. `src/Client/src/pages.ts` lists every page's path and which are public: the build pre-renders those and writes the list into `client-routes.json`, from which the API answers 404 for other paths and builds `sitemap.xml`. A unit test checks it matches `routes.ts`. The default description and link-preview tags are in `root.tsx`: describe your product there. * **Server data.** TanStack Query caches the Todo list (`features/todos/todoQueries.ts`). Changes and SignalR messages invalidate it, which refetches it. * **The API client** (`lib/api/client.ts`) is typed from the API's OpenAPI document (`lib/api/schema.d.ts`, regenerated with `npm run gen:api` while the API runs). It adds the access token to each request and, on a 401, refreshes the tokens once and retries. * **The API client** (`lib/api/client.ts`) is typed from the API's OpenAPI document (`lib/api/schema.d.ts`, regenerated with `npm run gen:api` while the API runs). * **One deployable.** In development, the Vite dev server forwards `/api` (including the SignalR WebSocket) to the API, so the browser talks to one origin and no CORS is needed. In production, the API serves the built client from `wwwroot`. --- --- url: /saas-starter/latest/guide/troubleshooting.md --- # Troubleshooting ::: tip What this page covers Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says which options a part is for. The copy in your app's `docs/` folder has only the parts for yours. `ApiHost` stands for your app's name. ::: Problems people run into, by what you see. Each message here is what the app or its tools actually print. ## Starting it ### `Failed to connect to 127.0.0.1:5432` when the API starts ``` Npgsql.NpgsqlException (0x80004005): Failed to connect to 127.0.0.1:5432 ---> System.Net.Sockets.SocketException (111): Connection refused ``` PostgreSQL isn't running. Start it with `docker compose up -d` at the repository root, and check it's up with `docker compose ps`. If Docker itself isn't running, `docker compose` says it can't connect to the Docker daemon: start Docker Desktop (or the Docker service) first. ### `port is already allocated` from `docker compose up` ``` Bind for 0.0.0.0:5432 failed: port is already allocated ``` Something else is using the port, usually a PostgreSQL installed on the machine or another project's container (`docker ps` lists those). Stop it, or give this app's container another port in `docker-compose.yml` (`"5433:5432"`) and the connection string in `src/ApiHost/appsettings.Development.json` to match (`Port=5433`). ::: info With accounts Mailpit's ports, 8025 and 1025, can clash the same way. ::: ### `address already in use` for port 5133 ``` System.IO.IOException: Failed to bind to address http://127.0.0.1:5133: address already in use. ``` The API is already running, often in another terminal or your IDE. Stop that one, or change `applicationUrl` in `src/ApiHost/Properties/launchSettings.json`, and `apiUrl`, the address the client's dev server forwards `/api` to, in `src/Client/vite.config.ts`. ::: info EF Core ### `The model for context 'AppDbContext' has pending changes` ``` System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'AppDbContext' has pending changes. Add a new migration before updating the database. ``` An entity or `AppDbContext` changed without a migration, so the app won't start: applying the migrations would leave the database different from the code. Add one ([how](./how-to/add-a-migration.md)), then start it again. ::: ### `npm install` warns `EBADENGINE`, or `npm run dev` fails ``` npm warn EBADENGINE Unsupported engine { package: '@react-router/dev@...', required: { node: '>=22.22.0' } } ``` The client needs Node.js 22.22 or later (React Router's tools do). Check with `node --version`, and update Node; with a version manager such as `nvm`, `nvm install 22` gets the latest 22. ## In development ### The page shows no data, and the dev server logs `http proxy error` ``` [vite] http proxy error: /api/todos Error: connect ECONNREFUSED 127.0.0.1:5133 ``` The client's dev server is running, but the API isn't: it forwards `/api` to http://localhost:5133, which nothing answers (the browser gets `502 Bad Gateway`). Start the API with `dotnet run --project src/ApiHost`, in a second terminal. ### `npm run gen:api` fails with `fetch failed` ``` ResolveError: fetch failed [cause]: Error: connect ECONNREFUSED 127.0.0.1:5133 ``` It reads the API's OpenAPI document from the running API, at http://localhost:5133/openapi/v1.json, which is only served in Development. Start the API, then run it again. ::: info With accounts ### Signing in says "Confirm your email address first" New accounts must confirm their email before they can sign in. In development, the email is in Mailpit at http://localhost:8025. If Mailpit has nothing, it wasn't running when you signed up: the API logs `Failed to process message ...SendEmailConfirmation` with `Connection refused`, and tries again after 30 seconds, then 2 minutes, 10 minutes and an hour. Start it with `docker compose up -d` and the email arrives on the next attempt; or sign up again with another address. The demo user, `demo@example.com`, is already confirmed. ::: ### A change to an endpoint or handler doesn't show Development generates Wolverine's code when the API starts, so a new endpoint, handler or message type needs the API restarted. A new endpoint also needs `npm run gen:api` before the client's types know it. ### The tests fail to start with a Docker error The API tests start their own PostgreSQL with Testcontainers, so Docker must be running. They don't use the database from `docker compose`, and can run while it's up. ## In production ### `MissingPreBuiltTypesException` at startup ``` Wolverine.Runtime.Handlers.MissingPreBuiltTypesException: Wolverine.Http is running in TypeLoadMode.Static, but 72 expected pre-built HTTP endpoint type(s) could not be loaded ... ``` Production loads Wolverine's code ready-made, generated by `dotnet publish`. This is a build that wasn't published, such as `dotnet build` output run with `ASPNETCORE_ENVIRONMENT=Production`. Publish it (`dotnet publish src/ApiHost -c Release`, or the container image), and run the published app ([deployment](./deployment.md)). ### `Missing '...' connection string` ::: info Marten Set `ConnectionStrings__Marten`, usually as an environment variable: `appsettings.json` only has the development database's. ::: ::: info EF Core Set `ConnectionStrings__Postgres`, usually as an environment variable: `appsettings.json` only has the development database's. ::: ::: info With accounts ### `'Jwt:SigningKey' must be at least 32 bytes`, or `is the development key` Set a random secret of at least 32 bytes as `Jwt__SigningKey`, such as the output of `openssl rand -base64 48`. The development key is refused outside Development, as it's in the repository. ### `'App:ClientUrl' must be set to the app's public address` Links in emails, and passkeys, need the app's public address: set `App__ClientUrl` to it, such as `https://app.example.com`, with no path or query string. ### Emails aren't sent Check the API's logs for `Failed to process message` on the email messages: the SMTP settings (`Email__Smtp__*`) are wrong, or the server can't reach the provider. Each email is tried again for about an hour, then kept as a failed message, which an admin can replay from the back office once it's fixed ([configure email](./how-to/configure-email.md)). ::: ### The app works, but links and redirects use `http://`, or every visitor seems to have one address Behind a reverse proxy (Caddy, nginx, a load balancer), set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true`, so the app sees the original scheme and the visitor's address. Without it, the app sees every visitor as the proxy's one address, in its logs and its rate limits. ## Still stuck Search the repository's issues, or open one, at [github.com/LibreSharp/saas-starter](https://github.com/LibreSharp/saas-starter/issues), with what you ran, what you saw, and the template version in `.saas-starter.json`. --- --- url: /saas-starter/latest/guide/accounts.md --- # Accounts ::: tip What this page covers Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says which options a part is for. The copy in your app's `docs/` folder has only the parts for yours. `ApiHost` stands for your app's name. ::: Accounts use ASP.NET Core Identity, with the app's own JSON Web Tokens instead of cookies. The endpoints are features, like the Todos: `src/ApiHost/Features/Auth/` (signing in and registering), `Features/Account/` (the signed-in user's own account) and `Features/Admin/`. What they share (users, tokens, roles, lockout, emails, providers, passkey set-up and two-factor authentication) is in `src/ApiHost/Identity/`. The pages match: `src/Client/src/features/auth/`, `features/account/` and `features/admin/`. For how each part protects users, see [Security](./security.md). ## Signing in ```mermaid sequenceDiagram participant B as Browser tab participant A as API B->>A: POST /api/auth/login A-->>B: access token (kept in memory)
and refresh token (HttpOnly cookie) B->>A: requests, with Authorization: Bearer Note over B,A: 15 minutes later, the access token has expired B->>A: a request A-->>B: 401 Unauthorized B->>A: POST /api/auth/refresh, with the cookie
(one tab at a time) A-->>B: a new access token, and a new cookie
(the old one is revoked) B->>A: the request again Note over B,A: after a reload or in a new tab, the page
refreshes with the cookie as it loads ``` * **Tokens.** Login returns a short-lived access token (a JWT) and a refresh token. The client refreshes automatically when a request gets a 401; each refresh replaces the refresh token. Lifetimes are under `Jwt` in `appsettings.json`. * **Where the browser keeps them.** The access token only in the page's memory. The refresh token in an HttpOnly, `SameSite=Strict` cookie (`__Secure-refresh_token` over HTTPS, path `/api`) that page scripts can't read, so an injected script can't steal it. The client asks for the cookie with the `X-Refresh-Token-Cookie: true` header on its requests, and the API only reads the cookie when that header comes with it, which a page on another site can't add (`Identity/RefreshTokenCookie.cs`). * **Tabs and reloads.** Every tab shares the cookie, so reloading, opening a new tab or duplicating one keeps you signed in: the page gets a new access token with the cookie as it loads. Tabs take turns to refresh (a Web Lock), and signing in or out in one tab does the same in the others at once (a `BroadcastChannel`). * **Mobile and desktop apps** use the same API and leave the header out: their refresh token comes back in the response body, to keep in the platform's secure storage. See [Sign in from a mobile or desktop app](./how-to/sign-in-from-a-mobile-app.md). * **Reuse detection.** A replaced refresh token is still accepted for `Jwt:RefreshTokenReuseGraceSeconds` (30 by default), so two tabs refreshing at the same moment, or an app retrying a refresh whose response it lost, aren't mistaken for theft. Reusing one after that signs the user out everywhere. * **Ways to sign in:** email and password, a passkey, or Google/GitHub when configured. With [two-factor authentication](#two-factor-authentication) on, a password or Google/GitHub sign-in also needs a code. * **Data belongs to organisations.** Each user works in one organisation at a time (see [Organisations](#organisations)), and sees only its data. * **Each user sees only their own data.** Endpoints scope queries to the signed-in user (`principal.GetUserId()`), and SignalR updates go only to that user's tabs. ## Account emails * **Confirmation.** Registering emails a link to `/confirm-email`, and login is refused (with a "send it again" button) until it's opened. * **Email changes.** A new email in Settings is only used once the link sent to it is opened. Asking for one needs the password too, and a code with two-factor on (see [Confirming it's you](#confirming-its-you)). * **Password reset.** `/forgot-password` emails a link to `/reset-password`. Resetting also confirms the email and lifts a lockout from failed logins. * **Security emails.** People are told when their password is changed or reset, their email changes (sent to the old address), two-factor authentication is turned on or off (also by an admin), they get new recovery codes or use one, a passkey or a Google/GitHub sign-in is added or removed, the account is [locked](#lockout), or someone signs in from a new device (see [New sign-ins](#new-sign-ins)). Each says what to do if it wasn't them. They're always sent: they aren't notifications people can turn off. The wording is in `Identity/Email/SecurityNotices.cs`; send one for a new kind of change by adding to `SecurityChange` and returning a `SendSecurityNotice`. The lockout and recovery-code emails are sent by `ApplicationUserManager` (`Identity/ApplicationUserManager.cs`), wherever a wrong password or code is counted or a recovery code is used, so new endpoints get them too. * **How they're sent.** Endpoints don't send email themselves: they return a message (`SendEmailConfirmation`, `SendPasswordReset`, ...) that Wolverine stores in its durable inbox, and `AccountEmailHandler` (`Identity/Email/AccountEmails.cs`) sends it in the background with MailKit, retrying if the mail server is down. The handler creates the one-time token when it sends, so tokens are never stored. To change the wording, edit the handler. * **In Development** the emails go to Mailpit (http://localhost:8025). For production, see [Send email through your email provider](./how-to/configure-email.md). ## Settings Settings has three tabs, each its own URL (`features/account/SettingsLayout.tsx`): * **Profile** (`/settings`): a profile picture, the display name and the email. * **Security** (`/settings/security`): the password (changing it signs out the other sessions), passkeys, [two-factor authentication](#two-factor-authentication), [sessions](#sessions), and linking Google/GitHub. * **Preferences** (`/settings/preferences`): which emails the user gets, the theme, cookies, product news and terms, downloading their data, and deleting the account (`/settings/notifications` redirects here). Settings won't remove the last way a user can sign in. ### Confirming it's you Changing the email address and deleting the account ask again who it is, so someone using a browser left signed in, or a stolen access token, can't take the account over or delete it: whoever controls the email can reset the password. They need the password (if the account has one) and, with two-factor on, a code or recovery code (`TwoFactor.ConfirmItsYouAsync`). Wrong ones count towards the [lockout](#lockout). `GET /api/auth/me` says what to ask for (`hasPassword`, `twoFactorEnabled`). An account with neither (Google, GitHub or passkeys only) is asked to type its email address before deleting, so it isn't deleted with one click. ### New sign-ins When someone signs in on a device that hasn't signed in to the account before, they get an email: "A new sign-in to your account: Chrome on Windows", with what to do if it wasn't them (`Identity/KnownDevices.cs`). A device is known when it has the `__Secure-known_device` cookie naming the account: HttpOnly, encrypted, sent only to `/api/auth`, kept for a year, and set at every sign-in and at registration (so the first sign-in after signing up isn't reported). The User-Agent alone isn't used, as every computer with the same browser version sends the same one. Apps that don't keep cookies get the email each time they sign in, which is rarely, as refresh tokens keep them signed in. Accepting an invitation and signing up with Google or GitHub don't send one. The email says the browser and system but not where, as the IP address isn't kept. ### Sessions **Settings → Sessions** lists where the user is signed in: one entry per sign-in on a device, with its browser and system ("Chrome on Windows", from the User-Agent), when it started and when it was last active, and "This device" on the current one. They can sign out one session, or every session but this one (`Features/Account/SessionEndpoints.cs`). * **A session is a chain of refresh tokens.** Each token replaced by a refresh keeps the session's ID (`RefreshToken.SessionId`), when it started, and the User-Agent; the access token carries the ID (the `sid` claim) so the API knows which session is asking. * **Signing a session out** revokes its refresh token, so it ends when its access token expires (`Jwt:AccessTokenLifetimeMinutes`, 15 minutes by default). * **How long a session lasts:** until it goes unused for `Jwt:RefreshTokenLifetimeDays` (14), and at most `Jwt:SessionLifetimeDays` (30) after signing in, however much it's used. Then the user signs in again. * **Only the User-Agent is kept,** not the IP address, so the list says which device but not where. ### Deleting an account Settings → **Delete account** deletes it for good, after [confirming it's you](#confirming-its-you). ::: info With organisations It publishes an `AccountDeleted` message; each feature that stores user data handles it to delete that data. The user leaves each of their organisations, and one they were the only member of is deleted with its data (`Organisations/LeaveOrganisationsOfDeletedAccountHandler.cs`). Todos in organisations that others are still in stay: they belong to the organisation, not the user, and keep the deleted user's id as their `OwnerId`, in the Todo and in its event history. Nothing else about the user (email, name) is kept with them. If your data needs to forget its authors too, clear or replace those ids in an `AccountDeleted` handler. ::: ::: info Without organisations It publishes an `AccountDeleted` message; each feature that stores user data handles it to delete that data (see `Features/Todos/DeleteTodosOfDeletedAccountHandler.cs`). ::: ## Preferences Each user has one preferences record (`Identity/UserPreferences.cs`), separate from their account: signing in and refreshing tokens don't load it, and it can grow without widening the users table. It holds their cookie choices ([analytics](./analytics.md)), their theme, which version of the [terms and privacy policy](#terms-and-privacy-policy) they accepted, and whether they want [product news](#product-news). It's the place for other preferences you add, such as a language or time zone. **Settings → Preferences** shows them: the theme, the cookie choice with a **Cookie settings** button (when analytics is on), product news, and when the terms were accepted (when they're set). Add new preferences there (`features/account/PreferencesSection.tsx`). The theme (System, Light or Dark: in the footer of public pages, and in Settings) works for everyone: the browser remembers it, and with an account it's saved in the preferences too, so it follows people to their other devices. When someone signs in, the theme saved in their preferences wins; if there's none, the browser's is saved. * **To add a preference,** add a property to `UserPreferences` with a sensible default (people who never set it get that), and a `PUT` endpoint that changes it with `IUserPreferencesStore.UpdateAsync`, like `PUT /api/account/consent` in `Features/Account/PreferenceEndpoints.cs`. The client reads them all with `GET /api/account/preferences` (`usePreferences()`). * **No migration needed:** the preferences are stored as JSON (a Marten document, or one `jsonb` column with EF Core), so a new property changes no table. * **Renaming or removing a property** loses what people saved under the old name, so keep the old one readable until you've moved the values over. * **Export and deletion are covered:** the preferences are in "Download your data", and deleted with the account. Settings that belong to one feature stay with that feature, such as which notifications are emailed (`Notifications/`). ### Product news Sign-up has an unticked **Send me product news** box, separate from accepting the terms, and **Settings → Preferences** a box to change it later. The choice and when it was made are kept in the preferences (`ProductNews`: `subscribed` and `chosenAt`), so there's a record of consent and it's in "Download your data". People who signed up with Google or GitHub, or were invited, haven't been asked (`ProductNews` is null), which counts as no. The template doesn't send product news itself: send it with your newsletter tool, only to people with `ProductNews.Subscribed` true, and include an unsubscribe link that turns it off (`PUT /api/account/product-news`). Set `Accounts:AskForProductNews=false` if the app doesn't send any. ## Terms and privacy policy Set `Legal:TermsUrl` and `Legal:PrivacyUrl` to your documents: a page of the app (`/terms`) or a full address. Then: * **The footer links to them** (in every app). * **Signing up needs them accepted:** the form has an "I agree" checkbox, and the API refuses a sign-up without it. What they accepted, and when, is saved in their [preferences](#preferences). * **Everyone else is asked after signing in:** people who signed up with Google or GitHub, or were invited, see an "Accept our terms" prompt. They can accept, or sign out. * **Raise `Legal:Version`** when either document changes in a way people should agree to again. Everyone is asked to accept the new version ("We've updated our terms") the next time they use the app. Without either setting, there are no links and nothing to accept. The prompt is in the client (`features/account/TermsGate.tsx`); the API doesn't refuse other requests from someone who hasn't accepted yet, so API keys and mobile apps keep working. If you need that, check `UserPreferences.Terms` where it matters. The record is in "Download your data" and deleted with the account. ## Profile pictures ::: info With organisations People's pictures appear in the sidebar's user menu, the member list and the admin page, and the organisation's logo in the switcher. A person's picture is, in order: ::: ::: info Without organisations People's pictures appear in the sidebar's user menu and the admin page. Each is, in order: ::: 1. **The picture they uploaded** in Settings. The browser crops the middle square of the file and resizes it to 256 × 256 pixels (`features/account/pictures.ts`), then uploads it to `PUT /api/account/picture`. The server needs no image library: it checks the bytes are a PNG, JPEG or WebP picture of at most 512 KB and 1024 pixels a side (`Pictures/ImageFiles.cs`), whatever the file name or type claims, and keeps it with [file storage](./file-storage.md) under `users/{id}/` with a new random name each time. It's served at `/media/...` with a one-year cache lifetime: a new picture gets a new address, so caches never show an old one. Anyone with the address can see the picture, as with most apps' avatars; the random name makes it unguessable. 2. **Their [Gravatar](https://gravatar.com)**, if they have one and you've set `Pictures:Gravatar` to `true` (it's off by default). The browser asks Gravatar for it by the SHA-256 hash of the user's email, so Gravatar, a third party, learns that hash and the viewer's IP address: under the GDPR, say so in your privacy policy before turning it on. The Content-Security-Policy allows Gravatar's pictures only when it's on. 3. **Their initials.** ::: info With organisations Owners and admins set an organisation's logo on `/organisation` (its General tab) the same way (`PUT /api/organisation/logo`). ::: Each person can upload `Pictures:UploadsPerMinute` files a minute (10 by default, counting pictures, logos and Todo attachments); more get `429 Too Many Requests`, since every upload writes a file. **Old pictures are cleaned up** (`Pictures/PictureCleanup.cs`) so that nothing is left in storage with nothing pointing at it: * When a picture is replaced or removed, the previous one is deleted in the background, once the change is saved, unless its owner is using it again by then. * Each new picture is checked again 10 minutes later and deleted if its owner isn't using it. That catches the rare races: two uploads at the same moment, or a request that loaded the user before an upload and saved after it. * If saving the owner fails after the file was written, the file is deleted straight away. ::: info With organisations Deleting the account deletes everything under `users/{id}/`, and deleting an organisation everything under `organisations/{id}/`, through a `DeleteStoredFiles` message of its own. If file storage is unreachable at that moment, the rest of the deletion still completes, and deleting the files is retried (after 1 minute, 10 minutes, 1 hour and 6 hours). ::: ::: info Without organisations Deleting the account deletes everything under `users/{id}/`, through a `DeleteStoredFiles` message of its own. If file storage is unreachable at that moment, the rest of the deletion still completes, and deleting the files is retried (after 1 minute, 10 minutes, 1 hour and 6 hours). ::: ## Notifications The bell in the sidebar lists the user's latest notifications, such as a Todo reminder that came due, with the number unread. They arrive live (over the realtime connection) and are kept per user (`Notifications:KeepPerUser`, 100). Each one is also emailed, unless the user turned that kind off in Settings ("Email notifications") or with the link at the bottom of the email. The link needs no login, and mail apps show a one-click "Unsubscribe" button for it (the `List-Unsubscribe` headers). Account emails, such as password resets, can't be turned off. To notify someone, publish `SendNotification(userId, category, title, body, link)` from an endpoint or handler (it goes through the outbox). Add new kinds to `NotificationCategories` in `Notifications/Notification.cs`, with the description users see in Settings. The reminder handler (`Features/Todos/RemindTodoEndpoint.cs`) is an example. ## Download your data ::: info With organisations Settings has "Download your data": everything the app stores about the user as one JSON file (their account, sign-ins and passkeys, preferences, notifications and email choices, and the organisations they belong to). Organisation owners download the organisation's data from the organisation page: its Todos, members, billing and integrations. ::: ::: info Without organisations Settings has "Download your data": everything the app stores about the user as one JSON file (their account, sign-ins and passkeys, preferences, notifications and email choices, and their Todos). ::: Privacy laws such as the GDPR and Thailand's PDPA give people this right. Never the password hash or other secrets. A feature that stores data about users adds its section by registering an `IPersonalDataSource` (`DataExport/DataExport.cs`), like `NotificationsPersonalData`. ::: info With organisations A feature that stores organisation data registers an `IOrganisationDataSource`, like `TodosOrganisationData`. ::: ## Lockout Repeated wrong passwords (or two-factor codes, at sign-in or when [confirming it's you](#confirming-its-you)) lock the account for a while (ASP.NET Core Identity's lockout, configured in `ConfigureIdentity` in `Identity/IdentityJwtSetup.cs`). While locked, login is refused without checking the password, refresh tokens stop working, and resetting the password lifts the lock. The owner is emailed when the lock starts ("Your account was locked"), once per lock, as it may be someone guessing their password. An admin can also lock an account until they unlock it; that isn't emailed. ## Roles and the back office Roles are constants in `Identity/AppRoles.cs`, created in the database at startup (`RoleSeeder`). Protect endpoints with `[Authorize(Roles = AppRoles.Admin)]`. A changed role reaches the user's access token at their next token refresh. The back office (`/admin`, Admin role only) has these sections: * **Users:** search users, change their roles, lock and unlock accounts (an admin lock ends the user's sessions), end a user's sessions (sign them out everywhere: their refresh tokens are revoked, and each session ends when its access token expires), resend the confirmation email, turn off two-factor authentication for someone who lost their phone and recovery codes, and invite people. An invitation creates the account and emails a link to choose a password, valid for a week. Each user's organisations are listed too. * **Dashboard, Organisations and Feature flags:** see [Plans, trials and limits](./billing.md#the-back-office). * **Users:** search users, change their roles, lock and unlock accounts (an admin lock ends the user's sessions), end a user's sessions (sign them out everywhere: their refresh tokens are revoked, and each session ends when its access token expires), resend the confirmation email, turn off two-factor authentication for someone who lost their phone and recovery codes, and invite people. An invitation creates the account and emails a link to choose a password, valid for a week. * **Audit log:** every change an admin makes, with who made it and when (`Features/Admin/IAuditLog.cs`). Record new admin actions with `IAuditLog.RecordAsync`. * **Failed messages:** background work that failed every attempt and waits in Wolverine's dead-letter queue, such as an email the SMTP server refused. Fix the cause, then replay the message (it runs again) or discard it. * The first admins come from configuration: see [Make someone an admin](./how-to/make-an-admin.md). * `Accounts:AllowRegistration=false` makes accounts invitation-only. * To add a role, see [Add a role](./how-to/add-a-role.md). ## Google and GitHub Each provider is turned on by setting its client ID and secret; see [Set up external sign-in](./how-to/set-up-external-sign-in.md). The provider must vouch for the email address: a verified email signs into (and links to) the account with that email, or creates one. After the provider, the API redirects to `/external-login` with a refresh token in the URL fragment (a full page load can't ask for the cookie), which the client exchanges at once for new tokens, and the cookie. ## Passkeys Users add passkeys in Settings and can then use "Log in with a passkey": the browser offers the passkeys it has for the site, so no email is typed. This is ASP.NET Core Identity's own WebAuthn support (`IPasskeyHandler`), used without cookies: the ceremony's state is encrypted and handed to the client for a few minutes (`Identity/Passkeys/PasskeySetup.cs`). Passkeys belong to the site's host name: a passkey created on one domain doesn't work on another, so moving the app to a new domain means users add new passkeys. In development, passkeys work on `localhost`. ## Two-factor authentication Users turn it on in **Settings → Two-factor authentication**: they scan a QR code with an authenticator app (Google Authenticator, Microsoft Authenticator, 1Password and others), and enter one code from it to prove it worked. They then get ten recovery codes to save, each usable once, for when they lose their phone. This is ASP.NET Core Identity's authenticator support (TOTP, six digits every 30 seconds), used without cookies (`Identity/TwoFactor.cs`). * **Signing in:** with it on, the right password (or a Google/GitHub sign-in) returns a 403 with `reason: "TwoFactorRequired"` and a `twoFactorTicket` instead of tokens. The client asks for a code and sends it with the ticket to `POST /api/auth/two-factor`. The ticket lasts five minutes and stops working if the password changes or two-factor is turned off. * **Passkeys don't ask for a code:** a passkey is already two factors (the device, and the fingerprint, face or PIN that unlocks it). * **Wrong codes count towards the lockout**, the same as wrong passwords. * **Each code works once.** Identity accepts a code for a minute or so either side of its 30 seconds, for phones whose clocks drift; a code that has worked is refused after that, so one seen over someone's shoulder is no use (`ApplicationUserManager`). Used codes are remembered in memory, by each instance of the app. * **Using a recovery code is emailed,** with how many are left: whoever used it may have the password too. * **Changing it needs a code:** turning it off or getting new recovery codes needs a current code (or a recovery code), so someone using a session left open can't turn it off. * **Lost phone and recovery codes:** an admin can turn it off from the back office (**Turn off two-factor**, recorded in the audit log). Check it's really them first, through some other channel. * **The name in the authenticator app** is `Accounts:TwoFactorIssuer` (the app's name by default). * **Changing the email or deleting the account needs a code** as well as the password (see [Confirming it's you](#confirming-its-you)). * **Recovery codes** are five groups of five letters and digits (`ABCDE-FGHJK-...`, 125 random bits), shown once and stored only as SHA-256 hashes. * **Stored by Identity:** the authenticator key and the unused recovery codes' hashes are kept with the user (with EF Core, in `AspNetUserTokens`; with Marten, on the user document). They're secrets, so "Download your data" says only whether two-factor is on. **Requiring it for admins:** with `Accounts:RequireTwoFactorForAdmins=true`, the Admin role only counts for admins whose account is protected: two-factor authentication is on, or they sign in only with passkeys. Other admins' tokens leave the role out, so the API refuses their back office requests, and `/admin` asks them to set it up in Settings first. Turn it on in production once your admins have set it up. ## Passwords A new password (at sign-up, changing or resetting it, or accepting an invitation) needs at least 8 characters, of any kind: no rules about upper case, digits or symbols, which make passwords harder to remember rather than to guess (NIST SP 800-63B). Paste and password managers work, and nothing is trimmed or changed. Instead, `Identity/CommonPasswords.cs` refuses: * the 10,000 most common passwords of 8 characters or more, in any case (`common-passwords.txt`, from SecLists, MIT licence); * passwords made mostly of the user's email address, the app's name, or the words in `Accounts:PasswordBlockedWords` (add your product and company names): taking those out must leave at least 8 characters, so `MyApp2024!` is refused, but a long passphrase that contains the app's name isn't. Passwords never expire: people change them when they want to, or when one turns out to be known (below). Change the length in `ConfigureIdentity` (`Identity/IdentityJwtSetup.cs`). ### Breached passwords With `Accounts:RejectBreachedPasswords=true`, a new password (at sign-up, changing or resetting it, or accepting an invitation) is refused if it's known from a data breach, as NIST SP 800-63B advises: those are the passwords attackers try first. It's checked with Have I Been Pwned's [Pwned Passwords](https://haveibeenpwned.com/API/v3#PwnedPasswords), which is free and needs no key, without sending the password: only the first five characters of its SHA-1 hash go to the service, which answers with every breached hash that starts with them (padded, so the answer's size gives nothing away), and the match is made on the server (`Identity/BreachedPasswords.cs`). If the service doesn't answer within three seconds, the password is accepted and a warning logged. It's off by default because it calls an outside service. ::: info With organisations ## Organisations Data belongs to organisations, the app's tenants. The code is in `src/ApiHost/Organisations/` (the model, its store, and choosing a session's organisation) and `Features/Organisations/` (the endpoints); the pages are in `src/Client/src/features/organisations/`. * **Everyone has one.** A new account gets its own organisation, named after the user ("Ada's organisation"). Users can create more, and be invited into others; the switcher at the top of the sidebar picks the current one. * **The access token names the organisation** (the `org` claim), chosen when the token is issued: the one the session was in, or the one the user used last. Switching issues new tokens. Every request checks that the user is still a member, so removing someone, or deleting the organisation, takes effect at once; the browser then refreshes its tokens into another of the user's organisations. * **Multi-tenancy.** Wolverine reads the claim as each request's tenant id and carries it on the messages the request sends. Tenanted data (`Todo`, which implements `ITenanted`) is stored with a tenant id (Marten's conjoined multi-tenancy), so queries only ever see the current organisation's, without a filter in each endpoint. Organisations, memberships and invitations themselves aren't tenanted. * **Multi-tenancy.** Wolverine reads the claim as each request's tenant id and carries it on the messages the request sends. Tenanted data (`Todo`, which implements `ITenanted`) is stored with a tenant id (Wolverine's conjoined multi-tenancy for EF Core: a `tenant_id` column and a global query filter), so queries only ever see the current organisation's, without a filter in each endpoint. Organisations, memberships and invitations themselves aren't tenanted. * **Roles:** Owner, Admin and Member. Owners and admins invite and remove members and change roles, but only owners make owners, change an owner's role, rename or delete the organisation. There's always an owner: the last one can't leave or step down, and can't delete their account while others are members (`Features/Organisations/OrganisationRules.cs`). Each change checks again after saving and undoes itself if a change at the same moment left no owner; and if an owner's account is deleted after someone joined, their longest-standing admin (or member) becomes the owner. * **Invitations** go by email, with a link to `/join` that works for a week. Someone with an account logs in with the invited email and accepts; someone without one chooses a password, and the link confirms their email. Only a hash of the link's token is stored, and the page sends the token in request bodies, never in a URL the API would log. Each user can send 20 invitations an hour and an organisation can have 100 waiting (`Organisations:InvitationsPerHour`, `Organisations:MaxPendingInvitations`; see `Organisations/OrganisationOptions.cs`), so the app can't be used to send spam. * **Requiring two-factor authentication:** an owner can require it of every member (the organisation page; the owner must have it on first). Members without it (or who don't sign in only with passkeys) can't work in the organisation: their tokens stop working at once, a new session starts in another of their organisations, and the switcher marks it "needs two-factor". The members list shows who has it. The access token carries whether the user has two-factor (the `tfa` claim), so this costs no extra query per request. API keys aren't affected: they're their own credential. * **Deleting an organisation** deletes it for everyone. Its data is deleted in the background: each feature handles `OrganisationDeleted`, which runs for that organisation's tenant (see `Features/Todos/DeleteTodosOfDeletedOrganisationHandler.cs`). The message is published in the same transaction as the deletion, so the data is never left behind. * **Realtime updates** go to everyone working in the organisation; the browser reconnects when it switches. Reminders go only to the member who set them, while they're still a member. A connection is closed when its access token expires, so someone removed from an organisation stops getting its updates within one token lifetime. ::: ## Development The demo user (`demo@example.com` / `Demo123!`) is created at startup in Development only, is already confirmed, and is an admin. Change it under `DevelopmentUser` in `src/ApiHost/appsettings.Development.json` and in `src/Client/.env.development`. --- --- url: /saas-starter/latest/guide/billing.md --- # Plans, trials and limits ::: tip What this page covers Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says which options a part is for. The copy in your app's `docs/` folder has only the parts for yours. `ApiHost` stands for your app's name. ::: Each organisation is on a plan. A plan includes **features**, which are on or off, and **limits**, which are numbers. The app checks both in one place, and the client shows or hides features and offers an upgrade. The code is in `src/ApiHost/Billing/`, the endpoints are in `Features/Billing/`, and the pages are in `src/Client/src/features/billing/`. ## The plans The plans are defined in one place: `PlanCatalogue` in `Billing/Plans.cs`. That file sets each plan's prices per currency (in cents), its features and its limits. The example has two plans: | | Free | Pro | |---|---|---| | Price | Free | $12 or €11 a month | | Open Todos | 25 | Unlimited | | Members (invitations count) | 3 | 50 | | Todo reminders | No | Yes, 1,000 a month | * **Versions keep existing customers' prices.** To change a plan, add a new version to `PlanCatalogue.All` instead of editing the existing one. An organisation keeps the version it subscribed to, with its price and limits, until it changes plan ("grandfathering"). New subscribers get the latest version. * **A free plan is a plan with a price of zero.** An organisation that isn't paying is on it. * **The pricing page** (`/pricing`) is pre-rendered from a copy of the catalogue, `src/Client/src/features/billing/plans.json`. A test fails when the copy no longer matches `GET /api/billing/plans`. To update it after changing the plans, run: `UPDATE_PLANS=1 dotnet test --filter the_plans_on_offer`. ## Trials New organisations get a **reverse trial**: the top plan (`Billing__TrialPlan`, `pro`) for 14 days (`Billing__TrialDays`; 0 turns trials off), then the free plan unless they subscribe. Nothing needs to run when a trial ends. The plan is worked out from the time and the organisation's billing account each time it's needed (`BillingState.Resolve`). ## Checking features and limits `Entitlements` (`Billing/Entitlements.cs`) answers "can this organisation use feature X?" and "how much of limit Y is left?". Use it in endpoints and handlers, and never check a plan's name. * **Features** are feature flags, using [Microsoft.FeatureManagement](https://github.com/microsoft/FeatureManagement-Dotnet). Each feature in `PlanFeatures` is a flag that is on for organisations whose plan includes it (`PlanFeatureFlags.cs`). Other flags come from the `FeatureManagement` configuration section as usual. Check either kind with `entitlements.IsEnabledAsync(organisationId, feature)`. * **Count limits** count what the organisation has now, such as open Todos or members. The feature that owns the data counts it: an `ILimitUsage`, registered in `BillingSetup`. Check with `CanAddAsync`. Two requests at the same moment can both take the last place, so a Count limit can be passed by one or two. * **PerPeriod limits** count use in the current billing period, such as reminders a month. `TryUseAsync` adds to the count only while it stays within the limit, in one SQL statement, so requests at the same moment can't pass it. The count starts again each period: the paid subscription's period, or otherwise a month at a time from the day the organisation was created. An endpoint checks before it runs, in a Wolverine `Before` method. If that method returns a problem, Wolverine stops there: ```csharp public static Task BeforeAsync(ClaimsPrincipal user, Entitlements entitlements, CancellationToken cancellationToken) => entitlements.RequireFeatureAsync(user.GetOrganisationId(), PlanFeatures.TodoReminders, cancellationToken); ``` The answer is **402 Payment Required**: ProblemDetails with a `detail` for the user, and a `feature` or `limit` field naming what's missing. The client shows the detail. To show or hide features in advance, the client reads `GET /api/billing` (`useBilling()`), which returns the plan, its features and how much of each limit is used. It warns at 80% and stops at 100%. ## Downgrades never delete data When an organisation moves to a smaller plan, anything over a limit stays. It can't add more until it's back under the limit: a 26th open Todo on Free is refused, but completing Todos makes room. Paid features switch off at once, including reminders already scheduled, which are dropped when they come due. ## Payments with Stripe Paid plans are sold through [Stripe](https://stripe.com/) (Stripe charges fees). Until its keys are set, the app offers no paid plans: just the trial and the free plan. * **Subscribing** happens on Stripe's own pages, so card details never reach the app. An owner presses Upgrade on `/organisation`, `POST /api/billing/checkout` opens Stripe Checkout, and Stripe brings them back. Whatever is left of the trial carries on, and Stripe charges when it ends. Changing plan or payment details, invoices and cancelling are in Stripe's customer portal (Manage billing; `POST /api/billing/portal`). * **Webhooks keep the app's copy in step.** Stripe calls `POST /api/billing/webhooks/stripe` for each change. The endpoint checks the signature, stores the event and answers at once. A second delivery of the same event is ignored. A Wolverine handler (`Billing/Payments/PaymentEventHandler.cs`) then reads the subscription from Stripe and updates the organisation's `BillingAccount`: plan and version, status, billing period and invoices. It runs from a durable queue, so a failure is retried, and then parked with Wolverine's failed messages. Answering "which plan is this organisation on?" never calls Stripe. * **A failed payment** (`PastDue`) keeps the plan while Stripe retries. When Stripe gives up, or the customer cancels, the subscription ends and the organisation is on the free plan. * **Deleting an organisation** cancels its subscription. * **Another provider** (such as Paddle or Lemon Squeezy, which handle sales tax and VAT as the seller) implements `IPaymentProvider` (`Billing/Payments/`) and is registered in `BillingSetup` instead. Nothing else changes. ### Setting it up 1. In the [Stripe dashboard](https://dashboard.stripe.com/), in test mode, copy the secret key (`sk_test_...`) into user secrets: `dotnet user-secrets --project src/ApiHost set Billing:Stripe:SecretKey sk_test_...` 2. Create the products and prices from `Billing/Plans.cs`: `dotnet run --project src/ApiHost -- stripe-prices`. Each plan version and currency becomes a price with a lookup key (such as `pro-v1-usd`), which checkout finds it by. Run it again after adding a plan version: it only adds what's missing. Prices can't change in Stripe, so a new price means a new plan version. 3. Forward webhooks to the app with the [Stripe CLI](https://docs.stripe.com/stripe-cli): `stripe listen --forward-to localhost:5133/api/billing/webhooks/stripe`. Put the signing secret it prints (`whsec_...`) in `Billing:Stripe:WebhookSecret`. 4. Turn on the customer portal in the dashboard (Settings > Billing > Customer portal), with the plans customers may switch between. 5. Subscribe with a [test card](https://docs.stripe.com/testing), such as 4242 4242 4242 4242. In production, use the live keys (`Billing__Stripe__SecretKey`, `Billing__Stripe__WebhookSecret`; see [deployment](./deployment.md)), run `stripe-prices` with the live key, and add a webhook endpoint for `https://your-domain/api/billing/webhooks/stripe` with these events: `checkout.session.completed`, `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `invoice.paid` and `invoice.payment_failed`. `Billing__Stripe__AutomaticTax=true` has Stripe Tax add sales tax and VAT. ## The back office Admins (see [accounts](./accounts.md#roles-and-the-back-office)) support customers from `/admin`: * **Dashboard:** monthly recurring revenue (per currency, from each subscription's plan version), organisations (new and active in the last 30 days), trials ending in the next 7 days, failed payments, and failed messages. * **Organisations:** search by name, then see an organisation's members, plan, usage, invoices (with links to Stripe's dashboard), feature flags, notes and history. From there an admin can: * **give a plan until a date**, free of charge, which also extends a trial (the organisation must not have a subscription: change a subscription in Stripe); * **suspend** it: nobody can work in it (every request checks), and its members' sessions move to their other organisations; nothing is deleted until it's unsuspended or deleted; * **keep notes**, which its members never see; * **delete** it with its data, as an owner can, which cancels its subscription. * **Feature flags:** turn a feature on or off for everyone, for a plan, or (on an organisation's page) for one organisation, over what the plans say. The most specific wins: the organisation's, then everyone's, then the plan's, then the catalogue. "Off for everyone" is a kill switch for a feature that misbehaves. The flags are stored in the database (`FeatureOverride`), and checked through the same `Entitlements.IsEnabledAsync`. Refunds stay in Stripe. Every change is in the audit log. ## Adding a feature or a limit 1. Add a constant to `PlanFeatures` (with a description) or `PlanLimits.All` in `Billing/Plans.cs`, and give it to the plans that include it. Add a new plan version if customers are already on the plan. 2. For a Count limit, add an `ILimitUsage` that counts it, and register it in `BillingSetup`. 3. Check it in the endpoint (`RequireFeatureAsync`, `RequireRoomAsync`, or `TryUseAsync`), and in any handler that runs later. 4. Update the pricing page's copy (above), and show or hide the feature in the client with `useBilling()`. A library built on the app adds its features and limits without editing `Plans.cs`: it calls `PlanFeatures.Add(name, description)` and `PlanLimits.Add(new LimitDefinition(...))` when its services are registered, and registers an `ILimitUsage` for a Count limit. The app then gives them to its plans in `PlanCatalogue`; a limit no plan sets is unlimited. Entitlements, the pricing page, the back office and feature flags all read the features and limits from there. --- --- url: /saas-starter/latest/guide/integrations.md --- # Integrations ::: tip What this page covers Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says which options a part is for. The copy in your app's `docs/` folder has only the parts for yours. `ApiHost` stands for your app's name. ::: Ways for other programs to work with an organisation's data: **API keys**, an **MCP endpoint** for AI assistants, **outgoing webhooks**, **encrypted secrets**, and **receiving webhooks**. The code is in `src/ApiHost/Integrations/`, the endpoints in `Features/Integrations/`, and the page (`/organisation/integrations`, for owners and admins) in `src/Client/src/features/integrations/`. ## API keys An owner or admin creates a key on the Integrations page. The key (`sk_...`) is shown once; only its SHA-256 hash is stored. A program sends it as a bearer token: ```bash curl -H "Authorization: Bearer sk_..." https://your-domain/api/todos ``` * **A key acts as the member who created it, in its organisation.** Tenancy, plan limits and realtime updates work as they do for that member's own requests. The key stops working when it's revoked or expires, when that member leaves the organisation, or when the organisation is suspended or deleted. * **Scopes:** `read` keys can only make GET requests (and use the MCP tools that only read); `write` keys can do everything a key may do. * **Keys only reach the paths they're for**, `ApiKeys:AllowedPaths` (`/api/todos` and `/mcp`). Account, organisation, billing and admin endpoints, and the realtime hub, need a user's login. Add your own API's paths there. * **Rate limits:** each key gets `ApiKeys:RequestsPerMinute` (120) requests a minute, then 429. * **Rotating** makes a new key with the same name and scope; the old one keeps working for `ApiKeys:RotationGracePeriod` (a day), so programs can switch over. How it works: the default authentication scheme looks at the bearer token. One that starts with `sk_` goes to `ApiKeyAuthenticationHandler`, anything else to the JWT handler, so endpoints need no changes: `[Authorize]` accepts either, and `user.GetUserId()` and the organisation claim are the same. `ApiKeyRestrictions` (middleware) keeps keys to their paths and scopes. ## AI assistants (MCP) `/mcp` is a [Model Context Protocol](https://modelcontextprotocol.io/) server (the official C# SDK, Apache-2.0), so assistants such as Claude can use the organisation's Todos: `list_todos`, `add_todo` and `complete_todo` (in `Integrations/Mcp/TodoTools.cs`). It only accepts API keys: ```json { "mcpServers": { "todos": { "type": "http", "url": "https://your-domain/mcp", "headers": { "Authorization": "Bearer sk_..." } } } } ``` The tools follow the same rules as the HTTP endpoints: validation, plan limits (the plan's error comes back to the assistant as the tool's error), realtime updates and webhooks. The server is stateless, so it works behind a load balancer. **Adding a tool:** add a method with `[McpServerTool]` and a `[Description]` (the assistant reads it to decide when to call the tool) to a class with `[McpServerToolType]`, and register the class in `IntegrationsSetup` (`.WithTools()`). Call `Caller.MustWrite()` first if the tool changes anything. Open a session or DbContext for the key's organisation, as `TodoTools` does: the MCP SDK runs tools outside Wolverine's endpoint pipeline. ## Outgoing webhooks Owners and admins add a URL and pick events (or all of them). When an event happens, the app POSTs JSON to the URL: ```json { "id": "...", "type": "todo.completed", "timestamp": "...", "data": { "id": "...", "title": "...", "isComplete": true } } ``` * **Signed the [Standard Webhooks](https://www.standardwebhooks.com/) way**, with the `webhook-id`, `webhook-timestamp` and `webhook-signature` headers. Receivers check the signature with the webhook's secret (shown when it's added, and on request) using a Standard Webhooks library for their language, or `WebhookSignatures.Check`. `webhook-id` is the same on every retry, so receivers can ignore repeats. * **Sent from a durable Wolverine queue**, one message per delivery, so one slow receiver doesn't hold up the others. A receiver that fails (not a 2xx answer within `Webhooks:Timeout`, 10 seconds) gets it again after 1, 5 and 30 minutes, 2 hours and 8 hours; then it's parked with the back office's failed messages. * **Every delivery is logged** with the receiver's status and the start of its answer. Owners see them on the Integrations page, and can resend any of them or send a test event. Deliveries are kept for `Webhooks:KeepDeliveriesFor` (30 days). * **Never to private networks in production:** the sender refuses localhost, private and link-local addresses (such as a cloud's metadata service at 169.254.169.254), checked on the address it actually connects to, after DNS. `Webhooks:AllowPrivateNetworks` turns this off, and allows plain HTTP, in Development only, to try a receiver on your machine. Redirects are never followed. **Adding an event:** add a constant and its description to `WebhookEvents` (`Integrations/Webhooks/Webhook.cs`), and publish `WebhookEvents.Raise(organisationId, type, data)` where it happens: return it with the endpoint's or handler's other messages, so it goes through the outbox with the change that caused it. `Features/Todos/CreateTodoEndpoint.cs` and `TodoCompleted.cs` do this. ## Secrets Owners keep keys and tokens for other services here, such as their own OpenAI key or an OAuth token, for the app to use on the organisation's behalf. Values are encrypted with ASP.NET Core Data Protection (whose keys the app keeps in PostgreSQL), for that organisation only, and are never shown again: the page shows names and the last four characters. The app's code reads them: ```csharp var key = await secrets.GetAsync(organisationId, "openai-api-key", cancellationToken); // OrganisationSecrets ``` The same protection keeps webhook signing secrets. Back up the Data Protection keys (the `mt_doc_dataprotectionkeydocument` table with Marten, `DataProtectionKeys` with EF Core) with the database: without them, secrets can't be decrypted. ## Receiving webhooks `POST /api/webhooks/incoming/{source}` receives webhooks from other services, the way billing receives Stripe's: it checks the signature, stores the event once (a second delivery of it is ignored), hands it to a durable message, and answers at once. The work happens in `IncomingWebhookHandler` (`Integrations/Webhooks/IncomingWebhooks.cs`), which is retried if it fails, so a slow handler never makes the sender give up. For a provider that signs the Standard Webhooks way, no code is needed to receive: add its signing secret as `Webhooks__Incoming__Secrets__` (for example `..._chat`), point the provider at `https://your-domain/api/webhooks/incoming/chat`, and handle `IncomingWebhookReceived` for that source. For a provider that signs differently (GitHub, Slack), copy the endpoint and change the signature check; `Features/Billing/PaymentEndpoints.cs` does this for Stripe. ## Data and deletion An organisation's keys, webhooks, deliveries and secrets are deleted with it, and its owners' data download (the organisation page) lists its keys, webhooks and secrets without the keys, signing secrets or values. --- --- url: /saas-starter/latest/guide/file-storage.md --- # File storage ::: tip What this page covers Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says which options a part is for. The copy in your app's `docs/` folder has only the parts for yours. `ApiHost` stands for your app's name. ::: Files people upload (pictures, attachments, imports) go through one interface, `IFileStorage` (`src/ApiHost/Storage/`). It has three implementations, and configuration chooses one, so features don't change when you move from a single server to a cloud provider: | `Storage:Provider` | Where files go | Suits | |---|---|---| | `Local` (the default) | A folder on the server (`Storage:Local:RootPath`) | One app on one server, such as the setup in `deploy/` | | `S3` | Any store with the S3 API: AWS S3, Cloudflare R2, Backblaze B2, Wasabi, Hetzner, DigitalOcean Spaces, Scaleway, OVH, Google Cloud Storage, or self-hosted SeaweedFS, Garage, Ceph or RustFS | Files off the server, more than one instance, a CDN | | `AzureBlob` | Azure Blob Storage | Apps on Azure | All three are free, open-source code: AWS's SDK (Apache-2.0) for S3 and Microsoft's (MIT) for Azure. The providers themselves charge for storage, except the self-hosted ones. ## How uploads work Browsers upload and download directly with short-lived signed URLs, so large files never pass through the app: 1. The browser asks one of your endpoints to upload. The endpoint checks the user may, picks the file's key, and returns `CreateUploadUrlAsync(key, contentType, lifetime)`: a URL and the headers to send. 2. The browser `PUT`s the file to that URL with those headers. 3. The browser tells your endpoint it's done. The endpoint checks the file with `GetInfoAsync` (size, content type) before using it, and deletes it if it doesn't qualify. S3 and Azure can't limit a signed upload's size, so this check is what enforces your limits. Download a file with a URL from `CreateDownloadUrlAsync(key, fileName, lifetime)`. On every provider the browser saves it as an attachment named `fileName` (`Content-Disposition: attachment`, signed into the URL), so an uploaded HTML page or SVG drawing is never opened as a page on the store's address, where it could pose as your app. An `` still shows a picture from it. Files the app writes itself (such as a resized picture) go through `SaveAsync`; `OpenReadAsync`, `GetInfoAsync` and `DeleteAsync` do the rest. **Todo attachments are the worked example** (`Features/Todos/TodoAttachments.cs` and `TodoAttachmentEndpoints`, and `useAttachFile` in the client's `features/todos/todoQueries.ts`). They add what a real feature needs around the three steps: * **An upload token.** Step 1 returns, with the URL, the file's key, name and type encrypted with Data Protection, and step 3 takes it back, so the browser can't change what it's finishing or where it goes. It expires with the URL. * **Limits checked twice:** the size the browser declares before the upload, and the stored size after it (`Attachments:MaxBytes`, 25 MB by default; `Attachments:MaxPerTodo`, 10). * **Abandoned uploads cleaned up.** Starting an upload schedules `DeleteAttachmentIfUnused` for after the token expires, which deletes the file unless it was attached by then. Removing an attachment sends the same message, so the file goes once the change is saved. * **Downloads by short-lived link:** the browser can't send the access token with a plain link, so it asks the API for a 5-minute download URL, then follows it. Keys are paths such as `organisations/{id}/logo.webp`: segments of letters, digits, `.`, `_` and `-`, separated by `/`. The same rules apply on every provider, so a key that works locally works in production. Put the owner first (the user or organisation ID), and give keys an extension: local disk has nowhere else to keep a file's content type. ```csharp // Step 1: the browser asks to upload a report's PDF. // (The Todo attachments show the whole flow, with its checks.) [WolverinePost("/api/reports/{reportId}/upload")] public static Task Post(Guid reportId, IFileStorage storage, CancellationToken cancellationToken) => storage.CreateUploadUrlAsync($"reports/{reportId}/{Guid.NewGuid():N}.pdf", "application/pdf", TimeSpan.FromMinutes(10), cancellationToken); ``` ## Deleting an owner's files When an owner of files is deleted (a user, an organisation, a record with attachments), delete its files by publishing `DeleteStoredFiles` with its prefix from the handler that deletes its data. ::: info With accounts `Pictures/PictureCleanup.cs` does this for `AccountDeleted`: ```csharp public static ValueTask Handle(AccountDeleted message, IMessageContext context) => context.PublishAsync(new DeleteStoredFiles($"users/{message.UserId}/")); ``` ::: ::: info Without accounts For example, for a project whose files are under `projects/{id}/`: ```csharp public static ValueTask Handle(ProjectDeleted message, IMessageContext context) => context.PublishAsync(new DeleteStoredFiles($"projects/{message.ProjectId}/")); ``` ::: Don't call `IFileStorage` in that handler. Each handler of a message runs on its own (its own transaction and retries; `MultipleHandlerBehavior.Separated` in `Program.cs`), but a storage outage there would still fail and repeat that feature's data clean-up with it. `DeleteStoredFiles` is sent only once the data is deleted, and retried on its own (after 1 minute, 10 minutes, 1 hour and 6 hours) until the store answers. For a single file that's been replaced, delete it in the background the same way, once the change is saved, and check first that nothing uses it any more (`DeletePictureIfUnused` is an example). ## Local disk Files go under `Storage:Local:RootPath` (`data/files` in the app's folder by default, relative to it unless absolute, with or without a trailing `/`; `src/ApiHost/data/files/` is in `.gitignore`). Signed URLs point at the app itself (`/api/files`), with the key, the operation and the expiry encrypted in the URL by ASP.NET Core Data Protection. `Storage:Local:MaxUploadBytes` (25 MB by default) caps each upload. Downloads come from the app's own address, so a stored HTML page or SVG drawing could run scripts as the app if a browser opened it. Besides coming as an attachment, as on every provider, each download is sent with `Content-Security-Policy: default-src 'none'; sandbox`, so nothing in it can run even if it's opened anyway. In a container, put the folder on a volume, or files disappear with the container. `deploy/docker-compose.yml` mounts the `app-files` volume at `/app/data`; back it up with the database (see [deploy/README.md](./deploy-to-a-server.md)). Local disk only works with one instance of the app: with more, use S3 or Azure. ## S3-compatible storage Set these as environment variables, or in `deploy/.env` as `STORAGE_PROVIDER=S3` and the `S3_*` values: | Setting | Value | |---|---| | `Storage__Provider` | `S3` | | `Storage__S3__ServiceUrl` | The store's endpoint. Leave empty for AWS itself | | `Storage__S3__Region` | AWS: the bucket's region. R2: `auto`. Others: whatever they document (often `us-east-1`) | | `Storage__S3__Bucket` | The bucket, which must already exist | | `Storage__S3__AccessKey`, `Storage__S3__SecretKey` | An access key for the bucket. On AWS you can leave them empty to use an instance or task role | | `Storage__S3__ForcePathStyle` | `true` for most self-hosted stores (the bucket goes in the path, not the host name) | Some examples: | Provider | `ServiceUrl` | `Region` | |---|---|---| | AWS S3 | (empty) | `eu-west-1` | | Cloudflare R2 | `https://.r2.cloudflarestorage.com` | `auto` | | Backblaze B2 | `https://s3..backblazeb2.com` | ``, such as `eu-central-003` | | Hetzner | `https://.your-objectstorage.com` | ``, such as `fsn1` | | Google Cloud Storage | `https://storage.googleapis.com` | `auto` | | SeaweedFS, Garage, Ceph, RustFS | Your server, such as `https://s3.example.com` | `us-east-1` (with `ForcePathStyle=true`) | **Google Cloud Storage** speaks the S3 API through its XML API: create an HMAC key for a service account (Cloud Storage → Settings → Interoperability) and use it as the access key. Signed uploads, downloads and the rest of `IFileStorage` work; some S3 features this app doesn't use (such as multipart upload details) differ. The app turns off the checksums that the AWS SDK adds to every request by default since 2025, which many S3-compatible stores reject. ## Azure Blob Storage Set these as environment variables, or in `deploy/.env` as `STORAGE_PROVIDER=AzureBlob` and the `AZURE_STORAGE_*` values: | Setting | Value | |---|---| | `Storage__Provider` | `AzureBlob` | | `Storage__AzureBlob__ConnectionString` | The storage account's connection string, with its key (signed URLs are signed with it) | | `Storage__AzureBlob__Container` | The container (`files` by default); created on first use | Azure doesn't speak the S3 API, so it has its own implementation. Signed URLs are SAS URLs. ## Let browsers reach the store (CORS) With S3 or Azure, the browser uploads straight to the store, from your app's address. The store must allow that, or the browser blocks the upload. The app's Content-Security-Policy already allows the store's address. Allow `PUT` and `GET` from your app's address, with any headers: * **S3-compatible stores:** a CORS rule on the bucket, in the provider's dashboard or with `aws s3api put-bucket-cors --bucket --endpoint-url --cors-configuration '{"CORSRules":[{"AllowedOrigins":["https://app.example.com"],"AllowedMethods":["PUT","GET"],"AllowedHeaders":["*"],"MaxAgeSeconds":3600}]}'`. * **Azure:** Storage account → Resource sharing (CORS) → Blob service, or `az storage cors add --services b --methods GET PUT --origins https://app.example.com --allowed-headers '*' --max-age 3600 --connection-string ""`. ## Trying each provider locally `docker compose --profile storage up -d` starts SeaweedFS (S3, on port 8333) and Azurite (Azure, on port 10000). Then run the API with one of: ```bash # S3 (SeaweedFS allows any origin, so no CORS rule is needed) Storage__Provider=S3 Storage__S3__ServiceUrl=http://localhost:8333 Storage__S3__Bucket=files \ Storage__S3__AccessKey=dev-access-key Storage__S3__SecretKey=dev-secret-key Storage__S3__ForcePathStyle=true \ dotnet run --project src/ApiHost # Azure (Azurite's well-known development account) Storage__Provider=AzureBlob \ Storage__AzureBlob__ConnectionString="UseDevelopmentStorage=true" \ dotnet run --project src/ApiHost ``` For browser uploads to Azurite, add a CORS rule for `http://localhost:5173` with the `az` command above and the same connection string. ::: info With the tests ## Tests `tests/ApiHost.Tests/FileStorageTests.cs` runs the same tests against every provider: local disk through the app, S3 against SeaweedFS and Azure against Azurite, each in a container. If you write your own implementation (for example for another cloud), add a class that inherits `FileStorageContract` and it gets the same tests. ::: --- --- url: /saas-starter/latest/guide/analytics.md --- # Analytics and cookie consent ::: tip What this page covers Every choice of `--Persistence`, `--Auth`, `--IncludeTests` and `--Aspire`: a label says which options a part is for. The copy in your app's `docs/` folder has only the parts for yours. `ApiHost` stands for your app's name. ::: The app has no analytics code. It has one switch: a Google Tag Manager container. Once that's set, the app asks each visitor which cookies they accept, and loads Tag Manager only after they accept some. Google Analytics, Datadog, Rollbar and other tools are then added as tags in Tag Manager, without changing the app. Without a container, the app shows no banner, because it sets no cookies that need consent ([what it does set](./security.md#cookies-and-consent)). ## Turning it on 1. Create a container at [tagmanager.google.com](https://tagmanager.google.com) (type: Web), and note its ID, such as `GTM-ABC1234`. 2. Set `Analytics__GoogleTagManagerId` to that ID. 3. For each tool you add in Tag Manager, allow its addresses in the [Content-Security-Policy](#the-content-security-policy). | Setting | What it does | |---|---| | `Analytics__GoogleTagManagerId` | The container's ID. Empty (the default): no Tag Manager and no banner | | `Analytics__ConsentVersion` | The cookie policy's version (default `1`). Raise it when the cookies you use change, and everyone is asked again | | `Analytics__ConnectOrigins__0`, `__1`, ... | Origins your tags send data to or load tracking pixels from (`connect-src` and `img-src`) | | `Analytics__ScriptOrigins__0`, `__1`, ... | Origins your tags load scripts from (`script-src`), besides Tag Manager's own | The app checks these at startup and refuses to start if one is malformed, such as an ID that isn't `GTM-...` or an origin that isn't a plain `https://` address. ## What visitors see When there's a container, a banner shows at the bottom of each page until the visitor chooses. It has **Accept all**, **Reject all** and **Choose**, which lets them pick: * **Necessary:** always on. These are the cookies the app needs to work, so they need no consent. * **Analytics:** for counting visits and seeing which pages are used. * **Marketing:** for measuring and personalising advertising. Refusing takes one click, the same as accepting, as the GDPR expects. **Cookie settings** in the footer brings the choices back, so people can change their mind. Change the banner's wording in `src/Client/src/features/consent/CookieConsent.tsx` so it describes your own tags. The choice is kept in a `cookie_consent` cookie for six months, after which people are asked again. Its value is `..`, such as `1.1.0`. A choice made under an older `ConsentVersion` doesn't count, so the banner shows again. ::: info With accounts **With an account, the choice is saved in the person's [preferences](./accounts.md#preferences) too** (`PUT /api/account/consent`), with the policy version and the time they chose. That records what each person agreed to and when, and their other devices don't ask again: * **When someone signs in,** a choice saved in their preferences is applied to that browser. If there's none yet, the browser's choice is saved to their preferences. * **A choice made while signed in** is saved straight away. A new choice replaces the last one. * **The saved choice** is in `GET /api/account/preferences` (`consent`) and in the person's data export. It's deleted with the account. ::: ## How it reaches Tag Manager Tag Manager isn't loaded until the visitor accepts analytics or marketing cookies, so nothing reaches Google before they choose. Nothing is loaded at all if they reject both. The app passes each choice on with Google's [Consent Mode](https://developers.google.com/tag-platform/security/guides/consent): | Choice | Consent Mode | |---|---| | Analytics | `analytics_storage` | | Marketing | `ad_storage`, `ad_user_data`, `ad_personalization` | | Necessary | `functionality_storage` and `security_storage`, always granted | Google's own tags, such as Google Analytics and Google Ads, follow Consent Mode by themselves. Other tags need a **consent check** in Tag Manager: in the tag's *Advanced settings → Consent settings*, require `analytics_storage` (or `ad_storage` for marketing tags). If someone withdraws consent later, the app tells Tag Manager straight away. Tags stop using the refused cookies, but Tag Manager stays loaded until the next page load. Cookies the tags set earlier stay until they expire, and Google's tags don't read them while consent is refused. ## The Content-Security-Policy In production, the app's Content-Security-Policy blocks scripts, connections and images from other sites ([security](./security.md)). With a container set, Tag Manager's own origin (`https://www.googletagmanager.com`) is allowed. Add the origins your tags use: * **Data and pixels (`ConnectOrigins`):** these can be broad. * **Scripts (`ScriptOrigins`):** keep these as narrow as you can. Allowing scripts from a broad origin such as `https://*.google.com` would let an injected script load through it. The app writes no inline scripts for Tag Manager, so the policy still doesn't allow `'unsafe-inline'` or `'unsafe-eval'`. That means: * **Custom HTML tags** with inline `