Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
fix: self-hosted registration connectivity + server selector (#24)
Carter58d8e6da2e98
diff --git a/.env.example b/.env.exampleindex 3f9d0db..11fd0c9 100644--- a/.env.example+++ b/.env.example@@ -4,3 +4,7 @@ JWT_SECRET=change-me-to-a-random-32-plus-character-string# OptionalCORS_ORIGIN=http://localhostPORT=80++# Where the frontend proxies /api to. Change the port if you set a custom backend+# PORT (the value must match), e.g. BACKEND_ORIGIN=backend:3008.+BACKEND_ORIGIN=backend:3000diff --git a/README.md b/README.mdindex 0c06e41..2a60434 100644--- a/README.md+++ b/README.md@@ -118,8 +118,9 @@ All variables live in `.env` at the project root.| Variable | Default | Description ||----------|---------|-------------|| `JWT_SECRET` | *required* | Min 32-char secret for signing tokens |-| `CORS_ORIGIN` | `http://localhost` | Set to your domain in production |+| `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` | `host:port` the frontend proxies `/api` to. Must match the backend's `PORT` if you change it |---diff --git a/backend/.env.example b/backend/.env.exampleindex 5e2133a..ea4eee3 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -17,7 +17,8 @@ DB_PATH=./data/lyftr.dbJWT_SECRET=change-me-in-production-min-32-chars!!JWT_EXPIRY=3600-# CORS — set to your frontend origin+# 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:5173# ExerciseDB (RapidAPI)diff --git a/backend/config/config.go b/backend/config/config.goindex bc05026..27b014e 100644--- a/backend/config/config.go+++ b/backend/config/config.go@@ -20,6 +20,7 @@ type Config struct {JWTExpiry stringCORSOrigin stringEnv string+ Version string}var C *Config@@ -40,6 +41,7 @@ func Load() {JWTExpiry: getEnv("JWT_EXPIRY", "3600"),CORSOrigin: getEnv("CORS_ORIGIN", "http://localhost:5173"),Env: getEnv("ENV", "development"),+ Version: getEnv("APP_VERSION", "0.1.0"),}if C.Env == "production" && C.JWTSecret == "change-me-in-production-min-32-chars!!" {diff --git a/backend/controllers/server.go b/backend/controllers/server.gonew file mode 100644index 0000000..c88f249--- /dev/null+++ b/backend/controllers/server.go@@ -0,0 +1,19 @@+package controllers++import (+ "github.com/Cawlumm/lyftr-backend/config"+ "github.com/Cawlumm/lyftr-backend/utils"+ "github.com/gin-gonic/gin"+)++// ServerInfo is a public, unauthenticated endpoint clients use to verify that a+// configured server URL is reachable and is actually a Lyftr backend — the+// "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.+func ServerInfo(c *gin.Context) {+ utils.OK(c, gin.H{+ "name": "lyftr",+ "version": config.C.Version,+ })+}diff --git a/backend/controllers/server_test.go b/backend/controllers/server_test.gonew file mode 100644index 0000000..3a6d89b--- /dev/null+++ b/backend/controllers/server_test.go@@ -0,0 +1,30 @@+package controllers++import (+ "net/http"+ "testing"++ "github.com/Cawlumm/lyftr-backend/config"+)++func TestServerInfo(t *testing.T) {+ config.C = &config.Config{Version: "9.9.9"}++ c, w := newContext(0, "GET", "/api/v1/info", nil)+ ServerInfo(c)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200", w.Code)+ }+ body := decodeResponse(t, w)+ data, ok := body["data"].(map[string]any)+ if !ok {+ t.Fatalf("missing data envelope: %v", body)+ }+ if data["name"] != "lyftr" {+ t.Errorf("name = %v, want lyftr", data["name"])+ }+ if data["version"] != "9.9.9" {+ t.Errorf("version = %v, want 9.9.9", data["version"])+ }+}diff --git a/backend/routes/cors_test.go b/backend/routes/cors_test.gonew file mode 100644index 0000000..5a21e39--- /dev/null+++ b/backend/routes/cors_test.go@@ -0,0 +1,42 @@+package routes++import (+ "testing"++ "github.com/Cawlumm/lyftr-backend/config"+)++func TestParseOrigins(t *testing.T) {+ got := parseOrigins(" http://a.com , http://b.com ,")+ if len(got) != 2 || got[0] != "http://a.com" || got[1] != "http://b.com" {+ t.Fatalf("parseOrigins = %#v", got)+ }+ if len(parseOrigins("")) != 0 {+ t.Fatalf("empty input should yield no origins")+ }+}++func TestCORSConfig(t *testing.T) {+ // Bearer-token auth means credentials mode must stay off.+ config.C = &config.Config{Env: "production", CORSOrigin: "http://a.com,http://b.com"}+ cfg := corsConfig()+ if cfg.AllowCredentials {+ t.Error("AllowCredentials should be false")+ }+ if cfg.AllowAllOrigins {+ t.Error("an explicit allow-list should not allow all origins")+ }+ if len(cfg.AllowOrigins) != 2 {+ t.Errorf("AllowOrigins = %v, want 2 entries", cfg.AllowOrigins)+ }++ config.C = &config.Config{Env: "production", CORSOrigin: "*"}+ if !corsConfig().AllowAllOrigins {+ t.Error(`CORS_ORIGIN="*" should allow all origins`)+ }++ config.C = &config.Config{Env: "development", CORSOrigin: "http://a.com"}+ if !corsConfig().AllowAllOrigins {+ t.Error("development should allow all origins")+ }+}diff --git a/backend/routes/routes.go b/backend/routes/routes.goindex 36214b6..85ecc6d 100644--- a/backend/routes/routes.go+++ b/backend/routes/routes.go@@ -1,6 +1,9 @@package routesimport (+ "slices"+ "strings"+"github.com/Cawlumm/lyftr-backend/config""github.com/Cawlumm/lyftr-backend/controllers""github.com/Cawlumm/lyftr-backend/middleware"@@ -9,16 +12,7 @@ import ()func Setup(r *gin.Engine) {- corsOrigins := []string{config.C.CORSOrigin}- if config.C.Env == "development" {- corsOrigins = []string{"*"}- }- r.Use(cors.New(cors.Config{- AllowOrigins: corsOrigins,- AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},- AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},- AllowCredentials: config.C.Env != "development",- }))+ r.Use(cors.New(corsConfig()))r.GET("/health", func(c *gin.Context) {c.JSON(200, gin.H{"status": "ok"})@@ -26,6 +20,9 @@ func Setup(r *gin.Engine) {api := r.Group("/api/v1")+ // Public: "test connection" probe for the in-app server selector.+ api.GET("/info", controllers.ServerInfo)+// Auth (public)auth := api.Group("/auth"){@@ -97,3 +94,33 @@ func Setup(r *gin.Engine) {protected.POST("admin/reset-exercises", controllers.ResetExercises)}}++// corsConfig builds the CORS policy. Auth is Bearer-token based (no cookies), so+// credentials mode is off — which also lets the wildcard origin be valid. In+// development, or when CORS_ORIGIN is unset or "*", any origin is allowed; in+// production CORS_ORIGIN is a comma-separated allow-list of client origins.+func corsConfig() cors.Config {+ cfg := cors.Config{+ AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},+ AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},+ AllowCredentials: false,+ }++ origins := parseOrigins(config.C.CORSOrigin)+ if config.C.Env == "development" || len(origins) == 0 || slices.Contains(origins, "*") {+ cfg.AllowAllOrigins = true+ } else {+ cfg.AllowOrigins = origins+ }+ return cfg+}++func parseOrigins(raw string) []string {+ out := make([]string, 0)+ for _, p := range strings.Split(raw, ",") {+ if t := strings.TrimSpace(p); t != "" {+ out = append(out, t)+ }+ }+ return out+}diff --git a/docker-compose.yml b/docker-compose.ymlindex c4c04b7..9d2d5ca 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -26,6 +26,9 @@ services:image: cwlumm/lyftr-frontend:latestbuild: ./webrestart: unless-stopped+ environment:+ # host:port the frontend nginx proxies /api to. Must match the backend's PORT.+ - BACKEND_ORIGIN=${BACKEND_ORIGIN:-backend:3000}ports:- "${PORT:-80}:80"depends_on:diff --git a/web/Dockerfile b/web/Dockerfileindex 19e2571..e838d06 100644--- a/web/Dockerfile+++ b/web/Dockerfile@@ -14,8 +14,15 @@ RUN npm run build# Stage 2: RuntimeFROM nginx:alpine-# Custom nginx config for SPA + API proxy-COPY nginx.conf /etc/nginx/conf.d/default.conf+# Backend upstream for the /api proxy. Override at runtime (compose/`docker run -e`)+# when the backend runs on a non-default port, e.g. BACKEND_ORIGIN=backend:3008.+ENV BACKEND_ORIGIN=backend:3000+# Only substitute our own var so nginx runtime vars ($host, $uri, ...) are left intact.+ENV NGINX_ENVSUBST_FILTER=BACKEND_ORIGIN++# Custom nginx config for SPA + API proxy. nginx's entrypoint renders templates in+# /etc/nginx/templates/*.template through envsubst into /etc/nginx/conf.d/ on start.+COPY nginx.conf.template /etc/nginx/templates/default.conf.template# Copy built assetsCOPY --from=builder /app/dist /usr/share/nginx/htmldiff --git a/web/e2e/auth.spec.ts b/web/e2e/auth.spec.tsnew file mode 100644index 0000000..518450c--- /dev/null+++ b/web/e2e/auth.spec.ts@@ -0,0 +1,53 @@+import { test, expect } from '@playwright/test'++// These run logged-out, so override the shared authenticated storage state.+test.use({ storageState: { cookies: [], origins: [] } })++test('registers a new user and lands on the dashboard', async ({ page }) => {+ const email = `e2e+${Date.now()}@lyftr.local`+ await page.goto('/register')+ await page.getByPlaceholder('[email protected]').fill(email)+ await page.locator('#password').fill('password123')+ await page.locator('#password-confirm').fill('password123')+ await page.getByRole('button', { name: /create account/i }).click()+ await page.waitForURL(url => new URL(url).pathname === '/')+})++test('wrong password shows an error and stays on the login page (no reload)', async ({ page }) => {+ // Regression guard: a 401 from /auth/login must surface "Invalid email or+ // 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]')+ 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()+ await expect(page).toHaveURL(/\/login$/)+})++test('server settings rejects an invalid URL without persisting it', async ({ page }) => {+ await page.goto('/login')+ await page.getByRole('button', { name: /server settings/i }).click()+ await page.getByPlaceholder('Leave blank to use this site').fill('not a valid url')+ await page.getByRole('button', { name: /test & save/i }).click()+ await expect(page.getByText(/include http:\/\/ or https:\/\//i)).toBeVisible()+ expect(await page.evaluate(() => localStorage.getItem('server_url'))).toBeNull()+})++test('server settings tests and connects to the default (reverse proxy)', async ({ page }) => {+ await page.goto('/login')+ await page.getByRole('button', { name: /server settings/i }).click()+ await page.getByRole('button', { name: /test & save/i }).click()+ await expect(page.getByText(/connected · lyftr/i)).toBeVisible()+})++test('server settings rejects a scheme-less host instead of guessing the scheme', async ({ page }) => {+ // A bare host like "127.0.0.1:9" must be rejected with an error — we no longer+ // silently prepend a scheme. The user has to type http:// or https:// explicitly.+ await page.goto('/login')+ await page.getByRole('button', { name: /server settings/i }).click()+ await page.getByPlaceholder('Leave blank to use this site').fill('127.0.0.1:9')+ await page.getByRole('button', { name: /test & save/i }).click()+ await expect(page.getByText(/include http:\/\/ or https:\/\//i)).toBeVisible()+ expect(await page.evaluate(() => localStorage.getItem('server_url'))).toBeNull()+})diff --git a/web/nginx.conf b/web/nginx.conf.templatesimilarity index 74%rename from web/nginx.confrename to web/nginx.conf.templateindex 51a8e60..67d3e63 100644--- a/web/nginx.conf+++ b/web/nginx.conf.template@@ -18,9 +18,12 @@ server {application/jsonimage/svg+xml;- # Proxy API requests to the backend service+ # Proxy API requests to the backend service.+ # BACKEND_ORIGIN is host:port of the backend (default backend:3000), set via+ # env so deployments that run the backend on another port don't have to+ # rebuild the image. Substituted at container start by nginx's envsubst entrypoint.location /api/ {- proxy_pass http://backend:3000/api/;+ proxy_pass http://${BACKEND_ORIGIN}/api/;proxy_http_version 1.1;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;diff --git a/web/src/components/ServerSettings.tsx b/web/src/components/ServerSettings.tsxnew file mode 100644index 0000000..6eeafe8--- /dev/null+++ b/web/src/components/ServerSettings.tsx@@ -0,0 +1,117 @@+import { useState } from 'react'+import { ChevronDown, Server, CheckCircle2, AlertTriangle, Loader } from 'lucide-react'+import { useServerStore, normalizeServerUrl } from '../stores/server'+import { testServerConnection } from '../services/api'++type Status =+ | { kind: 'idle' }+ | { kind: 'testing' }+ | { kind: 'ok'; message: string }+ | { kind: 'warn'; message: string }+ | { kind: 'error'; message: string }++// Bitwarden-style server selector shared by Login and Register: validates and+// normalizes the URL, tests connectivity against the backend's public /info, and+// saves regardless of the result (a server may be temporarily down) while showing+// clear status. Empty means "use this site's own origin via the reverse proxy".+export default function ServerSettings() {+ const { serverUrl, setServerUrl } = useServerStore()+ const [open, setOpen] = useState(false)+ const [input, setInput] = useState(serverUrl)+ const [status, setStatus] = useState<Status>({ kind: 'idle' })++ const handleSave = async () => {+ const raw = input.trim()+ const normalized = normalizeServerUrl(raw) // '' = same origin (reverse proxy)+ if (raw && !normalized) {+ setStatus({+ kind: 'error',+ message: 'Include http:// or https:// — e.g. http://192.168.1.10:3000',+ })+ return+ }+ // Save immediately (warn-but-save): the choice is authoritative right away;+ // the connection probe below is advisory and may lag on a slow/down server.+ setServerUrl(normalized)+ setInput(normalized)+ setStatus({ kind: 'testing' })+ const result = await testServerConnection(normalized)+ setStatus(+ result.ok+ ? { kind: 'ok', message: `Connected · ${result.info.name} ${result.info.version}` }+ : { kind: 'warn', message: `Saved, but ${result.message}` },+ )+ }++ return (+ <div className="mb-4">+ <button+ type="button"+ onClick={() => setOpen(o => !o)}+ className="flex items-center gap-2 px-3 py-2 w-full text-xs text-tx-muted hover:text-tx-secondary rounded-lg hover:bg-surface-muted/40 transition-colors"+ >+ <Server className="w-3.5 h-3.5" />+ <span>Server settings</span>+ <ChevronDown className={`w-3 h-3 ml-auto transition-transform ${open ? 'rotate-180' : ''}`} />+ </button>++ {open && (+ <div className="mt-2 p-3 bg-surface-muted/30 border border-surface-border rounded-lg space-y-2">+ <label className="block text-xs font-medium text-tx-secondary uppercase tracking-wider">Server URL</label>+ <input+ type="text"+ value={input}+ onChange={e => { setInput(e.target.value); setStatus({ kind: 'idle' }) }}+ placeholder="Leave blank to use this site"+ className="input text-sm"+ autoComplete="off"+ autoCapitalize="off"+ spellCheck={false}+ />++ <p className="text-[11px] leading-relaxed text-tx-muted">+ Full URL, e.g. <span className="font-mono text-tx-secondary">http://192.168.1.10:3000</span>+ </p>++ {status.kind === 'error' && <p className="text-xs text-error-400">{status.message}</p>}+ {status.kind === 'warn' && (+ <p className="flex items-start gap-1.5 text-xs text-warning-400">+ <AlertTriangle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />+ <span>{status.message}</span>+ </p>+ )}+ {status.kind === 'ok' && (+ <p className="flex items-center gap-1.5 text-xs text-success-500">+ <CheckCircle2 className="w-3.5 h-3.5 flex-shrink-0" />+ <span>{status.message}</span>+ </p>+ )}++ <div className="flex gap-2 pt-1">+ <button+ type="button"+ onClick={handleSave}+ disabled={status.kind === 'testing'}+ className="flex-1 px-2 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-1.5"+ >+ {status.kind === 'testing'+ ? (<><Loader className="w-3.5 h-3.5 animate-spin" /> Testing…</>)+ : 'Test & Save'}+ </button>+ <button+ type="button"+ onClick={() => setOpen(false)}+ className="flex-1 px-2 py-1.5 text-xs bg-surface-border text-tx-secondary hover:bg-surface-border/80 rounded-lg transition-colors"+ >+ Close+ </button>+ </div>++ <p className="text-xs text-tx-muted pt-1">+ {serverUrl ? `Current: ${serverUrl}` : 'Using this site’s address (reverse proxy)'}+ </p>+ </div>+ )}+ </div>+ )+}diff --git a/web/src/pages/Login.tsx b/web/src/pages/Login.tsxindex d5eb6af..2be1d93 100644--- a/web/src/pages/Login.tsx+++ b/web/src/pages/Login.tsx@@ -1,28 +1,19 @@import { useState } from 'react'import { useNavigate, Link } from 'react-router-dom'-import { AlertCircle, Zap, Dumbbell, Apple, TrendingUp, LogIn, ChevronDown, Server } from 'lucide-react'+import { AlertCircle, Zap, Dumbbell, Apple, TrendingUp, LogIn } from 'lucide-react'import { useAuthStore } from '../stores/auth'-import { useServerStore } from '../stores/server'+import { apiErrorMessage } from '../services/api'import Logo from '../components/Logo'+import ServerSettings from '../components/ServerSettings'export default function Login() {+ const navigate = useNavigate()+ const { login } = useAuthStore()+const [email, setEmail] = useState('')const [password, setPassword] = useState('')const [error, setError] = useState('')const [isLoading, setLoading] = useState(false)- const [showServerSettings, setShowServerSettings] = useState(false)- const [serverInput, setServerInput] = useState('')-- const navigate = useNavigate()- const { login } = useAuthStore()- const { serverUrl, setServerUrl } = useServerStore()-- const handleServerUrlChange = () => {- if (serverInput.trim()) {- setServerUrl(serverInput)- setServerInput('')- }- }const handleSubmit = async (e: React.FormEvent) => {e.preventDefault()@@ -32,7 +23,7 @@ export default function Login() {await login(email, password)navigate('/')} catch (err: any) {- setError(err.response?.data?.error || 'Invalid email or password.')+ setError(apiErrorMessage(err, 'Invalid email or password.'))} finally {setLoading(false)}@@ -44,7 +35,7 @@ export default function Login() {await login('[email protected]', 'password123')navigate('/')} catch (err: any) {- setError(err.response?.data?.error || 'Demo login failed')+ setError(apiErrorMessage(err, 'Demo login failed'))} finally {setLoading(false)}@@ -124,47 +115,8 @@ export default function Login() {</p></div>- {/* Server settings toggle */}- <button- onClick={() => setShowServerSettings(!showServerSettings)}- className="flex items-center gap-2 px-3 py-2 mb-4 text-xs text-tx-muted hover:text-tx-secondary rounded-lg hover:bg-surface-muted/40 transition-colors"- >- <Server className="w-3.5 h-3.5" />- <span>Server settings</span>- <ChevronDown className={`w-3 h-3 ml-auto transition-transform ${showServerSettings ? 'rotate-180' : ''}`} />- </button>-- {/* Server settings panel */}- {showServerSettings && (- <div className="mb-4 p-3 bg-surface-muted/30 border border-surface-border rounded-lg space-y-2">- <label className="block text-xs font-medium text-tx-secondary uppercase tracking-wider">Server URL</label>- <input- type="text"- value={serverInput || serverUrl}- onChange={e => setServerInput(e.target.value)}- placeholder="http://localhost:3000"- className="input text-sm"- />- <div className="flex gap-2 pt-1">- <button- onClick={handleServerUrlChange}- disabled={!serverInput.trim()}- className="flex-1 px-2 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors"- >- Save- </button>- <button- onClick={() => setShowServerSettings(false)}- className="flex-1 px-2 py-1.5 text-xs bg-surface-border text-tx-secondary hover:bg-surface-border/80 rounded-lg transition-colors"- >- Close- </button>- </div>- {serverUrl !== 'http://localhost:3000' && (- <p className="text-xs text-tx-muted pt-1">Current: {serverUrl}</p>- )}- </div>- )}+ {/* Server selector */}+ <ServerSettings />{/* Form */}<form onSubmit={handleSubmit} className="space-y-4">diff --git a/web/src/pages/Register.tsx b/web/src/pages/Register.tsxindex d77273c..7ea2df5 100644--- a/web/src/pages/Register.tsx+++ b/web/src/pages/Register.tsx@@ -1,29 +1,20 @@import { useState } from 'react'import { useNavigate, Link } from 'react-router-dom'-import { AlertCircle, Dumbbell, Apple, TrendingUp, UserPlus, ChevronDown, Server } from 'lucide-react'+import { AlertCircle, Dumbbell, Apple, TrendingUp, UserPlus } from 'lucide-react'import { useAuthStore } from '../stores/auth'-import { useServerStore } from '../stores/server'+import { apiErrorMessage } from '../services/api'import Logo from '../components/Logo'+import ServerSettings from '../components/ServerSettings'export default function Register() {+ const navigate = useNavigate()+ const { register } = useAuthStore()+const [email, setEmail] = useState('')const [password, setPassword] = useState('')const [passwordConfirm, setPasswordConfirm] = useState('')const [error, setError] = useState('')const [isLoading, setLoading] = useState(false)- const [showServerSettings, setShowServerSettings] = useState(false)- const [serverInput, setServerInput] = useState('')-- const navigate = useNavigate()- const { register } = useAuthStore()- const { serverUrl, setServerUrl } = useServerStore()-- const handleServerUrlChange = () => {- if (serverInput.trim()) {- setServerUrl(serverInput)- setServerInput('')- }- }const handleSubmit = async (e: React.FormEvent) => {e.preventDefault()@@ -35,7 +26,7 @@ export default function Register() {await register(email, password)navigate('/')} catch (err: any) {- setError(err.response?.data?.error || 'Registration failed.')+ setError(apiErrorMessage(err, 'Registration failed.'))} finally {setLoading(false)}@@ -115,47 +106,8 @@ export default function Register() {</p></div>- {/* Server settings toggle */}- <button- onClick={() => setShowServerSettings(!showServerSettings)}- className="flex items-center gap-2 px-3 py-2 mb-4 text-xs text-tx-muted hover:text-tx-secondary rounded-lg hover:bg-surface-muted/40 transition-colors"- >- <Server className="w-3.5 h-3.5" />- <span>Server settings</span>- <ChevronDown className={`w-3 h-3 ml-auto transition-transform ${showServerSettings ? 'rotate-180' : ''}`} />- </button>-- {/* Server settings panel */}- {showServerSettings && (- <div className="mb-4 p-3 bg-surface-muted/30 border border-surface-border rounded-lg space-y-2">- <label className="block text-xs font-medium text-tx-secondary uppercase tracking-wider">Server URL</label>- <input- type="text"- value={serverInput || serverUrl}- onChange={e => setServerInput(e.target.value)}- placeholder="http://localhost:3000"- className="input text-sm"- />- <div className="flex gap-2 pt-1">- <button- onClick={handleServerUrlChange}- disabled={!serverInput.trim()}- className="flex-1 px-2 py-1.5 text-xs bg-brand-500 hover:bg-brand-600 disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors"- >- Save- </button>- <button- onClick={() => setShowServerSettings(false)}- className="flex-1 px-2 py-1.5 text-xs bg-surface-border text-tx-secondary hover:bg-surface-border/80 rounded-lg transition-colors"- >- Close- </button>- </div>- {serverUrl !== 'http://localhost:3000' && (- <p className="text-xs text-tx-muted pt-1">Current: {serverUrl}</p>- )}- </div>- )}+ {/* Server selector */}+ <ServerSettings />{/* Form */}<form onSubmit={handleSubmit} className="space-y-4">diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsxindex 4d87d76..f1518ba 100644--- a/web/src/pages/Settings.tsx+++ b/web/src/pages/Settings.tsx@@ -1,5 +1,6 @@import { useState, useEffect, useCallback } from 'react'import { useAuthStore } from '../stores/auth'+import { useServerStore } from '../stores/server'import { useSettingsStore } from '../stores/settings'import { useTheme } from '../hooks/useTheme'import { exerciseAPI } from '../services/api'@@ -38,6 +39,7 @@ function Section({ title, children }: { title: string; children: React.ReactNodeexport default function Settings() {const { user, logout } = useAuthStore()+ const serverUrl = useServerStore(s => s.serverUrl)const { theme, toggleTheme } = useTheme()const { settings: storedSettings, update: updateSettings, fetch: fetchSettings, setWorkoutLayout } = useSettingsStore()const [loading, setLoading] = useState(!useSettingsStore.getState().loaded)@@ -292,7 +294,7 @@ export default function Settings() {<SettingRow label="API server" description="Backend server this client is connected to"><div className="flex items-center gap-2"><span className="w-1.5 h-1.5 rounded-full bg-success-500 flex-shrink-0" />- <span className="text-xs font-mono text-tx-muted">localhost:3000</span>+ <span className="text-xs font-mono text-tx-muted">{serverUrl || 'This site (reverse proxy)'}</span></div></SettingRow><SettingRow label="Database" description="Storage backend">diff --git a/web/src/services/api.ts b/web/src/services/api.tsindex 529cf17..e19d14d 100644--- a/web/src/services/api.ts+++ b/web/src/services/api.ts@@ -1,13 +1,65 @@import axios, { AxiosInstance } from 'axios'import * as types from '../types'+import { normalizeServerUrl } from '../stores/server'++// Every API call lives under this versioned path. `origin` is an absolute server+// origin for a cross-origin backend, or '' for the same-origin reverse proxy.+const API_BASE_PATH = '/api/v1'+const apiUrl = (origin = '') => `${origin}${API_BASE_PATH}`// Resolved per-request so the "Server settings" panel takes effect immediately,// without needing a full page reload.const resolveAPIBase = () => {const envUrl = import.meta.env.VITE_API_URL as string | undefinedif (envUrl) return envUrl- const serverUrl = localStorage.getItem('server_url')- return serverUrl ? `${serverUrl}/api/v1` : '/api/v1'+ // Re-normalize in case localStorage holds a legacy/scheme-less value: a relative+ // base would make axios fold the host into the request path (bogus 405s), so fall+ // back to the same-origin reverse proxy when it can't be made absolute.+ const stored = localStorage.getItem('server_url')+ const base = stored ? normalizeServerUrl(stored) : ''+ return apiUrl(base)+}++// Turn an axios error into an actionable message. Network/CORS/connection failures+// (no response) and proxy misconfig (404/405) are distinguished from real auth and+// server errors, so connectivity problems don't masquerade as "Registration failed."+// Intended for the auth/connectivity flows (login/register/connection test); the+// 404/405 wording assumes a misconfigured server URL rather than a missing resource.+export const apiErrorMessage = (err: any, fallback: string): string => {+ if (err?.response) {+ const serverError = err.response.data?.error+ if (serverError) return serverError+ const status = err.response.status+ if (status === 404 || status === 405) {+ return "Server URL looks misconfigured — the API endpoint wasn't found. Check Server settings."+ }+ if (status >= 500) return 'Server error. Please try again shortly.'+ return fallback+ }+ return "Can't reach the server. Check the URL, that the backend is running, and that it allows this app's origin (CORS)."+}++export interface ServerInfo {+ name: string+ version: string+}++// Probes a server's public /info endpoint to confirm it's reachable and is a+// Lyftr backend. Pass '' to test the same-origin reverse-proxy path. Runs under+// the backend's CORS policy, so success predicts that real requests will work.+export const testServerConnection = async (+ base: string,+): Promise<{ ok: true; info: ServerInfo } | { ok: false; message: string }> => {+ try {+ const res = await axios.get<{ data: ServerInfo }>(`${apiUrl(base)}/info`, { timeout: 8000 })+ const info = res.data?.data+ if (!info?.name) {+ return { ok: false, message: "That responded, but it doesn't look like a Lyftr server." }+ }+ return { ok: true, info }+ } catch (err) {+ return { ok: false, message: apiErrorMessage(err, "Couldn't reach the server.") }+ }}const api: AxiosInstance = axios.create({@@ -25,7 +77,11 @@ api.interceptors.response.use((response) => response,async (error) => {const original = error.config- if (error.response?.status === 401 && !original._retry) {+ // A 401 from the auth endpoints themselves is a credential error, not an+ // expired session — let the page show it instead of attempting a token+ // refresh and redirecting (which would wipe "Invalid email or password").+ const isAuthRequest = (original?.url || '').includes('/auth/')+ if (error.response?.status === 401 && !original._retry && !isAuthRequest) {original._retry = truetry {const refreshToken = localStorage.getItem('refresh_token')diff --git a/web/src/stores/server.ts b/web/src/stores/server.tsindex 4f94a4b..e932a75 100644--- a/web/src/stores/server.ts+++ b/web/src/stores/server.ts@@ -1,27 +1,41 @@import { create } from 'zustand'+// Normalize a user-entered server URL to an absolute origin (scheme + host[:port]).+// Empty input returns '' — "use this site's own origin via the reverse proxy", the+// zero-config default. A non-empty value MUST include an explicit http:// or+// https:// scheme; a bare host ("192.168.1.10:3000"), wrong scheme, or garbage+// returns '' so the caller can reject it with an error. We deliberately do NOT+// guess a scheme: silently prepending one hides typos and can pick the wrong+// protocol (e.g. http on an HTTPS deployment), so the user must be explicit.+export const normalizeServerUrl = (raw: string): string => {+ const trimmed = raw.trim()+ if (!trimmed) return ''+ if (/\s/.test(trimmed)) return '' // a server URL never contains whitespace+ if (!/^https?:\/\//i.test(trimmed)) return '' // require an explicit http:// or https://+ try {+ const u = new URL(trimmed)+ if (!u.hostname) return ''+ return `${u.protocol}//${u.host}`+ } catch {+ return ''+ }+}+interface ServerStore {- serverUrl: string+ serverUrl: string // '' = same origin (reverse proxy)setServerUrl: (url: string) => voidgetServerUrl: () => string}-const DEFAULT_SERVER = 'http://localhost:3000'+export const useServerStore = create<ServerStore>((set, get) => ({+ serverUrl: localStorage.getItem('server_url') || '',-export const useServerStore = create<ServerStore>((set, get) => {- const stored = localStorage.getItem('server_url') || DEFAULT_SERVER+ setServerUrl: (url: string) => {+ const normalized = normalizeServerUrl(url)+ if (normalized) localStorage.setItem('server_url', normalized)+ else localStorage.removeItem('server_url')+ set({ serverUrl: normalized })+ },- return {- serverUrl: stored,-- setServerUrl: (url: string) => {- const normalized = url.trim().replace(/\/$/, '')- localStorage.setItem('server_url', normalized)- set({ serverUrl: normalized })- },-- getServerUrl: () => {- return get().serverUrl- },- }-})+ getServerUrl: () => get().serverUrl,+}))