A tinderbox holds what you need to start a fire; this one holds what an Igniter
needs to catch. It is an Igniter template: point
mix igniter.new at it and it scaffolds one of three Elixir stacks, plus the local
tooling to run it — an emulator-backed docker-compose.yml, the environment those
services need, and a .mise.toml that pins the toolchain and gives you the
dev-loop tasks.
- API stack — Phoenix API-only + Ash + AshPostgres + AshJsonApi + AshPhoenix,
with a working JSON:API resource reachable at
/api. - Worker stack — headless OTP daemon: a Broadway pipeline that consumes from one
messaging endpoint, records each message id in an Ash/AshPostgres idempotency store,
and publishes the transformed message to a second endpoint of the same broker.
Brokers:
sqs,pubsub,rabbitmq,kafka,nats. - SaaS stack — a Phoenix LiveView application with password and SSO sign-in,
two-factor authentication (TOTP, or the SSO provider's MFA),
organizations with memberships and invitations, notifications (in-app inbox and
email), Stripe subscriptions, an admin area, a JSON:API with OpenAPI docs and
OAuth2 client-credentials connections for machines, JetStream domain events,
feature flags, health, metrics and tracing, a release
Dockerfileand a CI workflow — every page built on the themepack UI kit. On top of that, what a venture studio needs to launch a business and judge it: a landing page and waitlist drawn fromconcept.exs, first-party analytics and a validation funnel at/admin/validation, the project's own generators (mix <app>.gen.concept,.gen.live,.gen.resource,.gen.domain) and a Fly.io deployment.
Separately, mix tinderbox.gen.ui adds that UI kit to any Phoenix LiveView
project (--stack ui on install): a themeable component library, an app shell
and a live component gallery at /dev/ui. See UI kit.
All stacks also get object storage (<App>.Storage) with two interchangeable
backends — s3 through ex_aws and gcs through Req — both pointed at the local
emulators. It has put/2, get/1, delete/1 and presign/2 (S3 only: GCS needs a
service-account key to sign URLs and answers {:error, :not_supported}).
# API stack
mix igniter.new my_api \
--with phx.new \
--with-args="--no-html --no-assets --no-live --no-dashboard --no-mailer --no-gettext" \
--install tinderbox@path:/Users/jamescarr/projects/upmarkethq/tinderbox \
--stack api
# Worker stack
mix igniter.new my_worker --sup \
--install tinderbox@path:/Users/jamescarr/projects/upmarkethq/tinderbox \
--stack worker --broker sqs
# SaaS stack (a full Phoenix app: keep phx.new's defaults)
mix igniter.new my_app \
--with phx.new \
--install tinderbox@path:/Users/jamescarr/projects/upmarkethq/tinderbox \
--stack saas --themepack ember
# Only the UI kit, on a plain Phoenix app (no compose, no mise)
mix igniter.new my_app \
--with phx.new \
--install tinderbox@path:/Users/jamescarr/projects/upmarkethq/tinderbox \
--stack ui --themepack harbor@path:… installs from the working copy. To install from this repository instead,
swap the source (and drop the local path):
mix igniter.new my_worker --sup \
--install tinderbox@github:jamescarr/tinderbox \
--stack worker --broker sqsWith mise (the default):
mise trust && mise install # once: allow .mise.toml, install Elixir + Erlang
mise run dev # start the services, set up the database, run the appmise run dev is up → setup → mix phx.server (API, http://localhost:4000/api;
SaaS, http://localhost:4000, admin at /admin) or mix run --no-halt (worker,
http://localhost:4001/health).
Run bare mix commands through mise exec -- mix … when .mise.local.toml sets
anything: a plain shell does not load it, so mix test would reach for the default
ports. mix ash.codegen prints "this migration includes destructive operations" for
every migration whose down/0 drops what its up/0 creates, the first one included;
on a new resource that is expected.
Without mise:
docker compose up -d --wait
cp .env.example .env && . ./.env # every line is exported; no `set -a` needed
mix ash.setup
mix phx.server # or: mix run --no-halt| Flag | Applies to | Default | Meaning |
|---|---|---|---|
--stack api|worker|saas|ui |
installer | — (required) | which stack to generate; ui installs only the UI kit |
--themepack ember|slate|harbor |
saas, ui | ember |
the UI kit's look; see UI kit |
--broker sqs|pubsub|rabbitmq|kafka|nats |
worker | sqs |
messaging technology for both the inbound consumer and the outbound publisher. The SaaS stack always runs on nats (JetStream) and ignores the flag |
--no-compose |
both | compose generated | skip docker-compose.yml / .env.example |
--no-mise |
both | mise generated | skip .mise.toml |
--no-demo |
api | demo generated | skip the demo Catalog domain + Catalog.Item resource |
--deploy fly|none |
saas | fly |
fly.toml, fly/nats/fly.toml, the README's Fly.io runbook, flyctl and mise run deploy; none leaves them out |
--file-drop |
saas | off | the file drop at /drop (see SaaS stack), a ClamAV service in compose's scan profile, FILE_DROP_*/CLAMAV_* in .env.example and .mise.toml, FILE_DROP_SCANNER = "none" in fly.toml |
--integrations |
saas | off | the integrations framework at /integrations; implies --file-drop |
--plaid |
saas (also tinderbox.gen.compose, .gen.mise) |
off | the Plaid connector: bank links at /integrations/plaid, transaction sync, Plaid webhooks; implies --integrations; PLAID_* in .env.example, .mise.toml and fly.toml |
--no-db |
tinderbox.gen.compose, tinderbox.gen.mise |
Postgres service | skip the Postgres service and DATABASE_URL |
The individual tasks (tinderbox.gen.api, .worker, .saas, .compose, .mise) can
be re-run in an existing project. Re-running fails on the files a task creates —
compose, .env.example, .mise.toml, generated modules — rather than overwriting
them, and then writes nothing at all. The edits it makes to files that already exist
are guarded and not applied twice: dependencies, config/runtime.exs, ash_domains,
the supervisor children, .gitignore, and the /api mount in the router (the
guarded edits of the SaaS stack are covered by a test that applies it twice; the
real re-run was only seen to refuse, see below). tinderbox.gen.ui is the exception:
it skips kit modules that exist and is meant to be re-run, to switch packs.
tinderbox.install removes the
tinderbox path dependency from mix.exs when it finishes, because the path only
exists on the generating machine and mix deps.get fails anywhere else (CI first);
add it back for the run, as its notice says, before re-running a task.
Generated projects carry a .mise.toml (skip it with --no-mise):
[tools]— Elixir and Erlang, pinned to the toolchain that ran the generator (for example1.20.4-otp-29and29.1).mix newwrites the running Elixir's major.minor intomix.exsas itselixir:requirement, so a fixed pin would makemise run devfail Mix's version check for anyone generating on another release (phx.newwrites a fixed lower bound, which any newer Elixir satisfies). A dev or pre-release Elixir has no mise version: the pins then fall back to the pair this package was verified with,1.20.4-otp-29and29.1, and the generator prints a notice. The Kafka worker also pins CMake, becausebrod'scrc32cerNIF is built from source.[env]— the local environment:PGPORT(the host port compose publishes for Postgres, read byconfig/dev.exsandconfig/test.exs), the emulator endpoints,STORAGE_BACKEND, and for the workerHEALTH_PORTplus the broker's variables..env.exampleis rendered from the same data, so the two cannot drift.[tasks.*]:
| Task | Does |
|---|---|
mise run up |
docker compose up -d --wait — returns once Postgres, the emulators and the bootstrap jobs are done |
mise run down |
docker compose down |
mise run setup |
up, then mix deps.get and mix ash.setup |
mise run dev |
setup, then the app |
mise run test |
up, then mix test |
mise run check |
up, then mix format --check-formatted, mix compile --warnings-as-errors, mix test |
mise run health |
worker only: curl the health endpoint on $HEALTH_PORT |
mise run stripe |
SaaS only: stripe listen --forward-to localhost:4000/webhooks/stripe; copy the printed whsec_… into .mise.local.toml as STRIPE_WEBHOOK_SECRET |
--no-compose leaves out up/down and the depends on them.
Tasks are inline tables, not .mise/tasks/* files: a file task has to be executable,
which files an igniter writes are not, and mise does not list a non-executable file
task until it has been run once.
Machine-specific overrides go in .mise.local.toml (gitignored; mise layers it
over .mise.toml). For example, when something else owns the default ports:
[env]
HEALTH_PORT = "4022" # the worker reads it in config/runtime.exs
PORT = "4111" # phx.new's runtime.exs reads it for the APIDATABASE_URL and POOL_SIZE are read by MIX_ENV=prod runs only; dev and test
take their Postgres settings from config/dev.exs and config/test.exs.
ash.install,ash_postgres.install,ash_json_api.install— run by igniter, they create<App>.Repo,<App>Web.AshJsonApiRouter, the:apipipeline, and the/api/jsonmount (swagger UI at/api/json/swaggerui).<App>.Catalog+<App>.Catalog.Item— demo domain and resource (itemstable, uniquesku), registered inconfig :<app>, ash_domains:and in the router'sdomains:list.<App>Web.Router— the AshJsonApi router is additionally mounted in an alias-freescope "/api"placed after the installer's/api/jsonscope, soPOST/GET/PATCH/DELETE /api/itemsspeak JSON:API and swagger stays reachable.<App>.Storage+ the:ex_aws/:storageruntime config.
<App>.Inbox+<App>.Inbox.Message— the idempotency store: one row per message id, unique identity onmessage_id,processed_atset only after the outbound publish succeeded.<App>.Pipeline— Broadway pipeline. Producer per broker:BroadwaySQS.Producer/BroadwayCloudPubSub.Producer/BroadwayRabbitMQ.Producer/BroadwayKafka.Producer. Duplicates (bymessage_id) are acked and skipped; failures are failed, leaving redelivery to the broker.<App>.Processing— the seam for real business logic:handle/1receives the decoded payload and returns the payload to publish.<App>.Publisher— outbound write:ExAws.SQS/ Pub/Sub REST:publish/AMQPwith publisher confirms /:brod.produce_sync. RabbitMQ and Kafka also get a connection process (<App>.Publisher.Connection,<App>.Publisher.KafkaClient) that is supervised before the pipeline.<App>.Health—Plug.RouterservingGET /health(200 when the pipeline is alive, 503 otherwise), served by Bandit onHEALTH_PORT.
Needs a Phoenix project with LiveView and assets (mix igniter.new … --with phx.new
with its default flags); it refuses one without. The generator installs and wires
ash_authentication(_phoenix), oban, ash_oban and ash_paper_trail next to the
Ash packages the other stacks use, then adds:
- Sign-in —
<App>.Accounts.Userwith a password strategy (bcrypt) and an SSO strategy over OpenID Connect (SSO_BASE_URL,SSO_CLIENT_ID,SSO_CLIENT_SECRET,SSO_REDIRECT_URI). Locally Dex issues the tokens (docker/dex/config.yaml, one static user,admin@example.com/password); register<SSO_REDIRECT_URI>/user/sso/callbackwith a real issuer. Users are:useror:admin: an email inADMIN_EMAILSgets:adminwhen it registers. The list is empty in production unless you set it. The magic-link route the installer adds is removed. - Two-factor authentication — for the two setups a SaaS meets: self-hosted TOTP,
and an identity provider that already does MFA. People turn TOTP on at
/settings/security(QR code, a confirming code, ten recovery codes shown once); sign-in then asks for a code at/mfa(<App>Web.MfaController) before anyone is signed in. Ten wrong codes in a row lock the factor for 15 minutes, a code is never accepted twice (the database settles concurrent requests), recovery codes are stored as SHA-256 hashes, and the TOTP secret is encrypted at rest (AshCloak, AES-GCM,<App>.Vault, keyed byCLOAK_KEY). Platform admins see everyone's status at/admin/securityand can reset a user who lost the device and the codes.MFA_REQUIRED=truesends everyone without a factor to set one up at their next sign-in (and takes away the switch to turn it off); that enrolls whoever holds the password at that moment, so switch it on after the people who matter have enrolled.MFA_SSO=idptrusts the MFA the provider reports in the OIDC ID token (amr, oracragainstSSO_MFA_ACR;SSO_ACR_VALUESasks the provider to step up,urn:okta:loa:2fa:anyfor Okta); an SSO sign-in without it falls back to the same code prompt, it is not refused.<App>.Accounts.MFAis the facade and<App>.Accounts.MFA.Providerthe behaviour for another kind of factor. Only sign-ins finished by<App>Web.AuthControllerare gated: code that signs a user in some other way has to callMFA.sign_in_step/2too. A project generated before this existed gets it withmix tinderbox.gen.mfa(it addsnimble_totp,eqrcode,cloakandash_cloakitself, creates anadd_mfamigration, and replacesAuthControlleronly while it is still the installer's). - File drop (opt-in,
--file-drop) — owners and admins drop files at/drop(CSV, OFX/QFX, PDF, ZIP, EML, TXT, 25 MiB each by default).<App>.FileDrop.receive_file/4andreceive_binary/5check the size, read the type from the bytes (the extension must agree), deduplicate by sha256 per organization and store the file underdrop/<organization id>/…, a keyFileControllernever serves. The upload's:ingestAshOban job scans it (FILE_DROP_SCANNER:none, orclamavfor aclamdreached overINSTREAM; production refuses to boot without a value) and hands a clean file to<App>.FileDrop.Handler(config:handler). Downloads are always attachments.mix tinderbox.gen.file_dropadds it to an existing project. - Integrations (opt-in,
--integrations, brings the file drop) — a connector framework:<App>.Integrations.Connectorturns dropped files, webhook deliveries (POST /webhooks/integrations/<source id>, bearer token) or scheduled pulls into records; each organization's sources (/integrations) keep config, encrypted credentials and a hashed token; every record is stored once per source, type and external id and handed, with retries, to<App>.Integrations.Handler, the module the application edits. A record the handler rejects ({:reject, message}: a field missing or malformed) fails at once instead of retrying;/integrationscounts a source's failed records, shows why the latest failed, and puts them back in line. The genericwebhookconnector is what n8n, Zapier or Make post to; no workflow engine is deployed.mix tinderbox.gen.integrationsadds it (and the file drop) to an existing project. - Plaid (opt-in,
--plaid, brings integrations) —<App>.Integrations.Connectors.Plaid: owners and admins link a bank through Plaid Link at/integrations/plaid(the/integrationsform links there instead of offering it); the access token is kept in the source's encrypted credentials. The 15-minute:synctrigger pulls/transactions/syncfrom the cursor kept on the source, and Plaid'sSYNC_UPDATES_AVAILABLEwebhook (an ES256 JWT over the body's sha256, checked against Plaid's key) asks for a sync at once. Records reach the handler asaccount,transaction,transaction.modified(one record per revision) andtransaction.removed, each numbered in delivery order (data["seq"], continued across syncs) so a handler can drop a stale one. Deleting a source calls/item/removefirst (the connector'sdisconnect/1; an error keeps the source). Tests run againstPlaid.Client.Fake, never plaid.com; production refuses to boot withoutPLAID_CLIENT_IDandPLAID_SECRET.mix tinderbox.gen.plaidadds it (with integrations and the file drop when missing) to an existing project. - Organizations —
<App>.Accounts.Organization,Membership(owner,admin,member) andInvitation(email, role, token link). The creator becomes the owner; the last owner cannot be removed or demoted. Re-inviting an address updates the open invitation instead of adding a row. Organizations, memberships, invitations, connections and subscriptions keep a version history (AshPaperTrail; the version row carriesorganization_id, indexed with its time, throughAccounts.VersionIndexes); the invitation token is kept out of it./activity(<App>.Activity.feed/2) lists the latest versions of every organization-scoped resource, newest first, with who did it and what it set. - Notifications —
<App>.Notificationswith a catalog (member.invited,member.joined,subscription.updated,payment.failed), an in-app inbox at/inboxthat updates live and a per-user email toggle at/settings/notifications. Email goes through an Oban job and Swoosh (SMTP to Mailpit locally,SMTP_*in production).<App>.Notifications.Adapteris the seam for another channel. - Billing —
<App>.Billingwithstripity_stripe. Two plans fromSTRIPE_PRICE_STARTERandSTRIPE_PRICE_PRO;/billingstarts a Checkout session for an organization without a subscription and opens the Billing Portal for one that has one. Plan changes happen in the portal: a second Checkout for a subscribed organization is refused, because it would bill twice. Webhooks arrive at/webhooks/stripe, are verified againstSTRIPE_WEBHOOK_SECRETbefore the body is parsed, are stored once per event id, and an AshOban trigger fetches the subscription from Stripe and upserts the organization's singlesubscriptionsrow. A change of status notifies the organization's owners and admins. - Events —
<App>.Eventsover NATS JetStream: stream<app>-events, subjects<app>.events.<type>. Every create, update and destroy of an organization, membership, invitation or subscription is published as<resource>.<action>through anAsh.Notifier;<App>.Events.Handleris where consumers go. A handler that raises is nacked. The payload is the record's public attributes except thesensitive?ones (asecretattribute is one), sopublic?on an attribute also puts it on the event bus. - API — AshJsonApi at
/api/jsonand/api(organizations), OpenAPI at/api/json/open_api, Swagger UI at/api/json/swaggerui, bearer-token sign-in through the installer's:apipipeline. A request without a token gets200with an emptydatalist, not403: the installer configures Ash to filter instead of forbid. - API connections —
/connectionslists an organization's OAuth2 client-credentials connections (every member sees them); owners and admins create and revoke them.<App>.Connections.Connectionrecords a client held by an authorization server thatOAUTH_PROVIDERselects through<App>.Connections.Provider, the waySTORAGE_BACKENDselects the storage backend:hydra(Ory Hydra, in compose at:4444tokens and:4445admin, keeping its clients in ahydradatabase on the compose Postgres; withHYDRA_ADMIN_TOKENset it drives hosted Ory Network) orauth0(the Management API; a Machine-to-Machine application withcreate:clients,delete:clientsandcreate:client_grants). Both adapters are always generated; the tests use an in-memoryfakeone. Dex cannot issueclient_credentialstokens, which is why it stays for SSO only. The secret is shown once, on the page, and stored nowhere. A client asks the provider's token endpoint for a JWT access token withaudience=$OAUTH_AUDIENCE;<App>.Connections.Tokensverifies it against the issuer's JWKS (OIDC discovery:iss,aud,exp,nbfand an asymmetric algorithm), and<App>Web.Plugs.LoadConnection, after the user's bearer token in the:apipipeline, makes the unrevoked connection behind it the Ash actor. A token that was not issued byOAUTH_ISSUERis left alone (the policies see no actor); one that was and is not valid, or whose connection is revoked, gets401andWWW-Authenticate: Bearer error="invalid_token". Revoking deletes the client at the provider and marks the row, so a token that has not expired stops working on its next request. A connection has no scopes: it reads what the read policies allow it, and<App>.Accounts.Organizationlets it read its own organization. - API rate limit —
<App>Web.Plugs.RateLimitfollowsLoadConnectionin the:apipipeline:API_RATE_LIMITrequests (default 600) perAPI_RATE_WINDOW_MS(default 60000) for each connection, else each signed-in user, else each IP address, withx-ratelimit-limit/x-ratelimit-remainingheaders and429+retry-afterpast the limit. The counters are Hammer's ETS tables (<App>.RateLimit), so the limit is per node; multi-node deployments switchbackend:to Hammer's Redis backend. - Admin —
/admin(the UI kit, in the app shell): dashboard, users, organizations (and one organization), subscriptions, validation, the waitlist, and the FunWithFlags dashboard at/admin/flags. Only:adminusers get in: anyone else is sent to the dashboard, the flag dashboard and the waitlist CSV answer404, and an anonymous visitor goes to sign-in. - The concept —
concept.exsat the project root is the business on one page: name, tagline, description, call to action (:waitlistor:register), value propositions, plans, the Ash domain and its resources, the activation event and the validation thresholds.mix <app>.gen.conceptchecks it (every problem reported at once), rewrites<App>.Conceptfrom it, and generates the resources that are new (withnav, their pages too) with one migration. The landing page, the app shell's brand and the browser tab are drawn from<App>.Concept; until the task runs it says what the stack does. The landing page's value propositions and pricing grids fit the count (one centered, two side by side, three or more in columns). - Validation — first-party analytics in Postgres:
<App>.Analytics.track/3andchange {<App>.Analytics.Changes.Track, event: …}record named events (a landing view with itsutm_*and referrer, a waitlist sign-up, a sign-in, an organization, every generated resource's<name>.created); a visitor cookie (<App>Web.Plugs.Visitor) counts distinct visitors; the landing page's waitlist (POST /waitlist, one row per address) is listed at/admin/waitlistand exported at/admin/waitlist.csv./admin/validation(<App>.Analytics.Funnel) shows visitors → waitlist → registered → organizations → activated → paying, the conversion between them, the last eight weeks, and a verdict against the thresholds: on track, too early (day N ofwithin_days), or below. - The project's generators —
tinderboxleaves the project, so its generators stay:mix <app>.gen.resource <App>.Things.Thing name:string:required status:enum:a,b owner:belongs_to:User …(an organization-scoped resource: owners and admins write, members read, platform admins bypass;SameOrganizationon references; a<thing>.createdevent;[:organization_id, :inserted_at]and everybelongs_tocolumn indexed; a version history for/activity; its fixture and migration),mix <app>.gen.live(the same, plus list, show and form pages that read at most 1000 rows, routes, a navigation entry and a test; its form prefills requireddateanddatetimefields with today/now, and afileattribute —attachment:file:required— gets a file input that stores the upload in<App>.Storageunder<organization id>/…, with links on the pages to<App>Web.FileController, which serves it to the members of that organization only; asecretattribute —api_key:secret:required— is encrypted at rest with AshCloak through<App>.Vault, kept off the event bus and the activity feed, and shown masked, with a password input that is never prefilled),mix <app>.gen.conceptandmix <app>.gen.domain. Their templates are copied intopriv/templates/<app>.gen/for the project to edit; the shared code (Mix.<App>.Gen) has no Igniter in it and the tasks compile to aMix.raisein production. - Fly.io (
--deploy fly, the default) —fly.toml(the release image,bin/migrateas the release command overDIRECT_DATABASE_URLwhen set, the IPv6/PgBouncer/Tigris/Resend environment the runtime config reads, an always-on machine checked at/health),fly/nats/fly.toml(JetStream on a volume, on the private network only), flyctl in.mise.toml,mise run deploy, and a one-time runbook in the project README (apps, NATS volume, Managed Postgres, Tigris, secrets). - Feature flags — FunWithFlags stored through
<App>.Repo, cache busting over<App>.PubSub; users are actors and organizations are groups (<App>.FeatureFlags). Both packages areruntime: falsedependencies and areleases:entry loads them:FunWithFlags.Supervisorstarts in the application tree afterPhoenix.PubSub, because left to itself FunWithFlags starts before the host application and gives up subscribing after five seconds. - Operations —
GET /health({"status":"ok"}), PromEx metrics atGET /metrics(not authenticated: keep it off the public internet), OpenTelemetry for Phoenix, Ecto, Oban and Bandit (exports whenOTEL_EXPORTER_OTLP_ENDPOINTis set),Dockerfileandrel/frommix phx.gen.release --docker, and.github/workflows/ci.yml, which installs Hex, fetches deps and runsmise run check. - For the code you add —
<App>.Accounts.managers/1(an organization's owners and admins, the recipients the billing and invitation notifications use);<App>.Accounts.Changes.InheritOrganization(copyorganization_idfrom a parent record, as a plain change so the policy sees it),<App>.Accounts.Validations.SameOrganization(reject referenced ids that belong to another organization) and<App>.Accounts.Changes.NotifyManagers(notify the managers after the transaction commits; a failure is logged, never undoes the change);<App>Web.LiveHelpers(find/4,report/3(socket |> report(result, msg)),manager?/1,error_message/1,format_value/1,display_name/1, shared by the organization pages); the kit'shumanize/1,format_number/2(grouped thousands,compact: truefor112.4M) andenum_options/2(select options for an enum); a:require_managerhook in<App>Web.LiveOrganizationfor owner/admin-only pages;Layouts.apptakeswidefor pages made of tables andcurrent_pageto highlight its navigation entry;<App>.PromEx.Plugins.App, an empty PromEx plugin for the application's own metrics;<App>.Fixturesand<App>Web.LiveTestHelpers.sign_in/2intest/support, used bytest/<app>_web/live/members_live_test.exs, withadmin_fixture/1,signup_fixture/1andevent_fixture/2beside them; and aREADME.mdin place of Phoenix's (running it, configuration, validation, deploying, and these conventions), written once.
In production (the release image) the application refuses to start without
DATABASE_URL, SECRET_KEY_BASE and TOKEN_SIGNING_SECRET (AshAuthentication's;
runtime.exs raises when it is missing) and CLOAK_KEY (openssl rand -base64 32;
encrypts the two-factor secrets, so keep it). Also set PHX_HOST, PHX_SERVER=true, the
NATS_*, SMTP_*, STRIPE_*, SSO_*, MFA_*, OAUTH_* (and HYDRA_* or AUTH0_*),
PLAID_* (with --plaid; the keys are required) and ADMIN_EMAILS values of
.mise.toml.
Run migrations with the release's bin/migrate. With SMTP_USERNAME (and
SMTP_PASSWORD) set, mail is authenticated and upgraded with verified STARTTLS;
behind PgBouncer set DATABASE_POOLER=pgbouncer (unnamed prepared statements and
Oban's PG notifier); on an IPv6-only private network (Fly) set NATS_INET6=true.
/health is exempt from force_ssl, so a platform's plain-HTTP health check is not
redirected.
Every page uses the UI kit (<App>Web.UI, see below) next to Phoenix's daisyUI core
components; the stack applies the --themepack (default ember) before anything
else.
Needs a Phoenix LiveView project with its Tailwind + daisyUI assets (phx.new's
defaults); it refuses one without assets/css/app.css. It works on a plain
phx.new project and is part of the SaaS stack.
A themepack is a light and a dark daisyUI theme (colors, radii, density), font stacks, and the shape of the app shell. All packs share one component kit:
| Pack | Shell | Look |
|---|---|---|
ember (default) |
sidebar | Warm orange on charcoal, medium density |
slate |
sidebar | Neutral grays with indigo, compact: dense tool UIs |
harbor |
top navigation | Blue and white, roomy |
The generator:
- replaces Phoenix's two stock themes in
assets/css/app.csswith the pack's, between/* tinderbox:themepack … */markers (the themes stay namedlightanddark, so Phoenix's theme toggle keeps working), and setsconfig :<app>, <App>Web.UI, themepack: …, shell: …; - creates the kit, once — after that it is the project's code:
<App>Web.UI(used byhtml_helpers/0, so every template sees it),.Components(page_header,card,stat_grid,badge,status_badge,alert,empty_state,description_list,bar_list,tabs,modal,dropdown,avatar,feed,form_section,search_input,pagination,relative_time/1,format_datetime/1,humanize/1,format_number/2,enum_options/2),.Shell(app_shell,nav_item,nav_section,user_menu),.DataTable(searchable, sortable, paginated) and.ListState(the table's in-memory search/sort/paging state, with its test); - mounts
<App>Web.UIGalleryLiveat/dev/uiinside Phoenix's dev-only scope: every component, live, in the current pack; - on a plain project, replaces Phoenix's demo
Layouts.appwith one in the app shell (a customized layout is left alone, with a notice).
Switch packs by re-running it: mix tinderbox.gen.ui --themepack slate rewrites
only the themepack region of app.css and the config. Without --themepack the
installed pack is kept. Components style themselves only through daisyUI's semantic
colors and radii, so a pack restyles all of them, in light and dark.
docker-compose.yml— Postgres (host port$PGPORT, default 5432), Floci (:4566, S3 + SQS), floci-gcp (:4588, GCS + Pub/Sub) and their bootstrap jobs, plus RabbitMQ, Redpanda or NATS (JetStream,:4222) for those brokers; the SaaS stack adds NATS, Dex (:5556), Ory Hydra (:4444tokens,:4445admin, with two one-shot jobs that create and migrate its database) and Mailpit (SMTP$SMTP_PORT, UI$MAILPIT_UI_PORT, default 1025 and 8025). A worker onnatsalso gets anats-bootstrapjob that creates its two streams and the consumer. The app itself runs on the host, soFLOCI_HOSTNAMEis deliberately unset: Floci then embedslocalhostin the SQS queue URLs and pre-signed URLs. Areadyservice depends on every bootstrap job completing: compose failsup --waitwhen a job merely exits, even with status 0, unless a running service is waiting for it. It runs under an init, becausesleepas PID 1 ignores SIGTERM anddocker compose downwould otherwise wait out Docker's 10 s stop timeout..env.example— the same variables as[env], every lineexported..mise.toml— see above.config/dev.exs,config/test.exs— the repo'sport:readsPGPORT..gitignore— gains.env,docker-compose.override.ymland.mise.local.toml.config/runtime.exs— appended, outside theif config_env() == :prodblock, so it applies in every environment::ex_aws(with theAWS_ENDPOINT_URLhost/port override andExAws.Request.Reqas the HTTP client, which keeps hackney out),:storage, and — for the worker —:pipelineand:health_port. Every value has the compose default, so mix tasks that load it (ash.codegen,ash.setup,test) work before any environment is loaded.
--broker |
Client dep | Compose service | Inbound | Outbound |
|---|---|---|---|---|
sqs |
broadway_sqs, ex_aws_sqs |
— (Floci) | SQS_QUEUE_URL |
SQS_PUBLISH_QUEUE_URL |
pubsub |
broadway_cloud_pub_sub |
— (floci-gcp) | PUBSUB_SUBSCRIPTION |
PUBSUB_TOPIC |
rabbitmq |
broadway_rabbitmq |
rabbitmq |
RABBITMQ_QUEUE (bound to RABBITMQ_EXCHANGE) |
RABBITMQ_PUBLISH_QUEUE via RABBITMQ_ROUTING_KEY |
kafka |
broadway_kafka (:brod) |
redpanda |
KAFKA_CONSUMER_TOPIC |
KAFKA_PRODUCER_TOPIC |
nats |
gnat (Gnat.Jetstream.PullConsumer) |
nats |
NATS_STREAM + NATS_CONSUMER (durable, pull) |
NATS_PUBLISH_SUBJECT |
One broker technology per worker, used for both directions. To consume from X and
publish to Y, generate with the consumer's broker and edit <App>.Publisher.
Notes per broker:
- pubsub — the producer talks to floci-gcp through
base_url+token_generator: {<App>.Pipeline, :emulator_token, []}; Goth (and real GCP credentials) is only needed for real Pub/Sub. - rabbitmq —
<App>.Publisher.Connectiondeclares the durable topic exchange, the outbound queue and their binding, and publishes with confirms, so:okmeans RabbitMQ persisted the message. - kafka —
broadway_kafkabuilds brod'scrc32cerNIF from source, so CMake= 3.16 is needed to compile it (mise installs it for you).
- nats — streams live in the broker, not the app: the compose
nats-bootstrapjob creates<app>-inbound(subject<app>.inbound),<app>-outboundand the<app>-workerconsumer. The publisher waits for JetStream'sPubAck, and sendsmessage_idasNats-Msg-Idso a retry inside the stream's duplicate window is stored once.
mise run check # format, warnings-as-errors compile, testsThe generators are exercised through Igniter.Test.test_project/1 against the
Tinderbox.Gen.* modules, and mix tinderbox.install is composed against a test
project to cover flag handling and the files and notices each flag combination
produces. What a test project cannot do is fetch the packages the tasks declare in
installs: or run their installers. The SaaS generator is therefore tested against
test/fixtures/saas/: the files Phoenix, Ash, AshAuthentication, AshOban and Oban's
installers wrote in a real project (mix.exs, router, endpoint, application, user
resource and the rest), with the UserIdentity resource that ash.gen.resource
would have created. It also checks that applying the generator twice changes none of
the files the installers wrote.
Beyond that, generated projects were run end to end against the emulators:
-
worker / sqs, through mise, installed from
@github:jamescarr/tinderbox—mise run dev(up → setup → run) came up healthy. A message sent to the inbound queue came out of the outbound queue withprocessed_atadded; sending the same body again, under the samemise run dev, produced no second message, leftinbox_messagesat one processed row, and left the inbound queue empty. SettingHEALTH_PORTin.mise.local.tomlmoved the app to the new port;mise run downreturned in under a second;mise run checkpassed. -
storage —
STORAGE_BACKEND=s3round-trips through Floci (aws s3 lssees the object) andSTORAGE_BACKEND=gcsthrough floci-gcp; a missing key is{:error, :not_found}on both. -
api —
POST /api/itemsreturns201 Createdwith the JSON:API document,GET /api/itemslists it,/api/json/open_apiand/api/json/swaggeruistill serve the OpenAPI document, andmix compile --warnings-as-errorsis clean. -
broker matrix —
pubsub,rabbitmqandkafkaworkers compile with--warnings-as-errors; the pubsub worker consumed a message published todemo-pubsub-inboundon floci-gcp and published the transformed payload (plus itsmessage_idattribute) todemo-pubsub-outbound. -
worker / nats — a worker generated with
--broker natsran undermise run dev;/healthanswered{"status":"ok"}. The same JSON body (with anid) published twice to<app>.inboundleft one message in<app>-outbound, withprocessed_atadded, one processed row ininbox_messages, and the consumer with both deliveries acked (no pending, none redelivered).mise run checkpassed. -
saas — generated with
mix igniter.new … --with phx.new --install tinderbox@path:… --stack saas --yes(about four minutes).mise run checkpasses on the fresh project: formatting, warnings-as-errors compile and seven tests, the five Phoenix generates and the generated members page test (the owner sees the invite form, a member does not); the generated tests cover no other SaaS feature. Undermise run dev, against compose (the first group on an earlier generation, which differed from the next one only in how FunWithFlags starts, the formatting of the generated migration and a compile-warning pragma):- password registration (it signs the user in) and SSO through Dex; the SSO user in
ADMIN_EMAILSis an admin, a password user is not, and the SSO user gets no confirmation email; - an organization is created (the creator is its owner); inviting an address sends
an email to Mailpit, the invitee registers, accepts and lands on the dashboard as
a
member; /admin,/admin/users,/admin/organizationsand/admin/subscriptionsrender for the admin; for a member/adminredirects and/admin/flagsis404; anonymous/adminredirects to/sign-in;GET /api/organizationswithout a token is200with an emptydatalist.
On that next generation, before the shared helpers: SSO sign-in, creating an organization, the flag dashboard creating a flag that lands in
fun_with_flags_toggles,organization.createandmembership.addin the<app>-eventsstream and acked once each byEvents.Handler,/health200and/metricsserving over a thousand<app>_series.On the latest generation (shared helpers, test support, ports from the environment): the install task removed the
tinderboxpath dependency frommix.exsand printed it; withPGPORT=5456,SMTP_PORT=1027,MAILPIT_UI_PORT=8027andPORT=4112in.mise.local.toml(this machine's 5432, 1025 and 8025 belong to other projects), compose published Postgres on 5456 and Mailpit on 1027/8027 andmise run checkpassed against them. Pushed unchanged to a private repository, the generated.github/workflows/ci.ymlpassed (Hex, deps,mise run checkwith the seven tests, about twelve minutes onubuntu-latest). On the generation just before it, which differed only in the members page's role-form id and two documentation comments,/metricsserved 360<app>_series with the empty<App>.PromEx.Plugins.App,/healthwas200, and throwaway tests showed:require_managercontinuing for the owner, sending a member to/dashboardwith an error flash and a user with no organization to/organizations/new, andAccounts.managers/1returning the owner and an admin but not a member. A worker generated the same way (--stack worker --broker sqs) got theport:line inside the repo's block inconfig/dev.exsandconfig/test.exs(both imported byconfig.exs) and passedmise run checkwith Postgres onPGPORT=5457.On an earlier generation, not repeated since: a live inbox row and badge update without a reload, the
member.joinednotification and email to the owner, the per-event email toggle persisting, a re-invite updating one row instead of adding one, the version rows AshPaperTrail writes (without the invitation token),/api/json/open_apilisting the organization paths, and FunWithFlags connecting to PubSub on the first try.Stripe was only exercised against stripe-mock, not Stripe itself (on the generation before the last). The customer is created and its id stored on the organization, the Billing Portal URL comes back, and stripe-mock accepted the Checkout session parameters. It returns no Checkout
url, so the redirect (and the "no checkout page" message for that case) was not seen. Signed webhooks were posted to/webhooks/stripe: a wrong signature is400; a validcustomer.subscription.createdis stored once (the same event id again adds no row), an unrelated event type is acknowledged and ignored, and the subscription was synced in 0.3 s into onesubscriptionsrow (starter,active), with asubscription.updatednotification and email; aninvoice.payment_failedproducedpayment.failedthe same way. For that, the organization'sstripe_customer_idandSTRIPE_PRICE_STARTERwere set to the values of stripe-mock's fixture subscription. - password registration (it signs the user in) and SSO through Dex; the SSO user in
-
saas release image —
docker buildproduced the image (mix assets.deploy,mix release) and the container booted against the compose services:/health,/metricsand/sign-inanswered, andFunWithFlagstoggled and persisted a flag throughbin/<app> rpc. The image was built from a project whosemix.exshad been edited by hand to what the generator writes (a generated one has the same entries withreleases:last inproject/0). The release does not boot withoutTOKEN_SIGNING_SECRET. -
saas re-run —
mix tinderbox.gen.saasin a generated project reports "File already exists" for each module it would create and writes nothing; the guarded edits are only covered by the test that applies the generator twice. -
saas two-factor authentication — a project generated from this branch (
mfa_demo, ports from.mise.local.tomlbecause other projects held 4222, 4566, 4588 and 5556):mise run checkpassed (formatting, warnings-as-errors compile, 38 tests, 25 of them the generated MFA tests: the facade and TOTP provider, the controller, the settings page). Undermise run dev, in a browser:- a password user turned TOTP on at
/settings/security(QR code and manual key, a confirming code, ten recovery codes); the code was computed from the displayed key by a script, not by an authenticator app, and the QR code was not scanned; - sign out and in landed on
/mfawith/dashboardsent back to/sign-inmeanwhile; a wrong code gave the error and stayed, the right code signed in, a recovery code signed in once and was refused the second time; - a throwaway test sent one TOTP code, then one recovery code, through 20
concurrent
MFA.verify/2calls: each time one returned:okand 19{:error, :invalid_code}; with the spent-code filter taken out ofTotp.record_success/3, all 20 calls accepted the same TOTP code; /admin/securityas anADMIN_EMAILSuser listed the user as On with nine recovery codes; Reset (with its confirm dialog) turned it Off;- with
MFA_REQUIRED=truea user without a factor was sent to/mfa/setupafter the password, confirming showed the recovery codes, Continue signed in, and/settings/securityhad no turn-off form; - SSO through Dex with
MFA_SSO=idp: with no factor the SSO sign-in completed, and with one it went to/mfa, because Dex sends noamr; so what was seen is the fallback to the local rules. A throwaway test of thessostrategy's:registeraction with an unsigned ID token carryingamr: ["pwd","mfa"]put that on the user, and withMFA_SSO=idpsign_in_step/2was:completefor the SSO sign-in and:enrollfor a password one underMFA_REQUIRED; - with
SSO_ACR_VALUES=urn:okta:loa:2fa:anythe redirect to the provider carriedacr_values=urn%3Aokta%3Aloa%3A2fa%3Aanynext toscope=openid+openid+profile+email(Assent prependsopenidto the strategy's scope); MIX_ENV=prod mix run -e ''withoutCLOAK_KEY(everything else set) exited withenvironment variable CLOAK_KEY is missing.
mix tinderbox.gen.mfawas run in a project generated from the commit before this one (pre_mfa, notmain, which is behind it): it added the four packages tomix.exs, created the modules,*_add_mfa.exs(amfa_factorstable only) and the tests, put Security in the user menu and Two-factor in the admin navigation, and replacedAuthController. With thetinderboxdependency removed again,mise run checkpassed (38 tests);/settings/securityrendered undermise run dev; running the task again exited 1 withalready exists: this project has multi-factor authentication. Since the task only writes the packages tomix.exs(Igniter runsmix deps.getbefore the queuedash.codegen), a freshpre_mfarun created*_add_mfa.exswithout aCloak.Vault is not loadedfailure, andmise run checkpassed (38 tests). Not exercised: a real identity provider that sendsamr/acr(Okta, Entra, Auth0, Keycloak), an authenticator app, concurrent guesses against the lockout, and the customized-AuthControllerwarning outside the generator test. - a password user turned TOTP on at
-
saas
mix <app>.gen.domain— in a project generated from this branch (saas_check, ports as above),mix saas_check.gen.domain SaasCheck.Upstreams --queues upstreams:5,dead_letters --yescreatedSaasCheck.Upstreams(use Ash.Domain, otp_app: :saas_check), put it first inash_domainsand appendedupstreams: 5, dead_letters: 10to the Oban queues (default: 10, billing: 5, notifications: 10kept). Run again with--queues upstreams:9it changed nothing;--queues "bad name"exited 1 withInvalid --queues entry "bad name"and changed nothing.mise run checkthen passed (7 tests).MIX_ENV=prod mix compile --force --warnings-as-errorscompiled the task without igniter, and running it in prod exited 1 saying it needs igniter. -
ui —
mix igniter.new ui_plain --with phx.new --with-args="--no-ecto" --install tinderbox@path:… --stack ui --themepack harbor --yes: format, warnings-as-errors compile (dev and prod, so no~p"/dev/…"slipped in) and 11 tests passed (Phoenix's five and the generatedListStateTest's six), and the built CSS carries harbor's tokens. In a browser at/dev/ui: the topnav shell, searching, sorting (witharia-sortflipping) and paging the table, the modal opening and closing on Escape with focus moved in and back, tabs patching?tab=, and light/dark. Re-runningmix tinderbox.gen.ui --themepack slatechanged onlyassets/css/app.cssandconfig/config.exs, and the gallery came up in the sidebar shell, whose drawer opens from the menu button and closes on the overlay at phone width. Phoenix's own landing page does not useLayouts.app, so it keeps its look. -
saas on the UI kit — generated with
--themepack ember(and again withslate): nopetalinmix.exsormix.lock, 13 tests passed. Undermix phx.server(Postgres, Mailpit and NATS only, on other ports): the topnav landing page signed out; registration, creating an organization, inviting, the dashboard, members, inbox, notification settings and billing in the sidebar shell with the current page highlighted;/adminand its users (search, sort by Registered, Make admin), organizations → View and subscriptions pages; the flag dashboard; light and dark. SSO was not exercised in this run (another project held Dex's port);ADMIN_EMAILSmade the password user an admin. -
saas API connections — generated as above (the generator's own tests plus
mise run checkon the fresh project, regenerated from the final templates: 22 tests, among them threeConnectionsLiveTestand sixApiConnectionsTestcases that run on thefakeprovider;MIX_ENV=prod mix compile --warnings-as-errorsis clean). Withash3.36.0, which a fresh resolution now picks, generation stops inmix ash.codegen(Multiple actions (2) with the name readonAccounts.UserIdentity, which the AshAuthentication installer helper creates;mainfails the same way), so that run pinned{:ash, "== 3.35.0"}and ran the three tasks the generator had queued by hand (the generator has since removed thatdefaults [:read]; see the studio_demo run below). Compose came up withhydrahealthy andhydra-db/hydra-migrateexited 0, discovery answeringjwks_urihttp://localhost:4444/.well-known/jwks.json. Undermise run dev, in a browser: API connections in the sidebar, creatingCIshowed the client id, secret, token endpoint and audience once (dismissed with Done).curl -uagainst:4444/oauth2/tokengave a JWT (client_id,isshttp://localhost:4444/,audhttp://localhost:4000/api); with itGET /api/organizationslisted only that connection's organization (a second user's organization was absent), and/admin/clientslisted the client. Revoking it on the page (confirm dialog) turned the row to Revoked without a button; the same token was answered401,WWW-Authenticate: Bearer error="invalid_token"and the JSON:API error body, a new token request with the old credentials wasinvalid_client, and the client was gone from Hydra.GET /api/organizationswithout a token stayed200with an emptydata, and a signed-in user's bearer token still listed their organizations. Aftermise run down && mise run upa connection created before was still in Hydra and its token flow worked. Throwaway tests against that Hydra: a member's create is forbidden before the provider is called; an unreachable provider is reported on the name field; a second revoke is refused; a create whose row fails to write (unknown organization, as a platform admin) deletes the client it registered, which was run again on the regenerated project, along with a token from an issuer whose JWKS cannot be fetched, with nothing cached, being answered401in 45 ms. The other projects on this machine held 4222, 8222, 4566, 4588 and 5556, so those host ports were moved with adocker-compose.override.yml(andNATS_PORTin.mise.local.toml) instead of stopping them. -
saas production config and building blocks — a project generated from this branch (
tb_learn, ports as above, against the compose services of another project) compiled with--warnings-as-errors, passed its 7 tests without theafter_transactionhook warning, and hadpaths: ["/health"]uncommented inconfig/prod.exsandtypein<.button>'s attribute list.runtime.exsread withConfig.Reader.read!(…, env: :prod)gave{:unnamed, Oban.Notifiers.PG, :always, :verify_peer, [:inet6, :binary]}withDATABASE_POOLER=pgbouncer,SMTP_USERNAMEandNATS_INET6=trueset, and{nil, nil, :never, nil, [:binary]}without them.Storage.put,presign(key, expires_in: 60, disposition: …)anddeleteran against Floci: the presigned URL answered200, bodyhelloand the requestedContent-Disposition;getafterdeletewas{:error, :not_found}and a seconddelete:ok.InheritOrganization,SameOrganizationandNotifyManagersare exercised by trust_manage's suite, which runs the same module bodies. No connection to a real SMTP relay, PgBouncer or Fly network was made. -
saas concept → validated scaffold (
studio_demo) — generated from this branch with a fresh resolution (ash 3.36.1: the generator now drops the identity resource'sdefaults [:read], soash.codegenruns without a pin): 63 tests on the untouched scaffold. With aconcept.exsof two resources (Projectwith an enum and a decimal,Taskbelonging to it),mix studio_demo.gen.conceptwrote the concept, the domain, both resources, six pages, eight routes, two sidebar entries, fixtures, tests and oneadd_coremigration in 7 s;mise run checkpassed 71 tests andMIX_ENV=prod mix compile --force --warnings-as-errorswas clean. Re-running either task changed nothing; a resource with one attribute of every type passed its generated tests too. In a browser: the landing page from the concept (tab<tagline> · Studio Demo), a waitlist sign-up carryingutm_*, an owner creatingAlpha(Active,1,500.00) and a task under it, a member who could read but not add (and got404from the CSV), and/admin/validationreading "Day 1 of 30: 3 of 5 thresholds met".docker build .passed; in the image, fly.toml's release command migrated and the release answered/health. The Fly deployment itself was not run. Details:docs/feedback/studio-demo.md. -
saas file drop and integrations (
itemizer) — generated with--integrationsin 190 s: 118 tests on the untouched scaffold, among them the blocks' seven test files. The slice on top (statements, Amazon's order export and receipt emails become transactions and purchases, matched by amount and date) passed 165; its demo script explained the sampleAPPLE.COM/BILL -59.97as its three items (with the fake model: the run had no Anthropic key). In a browser:/drop,/transactions, a transaction's items,/integrations; the receipt webhook answered 401 without its token and 202 with it. WithFILE_DROP_SCANNER=clamavand the compose ClamAV, the EICAR string ended Infected and its object was deleted.mix tinderbox.gen.integrationson a reset scaffold added both blocks in one migration and its 118 tests passed. Details:docs/feedback/itemizer.md.
Not exercised: the untrusted-config path of mise trust. mise on the machine these
runs were made on never gated .mise.toml (a config with templates and hooks was
reported trusted too), so mise trust was a no-op there. It is left in the
instructions because mise refuses untrusted configs where it is set up to.
Not exercised for the SaaS stack: a real Stripe account (Checkout, the portal's plan
switch, mise run stripe — the Stripe CLI installs through mise and starts, but
stripe listen needs a login), a real OIDC issuer other than Dex, an SMTP server other
than Mailpit, a collector for the OpenTelemetry export, and SSO with the app moved
off port 4000.
Not exercised for API connections: the auth0 adapter (no tenant was at hand: its
requests follow the Management API's documented shapes only), and Hydra as hosted Ory
Network (HYDRA_ADMIN_TOKEN).
If something else already owns 5432, 1025 or 8025 on your machine, set PGPORT,
SMTP_PORT or MAILPIT_UI_PORT in .mise.local.toml: compose publishes
${PGPORT:-5432}:5432 and friends, and config/dev.exs and config/test.exs read
PGPORT. To move the app off 4000, set PORT and SSO_REDIRECT_URI there and add
the new …/auth/user/sso/callback to redirectURIs in docker/dex/config.yaml,
which Dex reads as a file (it otherwise refuses the SSO callback as an unregistered
redirect URI). docker-compose.override.yml is gitignored for any other local
change to the services.