Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

End a revoked or deleted account's session on its next request (#197)

Cartera40dc8ccd52e
diff --git a/backend/controllers/auth.go b/backend/controllers/auth.go
index e555bb9..9e839e3 100644
--- a/backend/controllers/auth.go
+++ b/backend/controllers/auth.go
@@ -309,11 +309,11 @@ func (h *Handler) RefreshToken(c *gin.Context) {
return
}
- // The one place a stateless token meets server state. Signature validity says the
- // token was minted by us; it cannot say the credentials behind it still stand. A
- // refresh lives 30 days, so without this check a password change would leave every
- // other device — including whoever the change was meant to evict — able to mint
- // fresh access tokens for a month.
+ // Signature validity says the token was minted by us; it cannot say the credentials
+ // behind it still stand. A refresh lives 30 days, so without this check a password change
+ // would leave every other device — including whoever the change was meant to evict — able
+ // to mint fresh access tokens for a month. The auth middleware makes the same comparison
+ // for access tokens on every request, so a revoked device stops at its next request.
current, err := h.s.User.TokenVersion(claims.UserID)
if err == sql.ErrNoRows {
utils.Unauthorized(c, "Your session isn't valid. Please sign in again.")
diff --git a/backend/controllers/handler.go b/backend/controllers/handler.go
index f219f95..d2c24ae 100644
--- a/backend/controllers/handler.go
+++ b/backend/controllers/handler.go
@@ -1,6 +1,9 @@
package controllers
-import "github.com/Cawlumm/lyftr-backend/stores"
+import (
+ "github.com/Cawlumm/lyftr-backend/middleware"
+ "github.com/Cawlumm/lyftr-backend/stores"
+)
// Handler carries the injected stores. Every HTTP handler is a method on Handler
// so it reaches the database only through h.s.<Entity>, never the global db.DB.
@@ -9,3 +12,7 @@ type Handler struct {
}
func NewHandler(s *stores.Stores) *Handler { return &Handler{s: s} }
+
+// TokenVersions is the handler's user store as the auth middleware needs it, so routes can
+// wire Auth without reaching into the stores.
+func (h *Handler) TokenVersions() middleware.TokenVersions { return h.s.User }
diff --git a/backend/middleware/auth.go b/backend/middleware/auth.go
index 8cfe745..89ac53a 100644
--- a/backend/middleware/auth.go
+++ b/backend/middleware/auth.go
@@ -1,16 +1,33 @@
package middleware
import (
+ "database/sql"
+ "errors"
"strings"
"github.com/Cawlumm/lyftr-backend/utils"
"github.com/gin-gonic/gin"
)
+// TokenVersions is what Auth needs from the user store: the account's current token
+// generation, or sql.ErrNoRows when the account is gone.
+type TokenVersions interface {
+ TokenVersion(uid int64) (int, error)
+}
+
const UserIDKey = "user_id"
const UserEmailKey = "user_email"
-func Auth() gin.HandlerFunc {
+// Auth accepts a request only if its access token is genuine and still stands: the account
+// exists and the token was minted against the account's current token version. A signature
+// alone proves we issued the token, not that the credentials behind it survive, so without
+// the lookup a deleted account or a session ended by a password or email change kept working
+// until its token expired — reads came back empty and writes failed with a server error.
+//
+// One primary-key read per request, measured at about 10µs on the production pool. A
+// mismatch answers 401, which the clients already read as "try a refresh"; the refresh
+// then fails the same check and signs the device out cleanly.
+func Auth(versions TokenVersions) gin.HandlerFunc {
return func(c *gin.Context) {
header := c.GetHeader("Authorization")
if !strings.HasPrefix(header, "Bearer ") {
@@ -32,6 +49,22 @@ func Auth() gin.HandlerFunc {
return
}
+ current, err := versions.TokenVersion(claims.UserID)
+ if errors.Is(err, sql.ErrNoRows) {
+ utils.Unauthorized(c, "Your session isn't valid. Please sign in again.")
+ c.Abort()
+ return
+ }
+ if utils.DBError(c, err) {
+ c.Abort()
+ return
+ }
+ if utils.NormalizeTokenVersion(claims.TokenVersion) != current {
+ utils.Unauthorized(c, "Your session expired. Please sign in again.")
+ c.Abort()
+ return
+ }
+
c.Set(UserIDKey, claims.UserID)
c.Set(UserEmailKey, claims.Email)
c.Next()
diff --git a/backend/middleware/auth_test.go b/backend/middleware/auth_test.go
new file mode 100644
index 0000000..d545297
--- /dev/null
+++ b/backend/middleware/auth_test.go
@@ -0,0 +1,163 @@
+package middleware
+
+import (
+ "database/sql"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/config"
+ "github.com/Cawlumm/lyftr-backend/utils"
+ "github.com/gin-gonic/gin"
+ _ "modernc.org/sqlite"
+)
+
+type fakeVersions struct {
+ version int
+ err error
+}
+
+func (f fakeVersions) TokenVersion(int64) (int, error) { return f.version, f.err }
+
+func useConfig(t *testing.T) {
+ t.Helper()
+ prev := config.C
+ config.C = &config.Config{JWTSecret: "test-secret-test-secret-test-secret-1", JWTExpiry: "3600"}
+ t.Cleanup(func() { config.C = prev })
+}
+
+func serve(t *testing.T, v TokenVersions, header string) (*httptest.ResponseRecorder, *bool) {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ reached := false
+ r := gin.New()
+ r.GET("/ping", Auth(v), func(c *gin.Context) {
+ reached = true
+ c.JSON(http.StatusOK, gin.H{"id": UserID(c)})
+ })
+ req := httptest.NewRequest(http.MethodGet, "/ping", nil)
+ if header != "" {
+ req.Header.Set("Authorization", header)
+ }
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+ return w, &reached
+}
+
+func pair(t *testing.T, version int) (access, refresh string) {
+ t.Helper()
+ a, r, err := utils.GenerateTokenPair(7, "[email protected]", version)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return a, r
+}
+
+func TestAuthAcceptsATokenAtTheCurrentVersion(t *testing.T) {
+ useConfig(t)
+ access, _ := pair(t, 3)
+ w, reached := serve(t, fakeVersions{version: 3}, "Bearer "+access)
+ if w.Code != http.StatusOK || !*reached {
+ t.Fatalf("status = %d reached = %v, want 200 and reached", w.Code, *reached)
+ }
+}
+
+func TestAuthRejectsATokenFromAnEarlierVersion(t *testing.T) {
+ useConfig(t)
+ access, _ := pair(t, 2)
+ w, reached := serve(t, fakeVersions{version: 3}, "Bearer "+access)
+ if w.Code != http.StatusUnauthorized || *reached {
+ t.Fatalf("status = %d reached = %v, want 401 and not reached", w.Code, *reached)
+ }
+}
+
+func TestAuthRejectsADeletedAccount(t *testing.T) {
+ useConfig(t)
+ access, _ := pair(t, 1)
+ w, reached := serve(t, fakeVersions{err: sql.ErrNoRows}, "Bearer "+access)
+ if w.Code != http.StatusUnauthorized || *reached {
+ t.Fatalf("status = %d reached = %v, want 401 and not reached", w.Code, *reached)
+ }
+}
+
+func TestAuthAnswers500WhenTheLookupFails(t *testing.T) {
+ useConfig(t)
+ access, _ := pair(t, 1)
+ w, reached := serve(t, fakeVersions{err: errors.New("disk I/O error")}, "Bearer "+access)
+ if w.Code != http.StatusInternalServerError || *reached {
+ t.Fatalf("status = %d reached = %v, want 500 and not reached", w.Code, *reached)
+ }
+}
+
+// busyErr returns a real modernc SQLITE_BUSY error by writing from a second connection
+// while a write lock is held on the first, the same way utils' own tests do.
+func busyErr(t *testing.T) error {
+ t.Helper()
+ path := t.TempDir() + "/busy.db"
+ a, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(0)")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer a.Close()
+ if _, err := a.Exec(`CREATE TABLE t (id INTEGER PRIMARY KEY)`); err != nil {
+ t.Fatal(err)
+ }
+ tx, err := a.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tx.Exec(`INSERT INTO t (id) VALUES (1)`); err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback()
+ b, err := sql.Open("sqlite", path+"?_pragma=busy_timeout(0)")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer b.Close()
+ _, err = b.Exec(`INSERT INTO t (id) VALUES (2)`)
+ if err == nil {
+ t.Fatal("expected a busy error")
+ }
+ return err
+}
+
+// A lock is transient: answering 401 would make every client refresh and then sign the user
+// out over a moment's contention, so it has to be a 503 the clients already retry.
+func TestAuthAnswers503WhenTheDatabaseIsLocked(t *testing.T) {
+ useConfig(t)
+ access, _ := pair(t, 1)
+ w, reached := serve(t, fakeVersions{err: busyErr(t)}, "Bearer "+access)
+ if w.Code != http.StatusServiceUnavailable || *reached {
+ t.Fatalf("status = %d reached = %v, want 503 and not reached", w.Code, *reached)
+ }
+}
+
+// Tokens minted before the version claim existed decode as 0. They stay valid while the
+// account is at 1 and end the moment a change moves it on.
+func TestAuthTreatsAPreVersionTokenAsVersionOne(t *testing.T) {
+ useConfig(t)
+ access, _ := pair(t, 0)
+ if w, _ := serve(t, fakeVersions{version: 1}, "Bearer "+access); w.Code != http.StatusOK {
+ t.Errorf("at version 1 = %d, want 200", w.Code)
+ }
+ if w, _ := serve(t, fakeVersions{version: 2}, "Bearer "+access); w.Code != http.StatusUnauthorized {
+ t.Errorf("at version 2 = %d, want 401", w.Code)
+ }
+}
+
+func TestAuthRejectsMissingMalformedAndRefreshTokens(t *testing.T) {
+ useConfig(t)
+ _, refresh := pair(t, 1)
+ for name, header := range map[string]string{
+ "no header": "",
+ "not a bearer": "Basic abc",
+ "garbage": "Bearer not-a-token",
+ "a refresh one": "Bearer " + refresh,
+ } {
+ if w, reached := serve(t, fakeVersions{version: 1}, header); w.Code != http.StatusUnauthorized || *reached {
+ t.Errorf("%s: status = %d reached = %v, want 401", name, w.Code, *reached)
+ }
+ }
+}
diff --git a/backend/routes/revocation_test.go b/backend/routes/revocation_test.go
new file mode 100644
index 0000000..b3f7710
--- /dev/null
+++ b/backend/routes/revocation_test.go
@@ -0,0 +1,194 @@
+package routes
+
+import (
+ "bytes"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "math/rand"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/Cawlumm/lyftr-backend/config"
+ "github.com/Cawlumm/lyftr-backend/controllers"
+ "github.com/Cawlumm/lyftr-backend/db"
+ "github.com/Cawlumm/lyftr-backend/stores"
+ "github.com/gin-gonic/gin"
+ _ "modernc.org/sqlite"
+)
+
+// These run the real router against a real database, so they prove what a client sees:
+// an access token stops working the moment its account is deleted or its session ended,
+// instead of lingering until it expires (#194).
+
+type api struct {
+ t *testing.T
+ r *gin.Engine
+}
+
+func newAPI(t *testing.T) *api {
+ t.Helper()
+ prev := config.C
+ config.C = &config.Config{
+ Env: "production", CORSOrigin: "http://a.com", Registration: config.RegistrationOpen,
+ JWTSecret: "test-secret-test-secret-test-secret-1", JWTExpiry: "3600", Version: "test",
+ }
+ t.Cleanup(func() { config.C = prev })
+
+ name := fmt.Sprintf("file:revoke_%d?mode=memory&cache=shared&_pragma=foreign_keys(on)", rand.Int63())
+ conn, err := sql.Open("sqlite", name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // One connection, as in production, so a query in the middleware that waited on a
+ // handler's transaction would hang these tests rather than pass them.
+ conn.SetMaxOpenConns(1)
+ prevDB := db.DB
+ db.DB = conn
+ if err := db.BuildSchema(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { conn.Close(); db.DB = prevDB })
+
+ gin.SetMode(gin.TestMode)
+ r := gin.New()
+ Setup(r, controllers.NewHandler(stores.New(conn)))
+ return &api{t: t, r: r}
+}
+
+func (a *api) do(method, path, token string, body any) (int, map[string]any) {
+ a.t.Helper()
+ var buf bytes.Buffer
+ if body != nil {
+ if err := json.NewEncoder(&buf).Encode(body); err != nil {
+ a.t.Fatal(err)
+ }
+ }
+ req := httptest.NewRequest(method, path, &buf)
+ req.Header.Set("Content-Type", "application/json")
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+ w := httptest.NewRecorder()
+ a.r.ServeHTTP(w, req)
+ var out map[string]any
+ _ = json.Unmarshal(w.Body.Bytes(), &out)
+ return w.Code, out
+}
+
+func data(m map[string]any) map[string]any {
+ d, _ := m["data"].(map[string]any)
+ return d
+}
+
+func (a *api) register(email string) (access, refresh string) {
+ a.t.Helper()
+ code, body := a.do("POST", "/api/v1/auth/register", "", map[string]string{"email": email, "password": "password123"})
+ if code != http.StatusCreated {
+ a.t.Fatalf("register %s = %d %v", email, code, body)
+ }
+ d := data(body)
+ return d["token"].(string), d["refresh_token"].(string)
+}
+
+func (a *api) login(email string) (access, refresh string) {
+ a.t.Helper()
+ code, body := a.do("POST", "/api/v1/auth/login", "", map[string]string{"email": email, "password": "password123"})
+ if code != http.StatusOK {
+ a.t.Fatalf("login %s = %d %v", email, code, body)
+ }
+ d := data(body)
+ return d["token"].(string), d["refresh_token"].(string)
+}
+
+func (a *api) status(token string) int {
+ code, _ := a.do("GET", "/api/v1/me", token, nil)
+ return code
+}
+
+func TestADeletedAccountsTokenStopsWorkingAtOnce(t *testing.T) {
+ a := newAPI(t)
+ access, _ := a.register("[email protected]")
+ if a.status(access) != http.StatusOK {
+ t.Fatal("a fresh token should work")
+ }
+
+ if code, body := a.do("DELETE", "/api/v1/me", access, nil); code != http.StatusOK {
+ t.Fatalf("delete = %d %v", code, body)
+ }
+
+ for _, probe := range []struct{ method, path string }{
+ {"GET", "/api/v1/me"}, {"GET", "/api/v1/weight"}, {"GET", "/api/v1/food"}, {"POST", "/api/v1/weight"},
+ } {
+ if code, _ := a.do(probe.method, probe.path, access, map[string]any{"weight": 180}); code != http.StatusUnauthorized {
+ t.Errorf("%s %s with the deleted account's token = %d, want 401", probe.method, probe.path, code)
+ }
+ }
+}
+
+func TestChangingThePasswordEndsOtherDevicesAtOnce(t *testing.T) {
+ a := newAPI(t)
+ a.register("[email protected]")
+ thisDevice, _ := a.login("[email protected]")
+ otherDevice, _ := a.login("[email protected]")
+
+ code, body := a.do("PUT", "/api/v1/me/password", thisDevice, map[string]string{
+ "current_password": "password123", "new_password": "a-new-password-9",
+ })
+ if code != http.StatusOK {
+ t.Fatalf("change password = %d %v", code, body)
+ }
+ fresh := data(body)["token"].(string)
+
+ if got := a.status(otherDevice); got != http.StatusUnauthorized {
+ t.Errorf("the other device's token = %d, want 401", got)
+ }
+ if got := a.status(thisDevice); got != http.StatusUnauthorized {
+ t.Errorf("this device's pre-change token = %d, want 401", got)
+ }
+ if got := a.status(fresh); got != http.StatusOK {
+ t.Errorf("the pair handed back = %d, want 200", got)
+ }
+}
+
+func TestChangingTheEmailEndsOtherDevicesButNotACaseOnlyChange(t *testing.T) {
+ a := newAPI(t)
+ a.register("[email protected]")
+ thisDevice, _ := a.login("[email protected]")
+ otherDevice, _ := a.login("[email protected]")
+
+ change := func(token, email string) map[string]any {
+ code, body := a.do("PUT", "/api/v1/me/email", token, map[string]string{"email": email, "current_password": "password123"})
+ if code != http.StatusOK {
+ t.Fatalf("change to %s = %d %v", email, code, body)
+ }
+ return data(body)
+ }
+
+ // Capitalisation alone changes no identity, so nothing ends.
+ cased := change(thisDevice, "[email protected]")
+ if got := a.status(otherDevice); got != http.StatusOK {
+ t.Errorf("other device after a case-only change = %d, want 200", got)
+ }
+
+ // A real change ends the other device immediately, and keeps the one that made it.
+ moved := change(cased["token"].(string), "[email protected]")
+ if got := a.status(otherDevice); got != http.StatusUnauthorized {
+ t.Errorf("other device after a real change = %d, want 401", got)
+ }
+ if got := a.status(moved["token"].(string)); got != http.StatusOK {
+ t.Errorf("the pair handed back = %d, want 200", got)
+ }
+}
+
+func TestAnUntouchedAccountsTokenKeepsWorking(t *testing.T) {
+ a := newAPI(t)
+ access, _ := a.register("[email protected]")
+ a.register("[email protected]")
+ for i := range 3 {
+ if got := a.status(access); got != http.StatusOK {
+ t.Fatalf("request %d = %d, want 200", i, got)
+ }
+ }
+}
diff --git a/backend/routes/routes.go b/backend/routes/routes.go
index 899ec43..904424a 100644
--- a/backend/routes/routes.go
+++ b/backend/routes/routes.go
@@ -33,7 +33,7 @@ func Setup(r *gin.Engine, h *controllers.Handler) {
// Protected routes
protected := api.Group("/")
- protected.Use(middleware.Auth())
+ protected.Use(middleware.Auth(h.TokenVersions()))
{
// User
protected.GET("me", h.GetMe)
diff --git a/backend/routes/routes_test.go b/backend/routes/routes_test.go
index 6448a02..1370fc9 100644
--- a/backend/routes/routes_test.go
+++ b/backend/routes/routes_test.go
@@ -6,26 +6,17 @@ import (
"net/http/httptest"
"strings"
"testing"
-
- "github.com/Cawlumm/lyftr-backend/config"
- "github.com/Cawlumm/lyftr-backend/controllers"
- "github.com/Cawlumm/lyftr-backend/stores"
- "github.com/gin-gonic/gin"
)
func TestChangeEmailRequiresAuth(t *testing.T) {
- prev := config.C
- config.C = &config.Config{Env: "production", CORSOrigin: "http://a.com", JWTSecret: "test-secret-test-secret-test-secret-1"}
- t.Cleanup(func() { config.C = prev })
-
- gin.SetMode(gin.TestMode)
- r := gin.New()
- Setup(r, controllers.NewHandler(stores.New(nil)))
+ // A real database rather than a nil store: Auth reads the account on a valid token, so a
+ // future case in this file that sent one would panic on a nil pool and take the binary down.
+ a := newAPI(t)
req := httptest.NewRequest(http.MethodPut, "/api/v1/me/email", strings.NewReader(`{}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
- r.ServeHTTP(w, req)
+ a.r.ServeHTTP(w, req)
if w.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", w.Code)
diff --git a/backend/stores/user.go b/backend/stores/user.go
index 6e8cb35..692887d 100644
--- a/backend/stores/user.go
+++ b/backend/stores/user.go
@@ -95,8 +95,9 @@ func (s *UserStore) GetByID(uid int64) (models.User, error) {
}
// TokenVersion returns the account's current token generation, or sql.ErrNoRows if the
-// account is gone. Read on refresh only — never on the per-request auth path, which
-// stays free of database work.
+// account is gone. Read on refresh and, by the auth middleware, on every authenticated
+// request: it is a primary-key read, and it is what makes a deleted account or an ended
+// session stop working at once rather than when its access token expires.
func (s *UserStore) TokenVersion(uid int64) (int, error) {
var v int
err := s.db.QueryRow(`SELECT token_version FROM users WHERE id = ?`, uid).Scan(&v)
diff --git a/backend/utils/jwt.go b/backend/utils/jwt.go
index ef44513..5ad8a6f 100644
--- a/backend/utils/jwt.go
+++ b/backend/utils/jwt.go
@@ -13,10 +13,10 @@ type Claims struct {
UserID int64 `json:"user_id"`
Email string `json:"email"`
Type string `json:"type"` // "access" or "refresh"
- // TokenVersion is the users.token_version this token was minted against. Refresh
- // rejects a mismatch, which is what makes a password change actually end other
- // sessions. Absent in tokens issued before the claim existed, so it decodes as 0
- // there — see NormalizeTokenVersion.
+ // TokenVersion is the users.token_version this token was minted against. Refresh and
+ // the auth middleware both reject a mismatch, which is what makes a password or email
+ // change actually end other sessions. Absent in tokens issued before the claim existed,
+ // so it decodes as 0 there — see NormalizeTokenVersion.
TokenVersion int `json:"ver,omitempty"`
jwt.RegisteredClaims
}
diff --git a/docs/API_CHANGES.md b/docs/API_CHANGES.md
index 8cb032f..46f9c87 100644
--- a/docs/API_CHANGES.md
+++ b/docs/API_CHANGES.md
@@ -197,6 +197,13 @@ with the entire history reads as data loss in reverse — so the rejection is de
Not entries — nothing to fix on a caller's side — but worth a line in the notes because
somebody will see the change.
+- **A revoked access token now answers `401` on the next request.** The auth middleware
+ checks the token's session version against the account on every request, so a deleted
+ account, or a session ended by a password or email change, is rejected on its next request
+ instead of lingering until the token expires (an hour by default; reads used to come back empty and writes
+ failed with a `500`). Clients already read a `401` as "try a refresh", and the refresh
+ fails the same check, so they sign out. A caller holding a long-lived access token for a
+ deleted or revoked account will now see the `401`.
- **Sign-in matches the address case-insensitively**, returning the spelling stored at
registration. An install that already holds case-variant accounts keeps both: each still
signs in with its exact spelling, and the boot log names them;
diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.ts
index 2998e3f..5129e44 100644
--- a/packages/shared/src/client.test.ts
+++ b/packages/shared/src/client.test.ts
@@ -512,3 +512,79 @@ describe('a token refresh nobody answers (#145)', () => {
expect(refreshes).toBe(2)
})
})
+
+// The device that changes its own password or email stores its replacement token pair a
+// moment after the server commits, and every older token is rejected from that instant.
+// A request already in flight then 401s with the old access token; refreshing from there
+// would present the old refresh token and sign out the device the change keeps signed in.
+describe('a 401 that arrives while this device is switching to its new tokens', () => {
+ const realAdapter = axios.defaults.adapter
+ afterEach(() => { axios.defaults.adapter = realAdapter })
+
+ const httpError = (status: number, config: any) => {
+ const err: any = new Error(`Request failed with status code ${status}`)
+ err.config = config
+ err.response = { status, data: {}, statusText: '', headers: {}, config }
+ return err
+ }
+ const ok = (config: any) => ({ data: { data: { id: 1 } }, status: 200, statusText: 'OK', headers: {}, config })
+
+ const setup = async () => {
+ const store = memStorage()
+ let signedOut = false
+ const client = createClient(store, { onAuthFailure: () => { signedOut = true } })
+ await store.set(STORAGE_KEYS.access, 'old')
+ await store.set(STORAGE_KEYS.refresh, 'old-refresh')
+ await store.set(STORAGE_KEYS.user, '{"id":1}')
+ return { store, client, wasSignedOut: () => signedOut }
+ }
+
+ it('retries with the token now in storage instead of refreshing', async () => {
+ const { store, client, wasSignedOut } = await setup()
+ let refreshes = 0
+ axios.defaults.adapter = (async () => { refreshes += 1; throw httpError(401, {}) }) as any
+ client.api.defaults.adapter = async (config: any) => {
+ if (config.headers.Authorization === 'Bearer old') {
+ await store.set(STORAGE_KEYS.access, 'new') // the new pair lands while this is in flight
+ throw httpError(401, config)
+ }
+ return ok(config)
+ }
+
+ await expect(client.userAPI.me()).resolves.toBeDefined()
+
+ expect(refreshes).toBe(0)
+ expect(wasSignedOut()).toBe(false)
+ })
+
+ it('does not sign out when a refresh with the old token is refused as the new pair lands', async () => {
+ const { store, client, wasSignedOut } = await setup()
+ client.api.defaults.adapter = async (config: any) => {
+ if (config.headers.Authorization === 'Bearer old') throw httpError(401, config)
+ return ok(config)
+ }
+ axios.defaults.adapter = (async (config: any) => {
+ await store.set(STORAGE_KEYS.access, 'new')
+ await store.set(STORAGE_KEYS.refresh, 'new-refresh')
+ throw httpError(401, config)
+ }) as any
+
+ await expect(client.userAPI.me()).resolves.toBeDefined()
+
+ expect(wasSignedOut()).toBe(false)
+ expect(await store.get(STORAGE_KEYS.access)).toBe('new')
+ expect(await store.get(STORAGE_KEYS.refresh)).toBe('new-refresh')
+ })
+
+ it('still signs out when the session really was revoked and nothing newer exists', async () => {
+ const { store, client, wasSignedOut } = await setup()
+ client.api.defaults.adapter = async (config: any) => { throw httpError(401, config) }
+ axios.defaults.adapter = (async (config: any) => { throw httpError(401, config) }) as any
+
+ await expect(client.userAPI.me()).rejects.toBeDefined()
+
+ expect(wasSignedOut()).toBe(true)
+ expect(await store.get(STORAGE_KEYS.access)).toBeNull()
+ expect(await store.get(STORAGE_KEYS.refresh)).toBeNull()
+ })
+})
diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.ts
index 120cefd..db826c5 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -191,6 +191,18 @@ export function createClient(
return refreshInFlight
}
+ // A password or email change makes the server reject every token minted before it, and the
+ // device that made the change stores its replacement pair only a moment after the server
+ // commits. A request already in flight carries the old access token, so it can 401 into
+ // that gap — and a refresh from there would present the old refresh token, fail the same
+ // check, and sign out the very device the change was meant to keep signed in. If storage
+ // already holds a different access token than the one the request carried, the session
+ // moved on under it: retry with that token instead of treating the 401 as a revocation.
+ const newerAccessToken = async (sent: unknown): Promise<string | null> => {
+ const stored = await storage.get(STORAGE_KEYS.access)
+ return stored && sent !== `Bearer ${stored}` ? stored : null
+ }
+
api.interceptors.response.use(
(response) => response,
async (error) => {
@@ -204,6 +216,12 @@ export function createClient(
const isCredentialCheck = url.includes('/auth/') || url.includes('/me/password') || url.includes('/me/email')
if (error.response?.status === 401 && !original._retry && !isCredentialCheck) {
original._retry = true
+ const sent = original.headers?.Authorization
+ const caughtUp = await newerAccessToken(sent)
+ if (caughtUp) {
+ original.headers.Authorization = `Bearer ${caughtUp}`
+ return api(original)
+ }
try {
// Set the header from the token this call returns rather than letting the
// request interceptor re-read storage: a queued retry that reads storage can
@@ -212,6 +230,11 @@ export function createClient(
original.headers.Authorization = `Bearer ${newToken}`
return api(original)
} catch (refreshError) {
+ const late = sessionWasRevoked(refreshError) ? await newerAccessToken(sent) : null
+ if (late) {
+ original.headers.Authorization = `Bearer ${late}`
+ return api(original)
+ }
if (sessionWasRevoked(refreshError)) {
await storage.remove(STORAGE_KEYS.access)
await storage.remove(STORAGE_KEYS.refresh)
diff --git a/site/src/content/docs/configuration.md b/site/src/content/docs/configuration.md
index 70d19b8..68174e2 100644
--- a/site/src/content/docs/configuration.md
+++ b/site/src/content/docs/configuration.md
@@ -95,9 +95,11 @@ Changing it **signs you out everywhere else**. The device you changed it on stay
is deliberate — a password change is what you reach for when you think someone else has a session,
so it has to actually end their session. Sign back in on your other devices with the new password.
-Other devices stop as soon as their current access token expires, which is `JWT_EXPIRY` seconds
-(one hour by default). Raising `JWT_EXPIRY` widens that window by exactly the same amount, so a
-long expiry trades a little convenience for a longer tail after a password change.
+Other devices stop on their next request to the server: it checks every request against the account's
+current session version, so a device that was signed out gets a 401, fails to refresh, and drops to
+the sign-in screen. A device that cannot reach the server at that moment, say on poor wifi, stays on
+its old screens until it can. `JWT_EXPIRY` only sets how often a healthy session re-mints its access
+token, not how long a revoked one lingers.
## Changing your email
@@ -112,8 +114,8 @@ change the case of your own address. The address is stored exactly as you type i
Like a password change it **signs you out everywhere else**. The device you changed it on stays
signed in, and you sign in with the new address from now on. The old one stops working at once.
Lyftr cannot email the old address, so ending the other sessions is how a change made from a session
-that was not yours gets contained. Other devices stop when their current access token expires, the
-same window as a password change. Changing only the letter case, say `carter@` to `Carter@`, is the
+that was not yours gets contained. Other devices stop on their next request to the server, as with a
+password change. Changing only the letter case, say `carter@` to `Carter@`, is the
one exception: sign-in already ignores case, so nothing needs containing and no session ends.
## If you forget your password
@@ -183,9 +185,8 @@ you do not want. The case-insensitive index is created on the next start.
If it is the only account, the command warns first: under `REGISTRATION=first-user` whoever registers
next becomes the owner, and under `REGISTRATION=closed` nobody can sign in or register. Take a backup
-before you run it — see [Backups](/backups/). A device still signed in to the deleted account keeps its
-access token until that expires (up to an hour): reads come back empty and writes fail, and it is signed
-out when it next refreshes.
+before you run it — see [Backups](/backups/). A device still signed in to the deleted account is signed out on
+its next request to the server.
Piping the exact address also works, with `-T`: `echo [email protected] | docker compose exec -T backend ./lyftr-api delete-account [email protected]`.