Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
feat: let a self-hoster close registration, and stop shipping a public account (#110)
Carter5dae7c50b2dd
diff --git a/.env.example b/.env.exampleindex cd63e69..e196166 100644--- a/.env.example+++ b/.env.example@@ -5,6 +5,12 @@ JWT_SECRET=change-me-to-a-random-32-plus-character-stringCORS_ORIGIN=http://localhostPORT=80+# open | first-user | closed — https://lyftr.app/configuration/#locking-down-registration+REGISTRATION=open++# Seeds [email protected], whose password is public. Leave off on a reachable instance.+DEMO_MODE=false+# Address the frontend's nginx proxies /api to, over the internal Docker network.# This MUST be the backend's Docker service name (backend) — NOT your host/LAN IP.# Only change the port, and only if you set a custom backend PORT, e.g. backend:3008.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5315e48..c80c45a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -212,12 +212,9 @@ jobs:- name: Install Playwright system dependenciesrun: cd web && npx playwright install-deps chromium webkit- - name: Wait for demo user to be seeded- run: |- timeout 90 bash -c 'until curl -sf -X POST http://localhost/api/v1/auth/login \- -H "Content-Type: application/json" \- -d "{\"email\":\"[email protected]\",\"password\":\"password123\"}" \- | grep -q "token"; do sleep 3; done'+ # Readiness (API up + exercise seed finished) is the suite's own globalSetup now,+ # which registers a throwaway account rather than logging in as a seeded one. So+ # this job runs against the production default: no DEMO_MODE, no demo account.- name: Run E2E testsrun: cd web && npm run test:e2e:dockerdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 885f541..6d380dc 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -19,7 +19,9 @@ go run .# API listens on http://localhost:3000```-On first run the backend seeds a demo account and exercise database automatically.+On first run the backend seeds the exercise database automatically, plus a demo account —+the latter only because `ENV=development`, which is what `DEMO_MODE` defaults to. A+production install seeds no account at all; set `DEMO_MODE=true` if you want one there.**Demo credentials**```diff --git a/README.md b/README.mdindex 1312417..6acc1b7 100644--- a/README.md+++ b/README.md@@ -71,7 +71,7 @@ Open `http://localhost` and create your account.## Try it-- **Live demo** — [lyftr-demo.fly.dev](https://lyftr-demo.fly.dev) · `[email protected]` / `password123` (resets hourly)+- **Live demo** — [lyftr-demo.fly.dev](https://lyftr-demo.fly.dev) · `[email protected]` / `password123` (resets hourly; that account is demo-only — your own install has no default login)- **Android** — [download the APK](https://github.com/Cawlumm/lyftr/releases/latest), then point it at your server ([mobile docs](https://lyftr-app.pages.dev/mobile/)). iOS is planned.## Roadmapdiff --git a/backend/.env.example b/backend/.env.exampleindex ea4eee3..af341c0 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -17,6 +17,12 @@ DB_PATH=./data/lyftr.dbJWT_SECRET=change-me-in-production-min-32-chars!!JWT_EXPIRY=3600+# open | first-user | closed+REGISTRATION=open++# Demo account + sample data. Defaults on when ENV=development, off otherwise.+# DEMO_MODE=true+# CORS — comma-separated allow-list of client origins permitted to call the API.# Use * to allow any origin (the API is Bearer-token based, so no cookies are at risk).CORS_ORIGIN=http://localhost:5173diff --git a/backend/config/config.go b/backend/config/config.goindex 6aea05a..4559739 100644--- a/backend/config/config.go+++ b/backend/config/config.go@@ -3,6 +3,9 @@ package configimport ("log""os"+ "slices"+ "strconv"+ "strings""github.com/joho/godotenv")@@ -21,8 +24,24 @@ type Config struct {CORSOrigin stringEnv stringVersion string++ // Registration is who may create an account: RegistrationOpen, RegistrationClosed,+ // or RegistrationFirstUser (open only while the users table is empty).+ Registration string+ // DemoMode seeds the demo account and its 8 weeks of sample data. Off outside+ // development: the credentials are published in the README, so an instance that+ // seeds them has a known-password account whatever Registration says.+ DemoMode bool}+const (+ RegistrationOpen = "open"+ RegistrationClosed = "closed"+ RegistrationFirstUser = "first-user"+)++var registrationModes = []string{RegistrationOpen, RegistrationClosed, RegistrationFirstUser}+var C *Config// buildVersion is set at build time via:@@ -42,6 +61,8 @@ func Version() string { return buildVersion }func Load() {_ = godotenv.Load()+ env := getEnv("ENV", "development")+C = &Config{Port: getEnv("PORT", "3000"),DBType: getEnv("DB_TYPE", "sqlite"),@@ -54,13 +75,35 @@ func Load() {JWTSecret: getEnv("JWT_SECRET", "change-me-in-production-min-32-chars!!"),JWTExpiry: getEnv("JWT_EXPIRY", "3600"),CORSOrigin: getEnv("CORS_ORIGIN", "http://localhost:5173"),- Env: getEnv("ENV", "development"),+ Env: env,Version: buildVersion,++ Registration: getEnv("REGISTRATION", RegistrationOpen),+ // Contributors following CONTRIBUTING.md get the demo account without setting+ // anything; a self-hoster or the Fly demo has to ask for it.+ DemoMode: getEnvBool("DEMO_MODE", env == "development"),}if C.Env == "production" && C.JWTSecret == "change-me-in-production-min-32-chars!!" {log.Fatal("JWT_SECRET must be set in production")}++ // Refuse to start on a typo rather than falling back to open. REGISTRATION=frst-user+ // silently meaning "anyone may sign up" is the one failure mode that leaves someone+ // believing their instance is locked down when it is not.+ if !ValidRegistration(C.Registration) {+ log.Fatalf("REGISTRATION must be one of %v, got %q", registrationModes, C.Registration)+ }++ if C.Registration == RegistrationFirstUser && C.DemoMode {+ log.Printf("WARNING: REGISTRATION=first-user with DEMO_MODE=true — the seeded demo " ++ "account already occupies the users table, so registration will never open. " ++ "Set DEMO_MODE=false to claim the first account yourself.")+ }+}++func ValidRegistration(mode string) bool {+ return slices.Contains(registrationModes, mode)}func getEnv(key, fallback string) string {@@ -69,3 +112,14 @@ func getEnv(key, fallback string) string {}return fallback}++// getEnvBool reads a boolean env var via strconv.ParseBool — the same spellings the+// rest of Go accepts. Unset or unparseable falls back rather than reading as false, so+// a typo cannot quietly turn a setting off.+func getEnvBool(key string, fallback bool) bool {+ v, err := strconv.ParseBool(strings.TrimSpace(os.Getenv(key)))+ if err != nil {+ return fallback+ }+ return v+}diff --git a/backend/config/config_test.go b/backend/config/config_test.gonew file mode 100644index 0000000..545e35c--- /dev/null+++ b/backend/config/config_test.go@@ -0,0 +1,52 @@+package config++import "testing"++func TestGetEnvBool(t *testing.T) {+ cases := []struct {+ raw string+ fallback bool+ want bool+ }{+ // The spellings strconv.ParseBool takes, which is the point of using it.+ {"true", false, true},+ {"TRUE", false, true},+ {"True", false, true},+ {"1", false, true},+ {" true ", false, true},+ {"false", true, false},+ {"FALSE", true, false},+ {"0", true, false},+ // Unset falls back — this is what makes DEMO_MODE default to ENV=development.+ {"", true, true},+ {"", false, false},+ // Unparseable falls back rather than reading as false: DEMO_MODE=ture should+ // not silently turn seeding off on a demo instance that asked for it.+ {"maybe", true, true},+ {"maybe", false, false},+ {"yes", false, false},+ {"on", true, true},+ }++ for _, tc := range cases {+ t.Setenv("LYFTR_TEST_BOOL", tc.raw)+ if got := getEnvBool("LYFTR_TEST_BOOL", tc.fallback); got != tc.want {+ t.Errorf("getEnvBool(%q, %v) = %v, want %v", tc.raw, tc.fallback, got, tc.want)+ }+ }+}++// Load refuses to start on an unknown mode rather than falling back to open, so this+// is the check that decides between "locked down" and "wide open with a typo".+func TestValidRegistration(t *testing.T) {+ for _, mode := range []string{RegistrationOpen, RegistrationClosed, RegistrationFirstUser} {+ if !ValidRegistration(mode) {+ t.Errorf("ValidRegistration(%q) = false, want true", mode)+ }+ }+ for _, mode := range []string{"", "frst-user", "Open", "first user", "disabled", "true"} {+ if ValidRegistration(mode) {+ t.Errorf("ValidRegistration(%q) = true, want false", mode)+ }+ }+}diff --git a/backend/controllers/auth.go b/backend/controllers/auth.goindex c1f2598..a628206 100644--- a/backend/controllers/auth.go+++ b/backend/controllers/auth.go@@ -2,8 +2,11 @@ package controllersimport ("database/sql"+ "errors"+ "github.com/Cawlumm/lyftr-backend/config""github.com/Cawlumm/lyftr-backend/models"+ "github.com/Cawlumm/lyftr-backend/stores""github.com/Cawlumm/lyftr-backend/utils""github.com/gin-gonic/gin""github.com/go-playground/validator/v10"@@ -11,7 +14,43 @@ import (var validate = validator.New()+// RegistrationClosedMessage is what a rejected signup sees. One constant so the two+// ways of being closed (REGISTRATION=closed, and first-user with the slot taken) are+// indistinguishable to a caller — and so the handler and its tests cannot drift.+const RegistrationClosedMessage = "registration is closed on this server"++// registrationOpen reports whether a new account may be created right now. Errors are+// reported as closed: advertising an open instance because a COUNT failed is the wrong+// direction to fail.+func (h *Handler) registrationOpen() (bool, error) {+ switch config.C.Registration {+ case config.RegistrationClosed:+ return false, nil+ case config.RegistrationFirstUser:+ n, err := h.s.User.Count()+ if err != nil {+ return false, err+ }+ return n == 0, nil+ default:+ return true, nil+ }+}+func (h *Handler) Register(c *gin.Context) {+ // Before binding or hashing: bcrypt on an unauthenticated public endpoint is a free+ // CPU-burn for anyone who finds a closed instance, and the answer does not depend on+ // anything in the body.+ open, err := h.registrationOpen()+ if err != nil {+ utils.DBError(c, err)+ return+ }+ if !open {+ utils.Forbidden(c, RegistrationClosedMessage)+ return+ }+var req models.RegisterRequestif err := c.ShouldBindJSON(&req); err != nil {utils.BadRequest(c, err.Error())@@ -28,7 +67,16 @@ func (h *Handler) Register(c *gin.Context) {return}- userID, err := h.s.User.Create(req.Email, hash)+ create := h.s.User.Create+ if config.C.Registration == config.RegistrationFirstUser {+ create = h.s.User.CreateFirst+ }++ userID, err := create(req.Email, hash)+ if errors.Is(err, stores.ErrRegistrationClosed) {+ utils.Forbidden(c, RegistrationClosedMessage)+ return+ }if utils.IsUniqueViolation(err) {utils.Conflict(c, "email already registered")returndiff --git a/backend/controllers/auth_test.go b/backend/controllers/auth_test.gonew file mode 100644index 0000000..8678e49--- /dev/null+++ b/backend/controllers/auth_test.go@@ -0,0 +1,168 @@+package controllers++import (+ "errors"+ "net/http"+ "testing"++ "github.com/Cawlumm/lyftr-backend/config"+ "github.com/Cawlumm/lyftr-backend/db"+ "github.com/Cawlumm/lyftr-backend/stores"+)++func registerRequest(t *testing.T, email string) int {+ t.Helper()+ c, w := newContext(0, "POST", "/api/v1/auth/register",+ map[string]string{"email": email, "password": "password123"})+ th.Register(c)+ return w.Code+}++func userCount(t *testing.T) int {+ t.Helper()+ var n int+ if err := db.DB.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n); err != nil {+ t.Fatalf("count users: %v", err)+ }+ return n+}++func TestRegisterOpenCreatesAccounts(t *testing.T) {+ setupTestDB(t)+ setRegistration(t, config.RegistrationOpen)++ if code := registerRequest(t, "[email protected]"); code != http.StatusCreated {+ t.Fatalf("status = %d, want 201", code)+ }+ // Open means open: a second, unrelated person may still sign up.+ if code := registerRequest(t, "[email protected]"); code != http.StatusCreated {+ t.Fatalf("second register status = %d, want 201", code)+ }+ if n := userCount(t); n != 2 {+ t.Errorf("user count = %d, want 2", n)+ }+}++func TestRegisterClosedRejectsAndWritesNothing(t *testing.T) {+ setupTestDB(t)+ setRegistration(t, config.RegistrationClosed)++ c, w := newContext(0, "POST", "/api/v1/auth/register",+ map[string]string{"email": "[email protected]", "password": "password123"})+ th.Register(c)++ if w.Code != http.StatusForbidden {+ t.Fatalf("status = %d, want 403", w.Code)+ }+ body := decodeResponse(t, w)+ if body["error"] != RegistrationClosedMessage {+ t.Errorf("error = %v, want %q", body["error"], RegistrationClosedMessage)+ }+ // The rejection must happen before the insert, not merely be reported after one.+ if n := userCount(t); n != 0 {+ t.Errorf("user count = %d, want 0 — a closed instance created an account", n)+ }+}++// A closed instance must not answer differently for a malformed body than for a valid+// one: the reject comes first, so probing register with junk cannot be used to tell a+// closed Lyftr from one that is merely rejecting the payload.+func TestRegisterClosedRejectsBeforeReadingTheBody(t *testing.T) {+ setupTestDB(t)+ setRegistration(t, config.RegistrationClosed)++ c, w := newContext(0, "POST", "/api/v1/auth/register", map[string]string{"email": "not-an-email"})+ th.Register(c)++ if w.Code != http.StatusForbidden {+ t.Fatalf("status = %d, want 403 (got the validation error instead)", w.Code)+ }+}++func TestRegisterFirstUserOpensOnceThenCloses(t *testing.T) {+ setupTestDB(t)+ setRegistration(t, config.RegistrationFirstUser)++ if code := registerRequest(t, "[email protected]"); code != http.StatusCreated {+ t.Fatalf("owner register status = %d, want 201", code)+ }++ c, w := newContext(0, "POST", "/api/v1/auth/register",+ map[string]string{"email": "[email protected]", "password": "password123"})+ th.Register(c)++ if w.Code != http.StatusForbidden {+ t.Fatalf("second register status = %d, want 403", w.Code)+ }+ // Identical to the closed message: a caller cannot tell first-user from closed.+ if body := decodeResponse(t, w); body["error"] != RegistrationClosedMessage {+ t.Errorf("error = %v, want %q", body["error"], RegistrationClosedMessage)+ }+ if n := userCount(t); n != 1 {+ t.Errorf("user count = %d, want 1", n)+ }+}++// Known gap, stated rather than papered over: nothing here proves Register *picks*+// CreateFirst in first-user mode. Swapping that line back to Create leaves every test+// above green, because the handler's pre-check already covers the sequential path and+// the difference only shows under a genuine interleaving — which cannot be produced+// deterministically through the handler. A concurrent version of this test would pass by+// luck as often as not, which is worse than an honest note.+//+// The handler's pre-check is a fast reject, not the guard. Two requests arriving at a+// fresh instance can both see an empty table and both be waved through — which is the+// exact race first-user exists to prevent — so the count is repeated inside the insert+// transaction. This calls the store directly because the interleaving cannot be produced+// through the handler: it is the state CreateFirst sees, not the order of two HTTP calls.+func TestCreateFirstRefusesOnceTheSlotIsTaken(t *testing.T) {+ setupTestDB(t)++ s := stores.New(db.DB)+ if _, err := s.User.CreateFirst("[email protected]", "hash"); err != nil {+ t.Fatalf("first CreateFirst: %v", err)+ }++ _, err := s.User.CreateFirst("[email protected]", "hash")+ if !errors.Is(err, stores.ErrRegistrationClosed) {+ t.Fatalf("second CreateFirst err = %v, want ErrRegistrationClosed", err)+ }+ if n := userCount(t); n != 1 {+ t.Errorf("user count = %d, want 1 — the race guard let a second account through", n)+ }+}++// A rejected CreateFirst must not leave a half-written account behind: the users insert+// and the user_settings insert share one transaction with the count.+func TestCreateFirstRollsBackCleanly(t *testing.T) {+ setupTestDB(t)++ s := stores.New(db.DB)+ if _, err := s.User.CreateFirst("[email protected]", "hash"); err != nil {+ t.Fatalf("first CreateFirst: %v", err)+ }+ if _, err := s.User.CreateFirst("[email protected]", "hash"); err == nil {+ t.Fatal("expected the second CreateFirst to fail")+ }++ var settings int+ if err := db.DB.QueryRow(`SELECT COUNT(*) FROM user_settings`).Scan(&settings); err != nil {+ t.Fatalf("count settings: %v", err)+ }+ if settings != 1 {+ t.Errorf("user_settings rows = %d, want 1", settings)+ }+}++func TestUserCount(t *testing.T) {+ setupTestDB(t)+ s := stores.New(db.DB)++ if n, err := s.User.Count(); err != nil || n != 0 {+ t.Fatalf("Count on an empty table = %d (err %v), want 0", n, err)+ }+ createTestUser(t)+ if n, err := s.User.Count(); err != nil || n != 1 {+ t.Errorf("Count = %d (err %v), want 1", n, err)+ }+}diff --git a/backend/controllers/server.go b/backend/controllers/server.goindex 6e87a32..82dbfa4 100644--- a/backend/controllers/server.go+++ b/backend/controllers/server.go@@ -1,6 +1,8 @@package controllersimport (+ "log"+"github.com/Cawlumm/lyftr-backend/config""github.com/Cawlumm/lyftr-backend/utils""github.com/gin-gonic/gin"@@ -11,9 +13,19 @@ import (// "test connection" behind the in-app server selector. It runs under the same// CORS policy as the rest of the API, so a successful probe honestly predicts// that authenticated requests from the same origin will be allowed too.+//+// registration_open lets the clients hide the "Create account" affordance instead of+// offering a link that 403s on submit. It is politeness, not enforcement — the check in+// Register is what actually closes the door — and only the boolean is exposed, never the+// mode, so a scanner learns nothing it could not learn by POSTing once.func (h *Handler) ServerInfo(c *gin.Context) {+ open, err := h.registrationOpen()+ if err != nil {+ log.Printf("server info: could not determine registration state, reporting closed: %v", err)+ }utils.OK(c, gin.H{- "name": "lyftr",- "version": config.C.Version,+ "name": "lyftr",+ "version": config.C.Version,+ "registration_open": open,})}diff --git a/backend/controllers/server_test.go b/backend/controllers/server_test.goindex c965ce0..a28ef0e 100644--- a/backend/controllers/server_test.go+++ b/backend/controllers/server_test.go@@ -8,7 +8,8 @@ import ()func TestServerInfo(t *testing.T) {- config.C = &config.Config{Version: "9.9.9"}+ setupTestDB(t)+ config.C.Version = "9.9.9"c, w := newContext(0, "GET", "/api/v1/info", nil)th.ServerInfo(c)@@ -27,4 +28,41 @@ func TestServerInfo(t *testing.T) {if data["version"] != "9.9.9" {t.Errorf("version = %v, want 9.9.9", data["version"])}+ if data["registration_open"] != true {+ t.Errorf("registration_open = %v, want true", data["registration_open"])+ }+}++// The flag both clients read to decide whether to offer "Create account". Under+// first-user it has to flip the moment the owner claims the instance — a static value+// per mode would keep advertising an open server that now 403s.+func TestServerInfoReportsRegistrationState(t *testing.T) {+ infoOpen := func(t *testing.T) any {+ t.Helper()+ c, w := newContext(0, "GET", "/api/v1/info", nil)+ th.ServerInfo(c)+ data := decodeResponse(t, w)["data"].(map[string]any)+ return data["registration_open"]+ }++ t.Run("closed", func(t *testing.T) {+ setupTestDB(t)+ setRegistration(t, config.RegistrationClosed)+ if got := infoOpen(t); got != false {+ t.Errorf("registration_open = %v, want false", got)+ }+ })++ t.Run("first-user flips once claimed", func(t *testing.T) {+ setupTestDB(t)+ setRegistration(t, config.RegistrationFirstUser)++ if got := infoOpen(t); got != true {+ t.Fatalf("registration_open on an empty instance = %v, want true", got)+ }+ createTestUser(t)+ if got := infoOpen(t); got != false {+ t.Errorf("registration_open after the first account = %v, want false", got)+ }+ })}diff --git a/backend/controllers/sqlite_lock_test.go b/backend/controllers/sqlite_lock_test.goindex 1ae8284..8e1e1f3 100644--- a/backend/controllers/sqlite_lock_test.go+++ b/backend/controllers/sqlite_lock_test.go@@ -6,6 +6,7 @@ import ("path/filepath""testing"+ "github.com/Cawlumm/lyftr-backend/config""github.com/Cawlumm/lyftr-backend/db""github.com/Cawlumm/lyftr-backend/stores""github.com/Cawlumm/lyftr-backend/utils"@@ -17,6 +18,7 @@ import (// also rebuilds the DI handler (th) bound to this DB.func setupFileDB(t *testing.T) string {t.Helper()+ setRegistration(t, config.RegistrationOpen)path := filepath.Join(t.TempDir(), "lock.db")var err errordb.DB, err = sql.Open("sqlite", path+"?_pragma=busy_timeout(0)")diff --git a/backend/controllers/testhelper_test.go b/backend/controllers/testhelper_test.goindex da787a4..7b14443 100644--- a/backend/controllers/testhelper_test.go+++ b/backend/controllers/testhelper_test.go@@ -10,6 +10,7 @@ import ("net/http/httptest""testing"+ "github.com/Cawlumm/lyftr-backend/config""github.com/Cawlumm/lyftr-backend/db""github.com/Cawlumm/lyftr-backend/stores""github.com/gin-gonic/gin"@@ -20,8 +21,20 @@ import (// the fresh per-test db.DB.var th *Handler+// setRegistration points config.C at a mode for the duration of one test and restores+// whatever was there before. Register and ServerInfo both read this global, so without a+// deterministic value per test the result depends on which test ran first — measured:+// TestRegister_lockedDBReturns503 passes in the full suite and nil-panics when run alone.+func setRegistration(t *testing.T, mode string) {+ t.Helper()+ prev := config.C+ config.C = &config.Config{Registration: mode, Version: "test"}+ t.Cleanup(func() { config.C = prev })+}+func setupTestDB(t *testing.T) {t.Helper()+ setRegistration(t, config.RegistrationOpen)var err error// modernc ignores the mattn-style _foreign_keys=on; use the _pragma form so the// harness actually enforces foreign keys, matching the production DSN.diff --git a/backend/main.go b/backend/main.goindex 1b2f391..ee5b6ef 100644--- a/backend/main.go+++ b/backend/main.go@@ -15,6 +15,33 @@ import ("github.com/gin-gonic/gin")+// warnIfUnclaimed says out loud, on every start, that first-user mode currently has the+// door open.+//+// first-user keys on the users table being empty, and that table lives on the data+// volume — so a volume that failed to mount, or a `docker compose up` from the wrong+// directory (which silently creates an empty ./data), is indistinguishable from a fresh+// install and re-opens registration. Immich shipped the same shape and had exactly this+// reported: immich-app/immich#24479, a reboot before the disk was mounted let anyone+// register as admin.+//+// Nothing stored in the database can guard against it, because any marker we wrote would+// be missing for the same reason. Only REGISTRATION=closed survives a missing volume,+// which is why the docs treat first-user as a setup mode rather than a resting state.+// What is left is to make the open door visible in the logs instead of silent.+func warnIfUnclaimed() {+ if config.C.Registration != config.RegistrationFirstUser {+ return+ }+ var n int+ if err := db.DB.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n); err != nil || n > 0 {+ return+ }+ log.Print("NOTICE: REGISTRATION=first-user and no accounts exist yet — registration is " ++ "OPEN until the first one is created. If this instance already had an account, its " ++ "data volume is not mounted: stop it before someone else claims it.")+}+func main() {showVersion := flag.Bool("version", false, "print the build version and exit")flag.Parse()@@ -25,9 +52,19 @@ func main() {config.Load()db.Connect()- seed.DemoUser(db.DB)+ warnIfUnclaimed()+ // The demo account's credentials are published, so it is not something a self-hosted+ // instance should get by default — only the public demo and local development ask for+ // it. The exercise library is not demo data and always seeds.+ if config.C.DemoMode {+ seed.DemoUser(db.DB)+ } else {+ seed.WarnLeftoverDemoUser(db.DB)+ }seed.Exercises(db.DB)- go seed.DemoData(db.DB)+ if config.C.DemoMode {+ go seed.DemoData(db.DB)+ }if config.C.Env == "production" {gin.SetMode(gin.ReleaseMode)diff --git a/backend/seed/demo_data.go b/backend/seed/demo_data.goindex 94aad24..fccd1f2 100644--- a/backend/seed/demo_data.go+++ b/backend/seed/demo_data.go@@ -97,7 +97,7 @@ func DemoData(db *sql.DB) {}var userID int64- if err := db.QueryRow(`SELECT id FROM users WHERE email = ?`, "[email protected]").Scan(&userID); err != nil {+ if err := db.QueryRow(`SELECT id FROM users WHERE email = ?`, DemoEmail).Scan(&userID); err != nil {log.Printf("seed: demo user not found: %v", err)return}diff --git a/backend/seed/users.go b/backend/seed/users.goindex 48991a4..1bf8e52 100644--- a/backend/seed/users.go+++ b/backend/seed/users.go@@ -7,9 +7,14 @@ import ("github.com/Cawlumm/lyftr-backend/utils")+// DemoEmail is the seeded demo account. Its password is published in the README, so+// nothing may create it unless DEMO_MODE is on — see WarnLeftoverDemoUser for the+// instances that already have one.+const DemoEmail = "[email protected]"+func DemoUser(db *sql.DB) {var count int- db.QueryRow(`SELECT COUNT(*) FROM users WHERE email = ?`, "[email protected]").Scan(&count)+ db.QueryRow(`SELECT COUNT(*) FROM users WHERE email = ?`, DemoEmail).Scan(&count)if count > 0 {return}@@ -20,7 +25,7 @@ func DemoUser(db *sql.DB) {return}- res, err := db.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, "[email protected]", hash)+ res, err := db.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, DemoEmail, hash)if err != nil {log.Printf("seed: failed to create demo user: %v", err)return@@ -30,3 +35,21 @@ func DemoUser(db *sql.DB) {db.Exec(`INSERT INTO user_settings (user_id) VALUES (?)`, userID)log.Println("seed: demo user created ([email protected] / password123)")}++// WarnLeftoverDemoUser flags a demo account on an instance that is no longer seeding+// one. Until DEMO_MODE existed every install got this account, so upgrading does not+// remove the exposure it already has — and closing registration while a published+// password still works would be a false sense of security.+//+// It warns rather than deleting: the row may by now hold real workouts, and silently+// dropping someone's data on upgrade is not a trade this can make for them.+func WarnLeftoverDemoUser(db *sql.DB) {+ var count int+ if err := db.QueryRow(`SELECT COUNT(*) FROM users WHERE email = ?`, DemoEmail).Scan(&count); err != nil || count == 0 {+ return+ }+ log.Printf("WARNING: this instance still has the %s account from an earlier version, and "++ "its password is published in the docs. Anyone who can reach this server can sign in as "++ "it. Delete it from Settings → Delete account while signed in as that user, or set "++ "DEMO_MODE=true if you meant to keep it.", DemoEmail)+}diff --git a/backend/stores/user.go b/backend/stores/user.goindex 8a61a59..436ecda 100644--- a/backend/stores/user.go+++ b/backend/stores/user.go@@ -2,6 +2,7 @@ package storesimport ("database/sql"+ "errors""github.com/Cawlumm/lyftr-backend/models")@@ -75,23 +76,56 @@ func (s *UserStore) UpsertSettings(uid int64, req models.UpdateSettingsRequest)return st, nil}+// ErrRegistrationClosed means the instance is in first-user mode and the slot was+// taken — by the owner, or by whoever raced them to it.+var ErrRegistrationClosed = errors.New("registration is closed")++// Count returns the number of accounts. Drives first-user mode and the+// registration_open flag on /info.+func (s *UserStore) Count() (int, error) {+ var n int+ err := s.db.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n)+ return n, err+}+// Create inserts a user and their default settings atomically (one transaction —// fixes the previous non-transactional gap). A duplicate email surfaces as a// UNIQUE violation for the controller to map to 409.func (s *UserStore) Create(email, hash string) (int64, error) {return inTx(s.db, func(tx *sql.Tx) (int64, error) {- res, err := tx.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, email, hash)- if err != nil {+ return createUserTx(tx, email, hash)+ })+}++// CreateFirst is Create for first-user mode: it re-counts inside the transaction and+// refuses if anyone got there first. The controller's pre-check is only a fast reject —+// on a fresh public instance a scraper and the owner can both observe an empty table+// and both be allowed through, which is the exact race this mode exists to prevent.+func (s *UserStore) CreateFirst(email, hash string) (int64, error) {+ return inTx(s.db, func(tx *sql.Tx) (int64, error) {+ var n int+ if err := tx.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n); err != nil {return 0, err}- uid, _ := res.LastInsertId()- if _, err := tx.Exec(`INSERT INTO user_settings (user_id) VALUES (?)`, uid); err != nil {- return 0, err+ if n > 0 {+ return 0, ErrRegistrationClosed}- return uid, nil+ return createUserTx(tx, email, hash)})}+func createUserTx(tx *sql.Tx, email, hash string) (int64, error) {+ res, err := tx.Exec(`INSERT INTO users (email, password_hash) VALUES (?, ?)`, email, hash)+ if err != nil {+ return 0, err+ }+ uid, _ := res.LastInsertId()+ if _, err := tx.Exec(`INSERT INTO user_settings (user_id) VALUES (?)`, uid); err != nil {+ return 0, err+ }+ return uid, nil+}+// Delete removes the user; child rows go via ON DELETE CASCADE (foreign_keys=on).func (s *UserStore) Delete(uid int64) error {_, err := s.db.Exec(`DELETE FROM users WHERE id = ?`, uid)diff --git a/backend/utils/response.go b/backend/utils/response.goindex 7e950dc..18d5686 100644--- a/backend/utils/response.go+++ b/backend/utils/response.go@@ -22,6 +22,10 @@ func Unauthorized(c *gin.Context, msg string) {c.JSON(http.StatusUnauthorized, gin.H{"error": msg})}+func Forbidden(c *gin.Context, msg string) {+ c.JSON(http.StatusForbidden, gin.H{"error": msg})+}+func NotFound(c *gin.Context, msg string) {c.JSON(http.StatusNotFound, gin.H{"error": msg})}diff --git a/docker-compose.yml b/docker-compose.ymlindex 448010c..d6f6d95 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -14,6 +14,8 @@ services:- CORS_ORIGIN=${CORS_ORIGIN:-http://localhost}- DB_TYPE=sqlite- DB_PATH=/app/data/lyftr.db+ - REGISTRATION=${REGISTRATION:-open}+ - DEMO_MODE=${DEMO_MODE:-false}expose:- "3000"healthcheck:diff --git a/fly.toml b/fly.tomlindex 7fba3f8..db41e47 100644--- a/fly.toml+++ b/fly.toml@@ -14,6 +14,8 @@ primary_region = "fra"PORT = "3000"DB_PATH = "/app/data/lyftr.db"CORS_ORIGIN = "https://lyftr-demo.fly.dev"+ # Without this the demo deploys with no account to log into.+ DEMO_MODE = "true"# JWT_SECRET must be set as a secret:# fly secrets set JWT_SECRET=$(openssl rand -hex 32)diff --git a/fly/SETUP.md b/fly/SETUP.mdindex 3be5f5b..f018498 100644--- a/fly/SETUP.md+++ b/fly/SETUP.md@@ -39,7 +39,9 @@ fly deploy --app lyftr-demoThe first deploy will:- Start the Go backend-- Seed the demo user (`[email protected]` / `password123`)+- Seed the demo user (`[email protected]` / `password123`) — this happens because+ `fly.toml` sets `DEMO_MODE = "true"`. It is off by default everywhere else, and+ without it the demo deploys with no account to log into- Begin seeding 800+ exercises async (takes ~30s)- `DemoData` goroutine waits for exercises then seeds 8 weeks of workouts,90 days of weight logs, and 7 days of food logs automaticallydiff --git a/mobile/README.md b/mobile/README.mdindex 0292190..55ceddc 100644--- a/mobile/README.md+++ b/mobile/README.md@@ -33,7 +33,8 @@ Mac only) / `a` (Android emulator).The **Server URL** field in the Settings tab configures the backend origin (validated via`GET /api/v1/info`). Leave blank for the default. For the VM dev backend use the LAN IP orthe Tailscale URL, e.g. `https://claude-code.tail2b1098.ts.net:3000`. Demo login:-`[email protected]` / `password123`.+`[email protected]` / `password123` — present on a dev backend and on the hosted demo, but+not on a production instance unless it sets `DEMO_MODE=true`.## Native networking config`network_security_config.xml` is an Androiddiff --git a/mobile/app/(auth)/login.tsx b/mobile/app/(auth)/login.tsxindex 0c66c67..8010679 100644--- a/mobile/app/(auth)/login.tsx+++ b/mobile/app/(auth)/login.tsx@@ -3,7 +3,8 @@ import { Text, View, Linking } from 'react-native'import { Link } from 'expo-router'import { AuthScaffold } from '../../src/components/AuthScaffold'import { IconInput, GradientButton, SecondaryButton, AuthDivider, AuthError, ServerRow, Footer } from '../../src/components/authui'-import { useAuthStore } from '../../src/lib/lyftr'+import { registrationOpen } from '@lyftr/shared'+import { useAuthStore, useServerInfo } from '../../src/lib/lyftr'import { useTheme } from '../../src/theme/useTheme'// Public hosted demo (Fly) — the "Try demo account" button opens it in the browser.@@ -22,6 +23,7 @@ export default function Login() {const error = useAuthStore((s) => s.error)const clearError = useAuthStore((s) => s.clearError)const { accent, colors } = useTheme()+ const isOpen = registrationOpen(useServerInfo())// Clear both the client-side and the server error when a field is edited.const onChange = (setter: (t: string) => void) => (t: string) => {@@ -67,13 +69,22 @@ export default function Login() {<GradientButton title="Sign in" onPress={submit} loading={loading} /><AuthDivider /><SecondaryButton title="Try demo account" hint="no sign-up" onPress={demo} />+ {/* A closed server says so instead of offering a link that 403s on submit — but it+ does still say so, rather than leaving someone who came to sign up hunting for a+ button that is not there (mastodon/mastodon#21556). */}<Footer>- <View style={{ flexDirection: 'row', gap: 5 }}>- <Text style={{ color: colors.txSecondary, fontFamily: 'PlusJakartaSans_600SemiBold', fontSize: 14 }}>New here?</Text>- <Link href="/register" style={{ color: accent, fontFamily: 'PlusJakartaSans_800ExtraBold', fontSize: 14 }}>- Create account- </Link>- </View>+ {isOpen ? (+ <View style={{ flexDirection: 'row', gap: 5 }}>+ <Text style={{ color: colors.txSecondary, fontFamily: 'PlusJakartaSans_600SemiBold', fontSize: 14 }}>New here?</Text>+ <Link href="/register" style={{ color: accent, fontFamily: 'PlusJakartaSans_800ExtraBold', fontSize: 14 }}>+ Create account+ </Link>+ </View>+ ) : (+ <Text style={{ color: colors.txSecondary, fontFamily: 'PlusJakartaSans_600SemiBold', fontSize: 14 }}>+ This server is not accepting new accounts.+ </Text>+ )}</Footer></AuthScaffold>)diff --git a/mobile/app/(auth)/register.tsx b/mobile/app/(auth)/register.tsxindex 6efe14e..4ed3472 100644--- a/mobile/app/(auth)/register.tsx+++ b/mobile/app/(auth)/register.tsx@@ -3,7 +3,8 @@ import { Text, View } from 'react-native'import { Link } from 'expo-router'import { AuthScaffold } from '../../src/components/AuthScaffold'import { IconInput, GradientButton, AuthError, ServerRow, Footer } from '../../src/components/authui'-import { useAuthStore } from '../../src/lib/lyftr'+import { registrationOpen } from '@lyftr/shared'+import { useAuthStore, useServerInfo } from '../../src/lib/lyftr'import { useTheme } from '../../src/theme/useTheme'// Same intent as the web's <input type=email required>: a lightweight shape check,@@ -39,6 +40,34 @@ export default function Register() {}const shownError = localError || error+ const isOpen = registrationOpen(useServerInfo())++ // A closed server explains itself instead of letting someone fill in three fields and+ // meet a 403 on submit. ServerRow stays: they may just be pointed at the wrong server.+ if (!isOpen) {+ return (+ <AuthScaffold heading="Registration closed" subtitle="This server is not accepting new accounts.">+ <ServerRow />+ <Text+ style={{+ color: colors.txSecondary,+ fontFamily: 'PlusJakartaSans_600SemiBold',+ fontSize: 14,+ lineHeight: 21,+ marginTop: 8,+ }}+ >+ The owner of this Lyftr instance has turned off new signups. If you should have an+ account here, ask them to create one for you.+ </Text>+ <Footer>+ <Link href="/login" style={{ color: accent, fontFamily: 'PlusJakartaSans_800ExtraBold', fontSize: 14 }}>+ Back to sign in+ </Link>+ </Footer>+ </AuthScaffold>+ )+ }return (<AuthScaffold heading="Create account" subtitle="Start your training log.">diff --git a/mobile/src/lib/lyftr.ts b/mobile/src/lib/lyftr.tsindex dc41ccc..78438a5 100644--- a/mobile/src/lib/lyftr.ts+++ b/mobile/src/lib/lyftr.ts@@ -10,6 +10,8 @@ import {createSettingsStore,createThemeStore,createWorkoutSession,+ testServerConnection,+ useServerInfoFor,} from '@lyftr/shared'import { storage } from './storage'@@ -41,3 +43,8 @@ export const useWorkoutSession = createWorkoutSession(storage)// Rest-timer state derived from the session store above. Logic in @lyftr/shared.export const useRestTimer = createUseRestTimer(useWorkoutSession)++// The selected server's /info — version and whether it is taking new accounts. Same+// hook and same cache the web uses; only the store binding differs.+export const useServerInfo = () =>+ useServerInfoFor(useServerStore((s) => s.serverUrl), testServerConnection)diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.tsindex 3d2f8e5..8ffecdb 100644--- a/packages/shared/src/client.ts+++ b/packages/shared/src/client.ts@@ -13,6 +13,9 @@ export const apiUrl = (origin = '') => `${origin}${API_BASE_PATH}`export interface ServerInfo {name: stringversion: string+ // Optional: a backend older than the REGISTRATION feature omits it. Read it through+ // registrationOpen() so "absent" means open rather than closed.+ registration_open?: boolean}export interface ClientOptions {diff --git a/packages/shared/src/hooks/useServerInfo.test.ts b/packages/shared/src/hooks/useServerInfo.test.tsnew file mode 100644index 0000000..82f43cc--- /dev/null+++ b/packages/shared/src/hooks/useServerInfo.test.ts@@ -0,0 +1,24 @@+import { registrationOpen } from './useServerInfo'++// The one rule worth pinning: which values hide the "Create account" affordance.+// Getting the absent case backwards would hide signup on every server older than the+// REGISTRATION feature — a silent, total break of the only way to make an account,+// against backends the user cannot upgrade.+describe('registrationOpen', () => {+ it('is open when the server says so', () => {+ expect(registrationOpen({ name: 'lyftr', version: '1.0.0', registration_open: true })).toBe(true)+ })++ it('is closed only on an explicit false', () => {+ expect(registrationOpen({ name: 'lyftr', version: '1.0.0', registration_open: false })).toBe(false)+ })++ it('is open when the field is absent — a backend older than this feature', () => {+ expect(registrationOpen({ name: 'lyftr', version: '0.1.0' })).toBe(true)+ })++ it('is open while the probe is still in flight or the server is unreachable', () => {+ expect(registrationOpen(null)).toBe(true)+ expect(registrationOpen(undefined)).toBe(true)+ })+})diff --git a/packages/shared/src/hooks/useServerInfo.ts b/packages/shared/src/hooks/useServerInfo.tsnew file mode 100644index 0000000..9a6e9d1--- /dev/null+++ b/packages/shared/src/hooks/useServerInfo.ts@@ -0,0 +1,59 @@+import { useEffect, useState } from 'react'+import type { ServerInfo } from '../client'++type Probe = (+ base: string,+) => Promise<{ ok: true; info: ServerInfo } | { ok: false; message: string }>++// Cache keyed by server URL, module-level so it survives remounts. Both apps share it+// because both have exactly one server selected at a time.+const cache = new Map<string, ServerInfo>()++// Fetches a backend's /info once per server URL and caches it, so the footer, Settings+// and the auth screens can show a live version and registration state. Returns null+// while loading or when the server is unreachable — callers render a graceful fallback+// rather than a stuck "Loading" (the failure mode some apps hit by hard-depending on+// the fetch).+//+// The probe is injected rather than imported: it keeps this hook free of the platform's+// API-client wiring, and lets each app's tests substitute one — same reason+// useServerList takes its fetcher.+//+// The cached copy can go stale within a session. Under REGISTRATION=first-user the+// server flips to closed the moment the owner registers, while this still says open, so+// the "Create account" link can linger until reload. That is acceptable precisely+// because the flag is advisory: registering navigates away anyway, and the server+// rejects a second signup regardless of what the UI offered.+export function useServerInfoFor(base: string, probe: Probe): ServerInfo | null {+ const [info, setInfo] = useState<ServerInfo | null>(() => cache.get(base) ?? null)++ useEffect(() => {+ const cached = cache.get(base)+ if (cached) {+ setInfo(cached)+ return+ }+ let active = true+ probe(base).then((result) => {+ if (active && result.ok) {+ cache.set(base, result.info)+ setInfo(result.info)+ }+ })+ return () => {+ active = false+ }+ // probe is a module-level function in both apps; re-running on identity changes+ // would refetch on every render for no benefit.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [base])++ return info+}++// Whether to offer a "Create account" affordance. Anything other than an explicit+// false means yes — a backend older than this feature omits the field entirely, and a+// new client must not hide a working signup link against an old server.+export function registrationOpen(info: ServerInfo | null | undefined): boolean {+ return info?.registration_open !== false+}diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 9a15d68..fd8c8ae 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -27,6 +27,7 @@ export * from './hooks/useNumericText'export * from './hooks/useElapsedSeconds'export * from './hooks/useRestTimer'export * from './hooks/useServerList'+export * from './hooks/useServerInfo'export * from './utils/dateUtils'export * from './utils/programUtils'export * from './stores/auth'diff --git a/site/src/content/docs/configuration.md b/site/src/content/docs/configuration.mdindex 24afcaa..86e793e 100644--- a/site/src/content/docs/configuration.md+++ b/site/src/content/docs/configuration.md@@ -13,6 +13,75 @@ All configuration lives in a `.env` file at the project root.| `CORS_ORIGIN` | `http://localhost` | Comma-separated allow-list of client origins. Use `*` to allow any (the API is Bearer-token based, no cookies). || `PORT` | `80` | Host port for the web interface. || `BACKEND_ORIGIN` | `backend:3000` | Docker **service name**:port the frontend proxies `/api` to — not a host IP. Only change the port, to match a custom backend `PORT`. |+| `REGISTRATION` | `open` | Who may create an account: `open`, `first-user`, or `closed`. See below. |+| `DEMO_MODE` | `false` | Seeds the demo account and sample data. Leave off — its password is public. |++## Locking down registration++By default `/api/v1/auth/register` accepts anyone. That is fine on a LAN and wrong the moment+your instance has a public hostname, which is what the [reverse proxy](/https/) guide gets you.+Set `REGISTRATION` in your `.env` and restart:++```bash+REGISTRATION=first-user+```++```bash+docker compose up -d # no rebuild — it is read at startup+```++| Value | Behaviour |+|-------|-----------|+| `open` | Anyone can sign up. The default, and what every version before this one did. |+| `first-user` | Open only while no account exists. The first person to register claims the instance; everyone after gets a 403. |+| `closed` | Nobody can register. Where you should end up. |++**`first-user` is a setup mode, not a resting state.** Use it for a fresh install — a plain+on/off switch would make you choose between starting open, and racing whatever scanner finds+your hostname, and starting closed, unable to create your own account at all. Then **switch to+`closed` once you have signed up**, for the reason below.++:::caution[Why `first-user` is not somewhere to stay]+`first-user` decides by asking whether the users table is empty — and that table lives on your+data volume. If the volume ever fails to mount, or you run `docker compose up` from a different+directory (which silently creates a new, empty `./data`), the instance looks brand new and+registration opens again. Immich shipped the same design and had exactly this reported: a+reboot before the disk was mounted let anyone register as the admin+([immich-app/immich#24479](https://github.com/immich-app/immich/issues/24479)).++No setting stored *in* the database can protect against this, because it would be missing for+the same reason. `REGISTRATION=closed` lives in your `.env`, so it survives.++While `first-user` is on and no account exists, the backend says so on every start:++```+NOTICE: REGISTRATION=first-user and no accounts exist yet — registration is OPEN until+the first one is created. If this instance already had an account, its data volume is+not mounted: stop it before someone else claims it.+```++If you see that on an instance you have already signed up on, your data is not where the+container is looking. Stop it before fixing the mount.+:::++A typo is a startup failure, not a fallback: `REGISTRATION=frst-user` refuses to boot rather than+quietly leaving you wide open. Check `docker compose logs backend` if the container will not start.++This is enforced by the API, not the interface. The apps also hide the "Create account" link when+the server reports registration closed, but that is politeness — the 403 is the lock.++## The demo account++Every version before this one seeded `[email protected]` with a password published in this+documentation, on **every** install. That account is now behind `DEMO_MODE`, which is off unless+you ask for it.++If you are upgrading, the account you already have is not deleted — deleting it might take real+workouts with it. The backend logs a warning at startup while it exists. To remove it: sign in as+`[email protected]`, then **Settings → Delete account**.++Turning registration off does nothing about this: a published password is a working login whatever+`REGISTRATION` says.## The `BACKEND_ORIGIN` gotchadiff --git a/site/src/content/docs/getting-started.md b/site/src/content/docs/getting-started.mdindex 4706022..b0adea2 100644--- a/site/src/content/docs/getting-started.md+++ b/site/src/content/docs/getting-started.md@@ -19,6 +19,11 @@ It's pre-loaded with 8 weeks of push/pull/legs workouts, 90 days of weight logs,every page has data to explore. It's a shared instance that **resets every hour**, so feel free tochange anything — or register your own throwaway account.+Those credentials are for the hosted demo only. Your own install does **not** come with that+account — see [`DEMO_MODE`](../configuration/#the-demo-account) if you want the sample data+locally, and [`REGISTRATION`](../configuration/#locking-down-registration) to control who may sign+up on it.+## Get the app- **Android** — download the latest signed APK from thediff --git a/site/src/content/docs/self-hosting.md b/site/src/content/docs/self-hosting.mdindex 26118ee..c7526fa 100644--- a/site/src/content/docs/self-hosting.md+++ b/site/src/content/docs/self-hosting.md@@ -30,6 +30,15 @@ The compose file references prebuilt images on Docker Hub. Running `docker compothem so nothing is built locally — you don't need the source code, just the compose file and `.env`.:::+:::caution[Close the door behind you]+Registration is open by default, so anyone who can reach your instance can create an account.+That is fine on a LAN and wrong once it has a public hostname. Set `REGISTRATION=first-user`+in `.env` **before** the first `up -d` to claim the instance with your own signup, then move+to `REGISTRATION=closed` once you have — see+[Locking down registration](../configuration/#locking-down-registration) for why the second+step matters.+:::+:::tip[Exercise library]On first startup Lyftr seeds **800+ exercises** from[free-exercise-db](https://github.com/yuhonas/free-exercise-db) in the background — no API key, no@@ -50,7 +59,7 @@ Single SQLite file, minimal RAM, no external services required.## Next steps-- **[Configuration](../configuration/)** — environment variables (`JWT_SECRET`, `CORS_ORIGIN`, ports).+- **[Configuration](../configuration/)** — environment variables (`JWT_SECRET`, `CORS_ORIGIN`, ports, `REGISTRATION`).- **[HTTPS & Reverse Proxy](../https/)** — expose it publicly with automatic TLS (and to use the mobile app).- **[Backups & Updates](../backups/)** — protect your data and upgrade safely.- **[Mobile App](../mobile/)** — install the Android app and point it at your server.diff --git a/web/e2e/auth.spec.ts b/web/e2e/auth.spec.tsindex c7021d4..dbd7613 100644--- a/web/e2e/auth.spec.ts+++ b/web/e2e/auth.spec.ts@@ -25,7 +25,10 @@ test('wrong password shows an error and stays on the login page (no reload)', as// password", not trigger a token-refresh redirect that reloads the page and// wipes the message.await page.goto('/login')- await page.getByPlaceholder('[email protected]').fill('[email protected]')+ // Any address works — the server answers "invalid email or password" whether the+ // account is missing or the password is wrong, and naming a seeded account here+ // implied the suite needed one.+ await page.getByPlaceholder('[email protected]').fill('[email protected]')await page.locator('#password').fill('definitely-the-wrong-password')await page.getByRole('button', { name: /sign in/i }).click()await expect(page.locator('.alert-error')).toBeVisible()diff --git a/web/e2e/globalSetup.ts b/web/e2e/globalSetup.tsnew file mode 100644index 0000000..eb3559d--- /dev/null+++ b/web/e2e/globalSetup.ts@@ -0,0 +1,56 @@+import { request } from '@playwright/test'+import { API_BASE } from './config'+import { recordCreatedUser } from './userRegistry'++// Blocks until the stack can actually serve the suite: the API answers, and the+// exercise library has finished its background seed (specs pick exercises, and an+// empty library fails them in ways that read like product bugs).+//+// It checks both by making its own account, which is the point. CI used to gate on+// logging in as [email protected], so the whole suite silently depended on a seeded+// demo account — and now that DEMO_MODE is off by default, that gate would just hang+// for 90s and read like a flake. Nothing here assumes any account exists beforehand.+// The throwaway is recorded so globalTeardown deletes it with the rest.+const READY_TIMEOUT_MS = 120_000+const POLL_MS = 2_000++async function poll(label: string, check: () => Promise<boolean>): Promise<void> {+ const deadline = Date.now() + READY_TIMEOUT_MS+ for (;;) {+ if (await check().catch(() => false)) return+ if (Date.now() > deadline) {+ throw new Error(`[globalSetup] timed out after ${READY_TIMEOUT_MS / 1000}s waiting for ${label}`)+ }+ await new Promise(r => setTimeout(r, POLL_MS))+ }+}++export default async function globalSetup(): Promise<void> {+ const api = await request.newContext({ ignoreHTTPSErrors: true })+ try {+ await poll('the API to answer', async () => (await api.get(`${API_BASE}/info`)).ok())++ const email = `e2e-ready-${Date.now()}@lyftr.local`+ const res = await api.post(`${API_BASE}/auth/register`, {+ data: { email, password: 'password123' },+ })+ if (!res.ok()) {+ throw new Error(+ `[globalSetup] could not register a probe account (${res.status()}). ` ++ `If this server runs REGISTRATION=closed or first-user, the suite cannot run against it.`,+ )+ }+ const token = (await res.json()).data.token+ recordCreatedUser(token)++ await poll('the exercise library to seed', async () => {+ const list = await api.get(`${API_BASE}/exercises?limit=1`, {+ headers: { Authorization: `Bearer ${token}` },+ })+ if (!list.ok()) return false+ return ((await list.json()).data ?? []).length > 0+ })+ } finally {+ await api.dispose()+ }+}diff --git a/web/playwright.config.ts b/web/playwright.config.tsindex d467bb4..dbe0388 100644--- a/web/playwright.config.ts+++ b/web/playwright.config.ts@@ -20,6 +20,10 @@ const baseURL = process.env.BASE_URLexport default defineConfig({testDir: './e2e',+ // Waits for the API and the exercise seed by registering its own probe account —+ // the suite depends on no pre-existing user, so it runs against a stack with+ // DEMO_MODE off (the production default).+ globalSetup: './e2e/globalSetup.ts',// Deletes every e2e account created during the run (recorded in userRegistry),// guaranteeing the DB is left as it started — no orphaned test users locally.globalTeardown: './e2e/globalTeardown.ts',diff --git a/web/src/hooks/useServerInfo.ts b/web/src/hooks/useServerInfo.tsindex 15f44b6..df87bff 100644--- a/web/src/hooks/useServerInfo.ts+++ b/web/src/hooks/useServerInfo.ts@@ -1,32 +1,10 @@-import { useEffect, useState } from 'react'+import { useServerInfoFor } from '@lyftr/shared'import { testServerConnection, type ServerInfo } from '../services/api'import { useServerStore } from '../stores/server'-// Fetches the connected backend's /info once per server URL and caches it, so the-// footer and Settings can show a live version. Returns null while loading or when-// the server is unreachable — callers render a graceful fallback rather than a-// stuck "Loading" (the failure mode some apps hit by hard-depending on the fetch).-const cache = new Map<string, ServerInfo>()-+// Binding only — the fetch, the cache and the staleness note live in @lyftr/shared so+// mobile's login screen reads the same registration state from the same code.export function useServerInfo(): ServerInfo | null {const base = useServerStore(s => s.serverUrl)- const [info, setInfo] = useState<ServerInfo | null>(() => cache.get(base) ?? null)-- useEffect(() => {- const cached = cache.get(base)- if (cached) {- setInfo(cached)- return- }- let active = true- testServerConnection(base).then(result => {- if (active && result.ok) {- cache.set(base, result.info)- setInfo(result.info)- }- })- return () => { active = false }- }, [base])-- return info+ return useServerInfoFor(base, testServerConnection)}diff --git a/web/src/pages/Login.tsx b/web/src/pages/Login.tsxindex 4d912c1..fb9f003 100644--- a/web/src/pages/Login.tsx+++ b/web/src/pages/Login.tsx@@ -4,7 +4,7 @@ import { AlertCircle, Zap, Dumbbell, Apple, TrendingUp, LogIn } from 'lucide-reaimport { useAuthStore } from '../stores/auth'import { apiErrorMessage } from '../services/api'import { useServerInfo } from '../hooks/useServerInfo'-import { formatVersion } from '@lyftr/shared'+import { formatVersion, registrationOpen } from '@lyftr/shared'import Logo from '../components/Logo'import ServerSettings from '../components/ServerSettings'@@ -173,12 +173,17 @@ export default function Login() {{isLoading ? 'Signing in…' : 'Sign in'}</button>- {/* Divider */}- <div className="relative flex items-center my-6">- <div className="flex-1 h-px bg-surface-border" />- <span className="px-3 text-xs text-tx-muted uppercase tracking-wider">or</span>- <div className="flex-1 h-px bg-surface-border" />- </div>+ {/* Divider — only when something follows it that is genuinely an alternative+ way in. In a production build the demo button is absent, so on a server+ with registration closed there is nothing below but a statement, and an+ "or" heading it reads like the start of an option that never arrives. */}+ {(import.meta.env.DEV || registrationOpen(serverInfo)) && (+ <div className="relative flex items-center my-6">+ <div className="flex-1 h-px bg-surface-border" />+ <span className="px-3 text-xs text-tx-muted uppercase tracking-wider">or</span>+ <div className="flex-1 h-px bg-surface-border" />+ </div>+ )}{/* Demo button — dev only */}{import.meta.env.DEV && (@@ -194,16 +199,25 @@ export default function Login() {)}</form>- {/* Sign up link */}- <p className="mt-8 text-center text-sm text-tx-muted">- New here?{' '}- <Link- to="/register"- className="text-brand-400 font-medium hover:text-brand-300 transition-colors"- >- Create account- </Link>- </p>+ {/* A closed instance says so rather than offering a link that 403s on submit —+ but it does still say so. Removing the signup path without a trace sends+ someone who came here to sign up hunting for a button that is not there+ (mastodon/mastodon#21556); a line of text answers them where they are. */}+ {registrationOpen(serverInfo) ? (+ <p className="mt-8 text-center text-sm text-tx-muted">+ New here?{' '}+ <Link+ to="/register"+ className="text-brand-400 font-medium hover:text-brand-300 transition-colors"+ >+ Create account+ </Link>+ </p>+ ) : (+ <p className="mt-8 text-center text-sm text-tx-muted">+ This server is not accepting new accounts.+ </p>+ )}</div></div></div>diff --git a/web/src/pages/Register.tsx b/web/src/pages/Register.tsxindex 9281e67..ab34880 100644--- a/web/src/pages/Register.tsx+++ b/web/src/pages/Register.tsx@@ -1,10 +1,10 @@import { useState } from 'react'import { useNavigate, Link } from 'react-router-dom'-import { AlertCircle, Dumbbell, Apple, TrendingUp, UserPlus } from 'lucide-react'+import { AlertCircle, Dumbbell, Apple, TrendingUp, UserPlus, Lock } from 'lucide-react'import { useAuthStore } from '../stores/auth'import { apiErrorMessage } from '../services/api'import { useServerInfo } from '../hooks/useServerInfo'-import { formatVersion } from '@lyftr/shared'+import { formatVersion, registrationOpen } from '@lyftr/shared'import Logo from '../components/Logo'import ServerSettings from '../components/ServerSettings'@@ -12,6 +12,7 @@ export default function Register() {const navigate = useNavigate()const { register } = useAuthStore()const serverInfo = useServerInfo()+ const isOpen = registrationOpen(serverInfo)const [email, setEmail] = useState('')const [password, setPassword] = useState('')@@ -102,16 +103,36 @@ export default function Register() {{/* Heading */}<div className="mb-8"><h2 className="font-display font-bold text-3xl text-tx-primary tracking-tight">- Create account+ {isOpen ? 'Create account' : 'Registration closed'}</h2><p className="text-tx-muted text-sm mt-2">- Start tracking your fitness today.+ {isOpen+ ? 'Start tracking your fitness today.'+ : 'This server is not accepting new accounts.'}</p></div>- {/* Server selector */}+ {/* Server selector — stays visible when closed: the user may simply be+ pointed at the wrong server, and this is where they'd fix that. */}<ServerSettings />+ {/* A closed instance explains itself rather than letting someone fill in the+ form and meet a 403 on submit. The server is what enforces this. */}+ {!isOpen ? (+ <div className="mt-6 space-y-6">+ <div className="flex gap-3 rounded-xl border border-surface-border bg-surface-raised p-4">+ <Lock className="w-4 h-4 mt-0.5 flex-shrink-0 text-tx-muted" />+ <p className="text-sm text-tx-secondary leading-relaxed">+ The owner of this Lyftr instance has turned off new signups. If you should+ have an account here, ask them to create one for you.+ </p>+ </div>+ <Link to="/login" className="btn-primary btn-lg w-full flex items-center justify-center gap-2">+ Back to sign in+ </Link>+ </div>+ ) : (+ <>{/* Form */}<form onSubmit={handleSubmit} className="space-y-4">{/* Email */}@@ -188,6 +209,8 @@ export default function Register() {Sign in</Link></p>+ </>+ )}</div></div></div>