moth

module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 3, 2026 License: MIT

README

moth

Self-hosted authentication for your mobile apps — in one binary.
One instance hosts your whole portfolio of apps. No SaaS bill, no lock-in.

Website & docs · Quick start · Changelog · MIT


What & why

moth is a single Go binary that gives your mobile apps sign-up, sign-in, email verification, password reset, and Sign in with Google/Apple — backed by per-project ES256 JWTs any standard library can verify offline.

It also monetizes them: App Store and Google Play subscription receipts are validated server-side (no billing SaaS), the same tiers sell on the web through Stripe-hosted Checkout, and everything is distilled into entitlements like pro your app gates on, sold through a themed paywall configured from the admin, and reported as revenue per month on the analytics tab. A free tier is always built in, so paid subscriptions stay optional. On device, the first-party moth_billing plugin runs the native purchase itself — StoreKit 2 on iOS, Play Billing on Android — so selling needs one dependency and zero adapter code.

And it registers their devices for push notifications: every signed-in device reports its APNs / FCM / Web Push credential (with an honest permission state) through the moth_push plugin or the React useMothPush() hook, and your backend reads the live registry over moth.server.v1 and sends with the push services' own APIs. moth registers, your server sends — sender credentials never touch it, and dead tokens age out through sign-out, feedback, and staleness sweeps.

Every app you ship is a project: a sealed tenant with its own users, its own signing keypair, its own provider credentials, its own login branding, its own subscription tiers, its own analytics. Adding app #10 costs what app #1 did — one project created in the admin, zero new infrastructure.

Everything ships inside the binary: the SQLite database, the admin web console, the hosted email pages, the fonts, the Flutter SDK packages (moth_auth plus the moth_billing and moth_push native companions, served from the instance's own pub repository), the @moth/react React SDK (served from the instance's own npm registry), the CLI, and the documentation you're reading (served at /docs, version-matched to the binary). moth serve and you're running.

Reach for moth when you want Firebase-style auth for a portfolio of apps but would rather own the data, the bill, and the deployment.

moth admin console Themed login screen (light) Themed login screen (dark)

Quick start

Four steps from nothing to a logged-in Flutter app (full version in the quick start guide):

# 1. Build the single binary (release binaries & Homebrew tap ship with v1.0).
make build            # → bin/moth

# 2. Run it. Open the admin, complete first-run setup, create a project,
#    and copy its publishable key (pk_…).
./bin/moth serve      # http://localhost:8080/admin

# 3. Add the SDK to your Flutter app from moth's own pub repository.
#    (dart pub speaks to the instance you just started.)
dart pub add moth_auth \
  --hosted-url http://localhost:8080/pub
#    React app instead? The instance serves an npm registry too:
#      echo '@moth:registry=http://localhost:8080/npm' >> .npmrc
#      npm install @moth/react

# 4. Point the client at your instance + project and sign a user in.
final moth = MothClient(
  baseUrl: 'http://localhost:8080',
  publishableKey: 'pk_...',
);
await moth.signUp(email: email, password: password);
final session = await moth.signIn(email: email, password: password);
// session.accessToken is an ES256 JWT verifiable against the project JWKS.

Deploy it for real

moth is CGO-free and self-contained, so deployment is "copy the binary + one data directory". The installation guide covers moth.toml, a hardened systemd unit, Docker, and reverse proxies (Caddy/Traefik/nginx) including the HTTP/2-end-to-end requirement native gRPC needs. A scratch-based image is a docker build . away (see Dockerfile).

docker build -t moth .
docker run -d -p 8080:8080 -v moth-data:/data \
  -e MOTH_BASE_URL=https://auth.example.com moth

Performance

argon2id password verification — deliberately slow — dominates SignIn cost, so honest throughput is tens-to-low-hundreds of sign-ins per second per core, with steady-state token refreshes far cheaper. moth ships a repeatable ghz harness at scripts/loadtest/ so you can measure the number on your hardware. This project does not quote a load figure it has not measured on the machine it attributes it to; recorded runs live in scripts/loadtest/RESULTS.md.

Development

See CONTRIBUTING.md and CLAUDE.md for the layout and conventions. Common targets:

Command What
make build build bin/moth (embeds the SPA + docs)
make test go test ./...
make dev Go server on :8080 + Vite SPA on :5173
make proto regenerate gen/ + the TS client
make docs-embed re-sync the embedded /docs from the website
make website build the public website

License

MIT © 2026 Aloïs Deniel. The moth_auth Flutter SDK is MIT too.

Directories

Path Synopsis
cmd
moth command
Command moth is the single-binary auth server for mobile apps.
Command moth is the single-binary auth server for mobile apps.
gen
internal
acme
Package acme wires golang.org/x/crypto/acme/autocert so a bare VPS can get a Let's Encrypt certificate straight from the single moth binary via --acme-domain, with no reverse proxy in front.
Package acme wires golang.org/x/crypto/acme/autocert so a bare VPS can get a Let's Encrypt certificate straight from the single moth binary via --acme-domain, with no reverse proxy in front.
analytics
Package analytics runs the milestone-07 aggregate-and-prune job: it rolls the raw event stream up into per-project daily_stats rows (bucketed in each project's rollup timezone) and prunes events older than the project's retention window.
Package analytics runs the milestone-07 aggregate-and-prune job: it rolls the raw event stream up into per-project daily_stats rows (bucketed in each project's rollup timezone) and prunes events older than the project's retention window.
audit
Package audit records the append-only admin/security audit log.
Package audit records the append-only admin/security audit log.
backup
Package backup produces and restores a single-file archive of a moth data directory: an online-consistent snapshot of the SQLite database plus the uploads and key material.
Package backup produces and restores a single-file archive of a moth data directory: an online-consistent snapshot of the SQLite database plus the uploads and key material.
billing
Package billing validates App Store and Google Play subscription receipts and parses the two stores' server notifications, mapping both into one normalized model.
Package billing validates App Store and Google Play subscription receipts and parses the two stores' server notifications, mapping both into one normalized model.
cli
Package cli implements the moth binary's remote-client mode: named contexts (server URL + personal access token) stored in ~/.config/moth/config.toml, connect clients for the moth.admin.v1 services authenticated by that token, and the declarative dump/apply logic built on ProjectSpec.
Package cli implements the moth binary's remote-client mode: named contexts (server URL + personal access token) stored in ~/.config/moth/config.toml, connect clients for the moth.admin.v1 services authenticated by that token, and the declarative dump/apply logic built on ProjectSpec.
config
Package config resolves the moth server configuration.
Package config resolves the moth server configuration.
docs
Package docs embeds the moth documentation and serves it, rendered to self-contained HTML, at /docs inside the binary.
Package docs embeds the moth documentation and serves it, rendered to self-contained HTML, at /docs inside the binary.
entitlements
Package entitlements holds the pure entitlement-derivation engine: given a user's subscription rows and grants, it computes the set of entitlement identifiers the user currently holds.
Package entitlements holds the pure entitlement-derivation engine: given a user's subscription rows and grants, it computes the set of entitlement identifiers the user currently holds.
events
Package events captures the server-emitted analytics events of milestone 07.
Package events captures the server-emitted analytics events of milestone 07.
fonts
Package fonts ships the curated set of open-license typefaces a project theme can pick from (plan/06).
Package fonts ships the curated set of open-license typefaces a project theme can pick from (plan/06).
httpsec
Package httpsec is the security-header middleware for moth's HTML and JSON surfaces: a strict Content-Security-Policy, HSTS (https only), X-Content-Type-Options, Referrer-Policy and frame options.
Package httpsec is the security-header middleware for moth's HTML and JSON surfaces: a strict Content-Security-Policy, HSTS (https only), X-Content-Type-Options, Referrer-Policy and frame options.
i18n
Package i18n is moth's self-contained message catalog and locale negotiation.
Package i18n is moth's self-contained message catalog and locale negotiation.
jwt
Package jwt signs and verifies moth access tokens: compact JWS with ES256, a kid header, and the fixed claim set moth mints.
Package jwt signs and verifies moth access tokens: compact JWS with ES256, a kid header, and the fixed claim set moth mints.
keys
Package keys manages the instance master key and per-project ES256 signing keypairs.
Package keys manages the instance master key and per-project ES256 signing keypairs.
mail
Package mail delivers moth's transactional emails.
Package mail delivers moth's transactional emails.
metrics
Package metrics is moth's lightweight instrumentation: a small in-process registry of counters and latency histograms and an http.Handler that renders them in Prometheus text exposition format (version 0.0.4).
Package metrics is moth's lightweight instrumentation: a small in-process registry of counters and latency histograms and an http.Handler that renders them in Prometheus text exposition format (version 0.0.4).
netutil
Package netutil derives the real client IP behind an optional set of trusted reverse proxies.
Package netutil derives the real client IP behind an optional set of trusted reverse proxies.
oidc
Package oidc verifies Google and Apple ID tokens for social sign-in and talks to the providers' OAuth token endpoints.
Package oidc verifies Google and Apple ID tokens for social sign-in and talks to the providers' OAuth token endpoints.
password
Package password hashes and verifies passwords with argon2id.
Package password hashes and verifies passwords with argon2id.
paywall
Package paywall defines the per-project paywall configuration: the copy and layout knobs that the SDK's batteries-included paywall screen renders from (milestone 13).
Package paywall defines the per-project paywall configuration: the copy and layout knobs that the SDK's batteries-included paywall screen renders from (milestone 13).
profile
Package profile defines the per-project setup profile (milestone 22): the creation wizard's answers — platforms, sign-in intent, monetization and push intent, plus the checklist-dismissed flag.
Package profile defines the per-project setup profile (milestone 22): the creation wizard's answers — platforms, sign-in intent, monetization and push intent, plus the checklist-dismissed flag.
push
Package push defines the per-project push settings: the enabled switch for the push-device registry (milestone 20) and the Web Push VAPID public key browser clients subscribe with.
Package push defines the per-project push settings: the enabled switch for the push-device registry (milestone 20) and the Web Push VAPID public key browser clients subscribe with.
pwimport
Package pwimport verifies foreign password hashes so users migrated from another auth system (Firebase, Auth0, Supabase, a home-grown backend) can sign in with their existing password without a reset.
Package pwimport verifies foreign password hashes so users migrated from another auth system (Firebase, Auth0, Supabase, a home-grown backend) can sign in with their existing password without a reset.
ratelimit
Package ratelimit is moth's shared, SQLite-backed rate limiter for the credential-facing surfaces.
Package ratelimit is moth's shared, SQLite-backed rate limiter for the credential-facing surfaces.
server
Package server assembles the moth HTTP handler: connect (gRPC / gRPC-Web) services and the plain-HTTP surfaces, multiplexed on one port.
Package server assembles the moth HTTP handler: connect (gRPC / gRPC-Web) services and the plain-HTTP surfaces, multiplexed on one port.
server/rpc/admin
Package adminrpc implements the moth.admin.v1 connect services.
Package adminrpc implements the moth.admin.v1 connect services.
server/rpc/auth
Package authrpc implements moth.auth.v1.AuthService — the public end-user authentication API.
Package authrpc implements moth.auth.v1.AuthService — the public end-user authentication API.
server/rpc/billing
Package billingrpc implements moth.billing.v1.BillingService — the publishable-key + Bearer client API for subscriptions and entitlements — and hosts the shared store-validation plumbing the webhook and reconciliation sweep reuse.
Package billingrpc implements moth.billing.v1.BillingService — the publishable-key + Bearer client API for subscriptions and entitlements — and hosts the shared store-validation plumbing the webhook and reconciliation sweep reuse.
server/rpc/push
Package pushrpc implements moth.push.v1.PushService — the publishable-key + Bearer client API for the push-device registry (milestone 20).
Package pushrpc implements moth.push.v1.PushService — the publishable-key + Bearer client API for the push-device registry (milestone 20).
server/rpc/serverapi
Package serverapi implements moth.server.v1 — the services the developer's own backend calls with the project secret key (`x-moth-key: sk_...`): online token introspection and programmatic user management.
Package serverapi implements moth.server.v1 — the services the developer's own backend calls with the project secret key (`x-moth-key: sk_...`): online token introspection and programmatic user management.
setup
Package setup implements the provider-console orchestration behind `moth setup google`, `moth setup apple` and `moth doctor`: guided or partially automated configuration of the Google/Apple sign-in consoles for one moth project, always followed by verification.
Package setup implements the provider-console orchestration behind `moth setup google`, `moth setup apple` and `moth doctor`: guided or partially automated configuration of the Google/Apple sign-in consoles for one moth project, always followed by verification.
skill
Package skill renders the embedded moth agent skill: a SKILL.md + references/ directory (the Agent Skills format) teaching a coding agent both halves of moth — integrating the Flutter SDK into an app and administering an instance through the CLI.
Package skill renders the embedded moth agent skill: a SKILL.md + references/ directory (the Agent Skills format) teaching a coding agent both halves of moth — integrating the Flutter SDK into an app and administering an instance through the CLI.
store
Package store is the SQLite persistence layer: connection setup, embedded migrations, and hand-written queries behind small per-domain interfaces (no ORM).
Package store is the SQLite persistence layer: connection setup, embedded migrations, and hand-written queries behind small per-domain interfaces (no ORM).
theme
Package theme defines the per-project design system: a small, versioned set of tokens (colors, typography, spacing, corner radius, logo, legal links) that every end-user surface — the Flutter login screen, hosted web pages, emails — renders from.
Package theme defines the per-project design system: a small, versioned set of tokens (colors, typography, spacing, corner radius, logo, legal links) that every end-user surface — the Flutter login screen, hosted web pages, emails — renders from.
token
Package token generates and hashes the random secrets moth hands out: publishable/secret API keys, admin session tokens, setup tokens.
Package token generates and hashes the random secrets moth hands out: publishable/secret API keys, admin session tokens, setup tokens.
version
Package version exposes the build version of the moth binary.
Package version exposes the build version of the moth binary.
Package proto embeds the .proto sources so the server can offer them for download from the admin setup-instructions page (developers generate their own moth.server.v1 clients from these).
Package proto embeds the .proto sources so the server can offer them for download from the admin setup-instructions page (developers generate their own moth.server.v1 clients from these).
scripts
example_backend command
Command example_backend is the "your own API" half of the moth loop: a tiny HTTP server that authenticates requests by verifying the moth access token (an ES256 JWT) against the project's public JWKS — exactly what any real backend does, in ~200 lines of standard library.
Command example_backend is the "your own API" half of the moth loop: a tiny HTTP server that authenticates requests by verifying the moth access token (an ES256 JWT) against the project's public JWKS — exactly what any real backend does, in ~200 lines of standard library.
Package sdk embeds the moth_auth, moth_billing and moth_push Flutter package sources and the built @moth/react npm package so the server can serve them as a pub hosted repository under /pub and an npm registry under /npm.
Package sdk embeds the moth_auth, moth_billing and moth_push Flutter package sources and the built @moth/react npm package so the server can serve them as a pub hosted repository under /pub and an npm registry under /npm.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL