Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

fix: cap oauth registration bodies and revoke refresh-token families on replay (#921)

Aldino Kemaldd9d72797b14
diff --git a/docs/mcp-oauth.md b/docs/mcp-oauth.md
index 34f8e1a3..2da3aaeb 100644
--- a/docs/mcp-oauth.md
+++ b/docs/mcp-oauth.md
@@ -111,7 +111,7 @@ The implementation intentionally uses opaque tokens rather than JWTs:
- the OAuth `resource` value is bound to the canonical MCP resource at authorization and checked when access tokens are used; token requests may omit `resource`, in which case the resource bound to the code or refresh-token family is used, while a supplied value must match;
- successful authorization responses include RFC 9207 `iss` for authorization-server mix-up protection.
-Expired authorization codes and tokens are removed opportunistically during OAuth writes so their rows do not accumulate indefinitely. SQLite can reuse the freed pages; shrinking the file itself still requires normal SQLite maintenance such as `VACUUM` while GOWA is stopped.
+Expired authorization codes and tokens are removed opportunistically during OAuth writes so their rows do not accumulate indefinitely. A rotated refresh token is kept for at most one more refresh-token lifetime (30 days) after it expires, and only while its family still has a live token, so replaying it still revokes that family. SQLite can reuse the freed pages; shrinking the file itself still requires normal SQLite maintenance such as `VACUUM` while GOWA is stopped.
No OAuth token is accepted as authentication for the normal REST/UI routes. OAuth only extends the MCP authentication surface.
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 9ee6c1a5..8510ca56 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -97,6 +97,9 @@ func restServer(_ *cobra.Command, _ []string) {
if config.AppBasePath != "" {
webhookPath = config.AppBasePath + webhookPath
}
+ // Both webhook routes read the body before checking a secret, so refuse
+ // compressed bodies Fiber would expand up to the app BodyLimit.
+ app.Use(webhookPath, middleware.RejectCompressedBody())
// In front of both webhook routes: a Chatwoot-signed request is only
// remembered as delivered once it has been answered 2xx.
app.Use(webhookPath, rest.ChatwootWebhookReplayGuard())
diff --git a/src/ui/mcp/oauth/security_test.go b/src/ui/mcp/oauth/security_test.go
index 4668f4dd..d2d07a37 100644
--- a/src/ui/mcp/oauth/security_test.go
+++ b/src/ui/mcp/oauth/security_test.go
@@ -1,6 +1,8 @@
package oauth
import (
+ "bytes"
+ "compress/gzip"
"crypto/sha256"
"encoding/base64"
"encoding/json"
@@ -359,3 +361,71 @@ func TestOAuthBodyCapLeavesOtherRoutesAlone(t *testing.T) {
assert.Equal(t, fiber.StatusOK, resp.StatusCode)
require.NoError(t, resp.Body.Close())
}
+
+func TestOAuthPOSTRejectsCompressedBodiesBeforeDecode(t *testing.T) {
+ valid := []byte(`{"client_name":"Gzip","redirect_uris":["https://example.com/callback"],"application_type":"web","token_endpoint_auth_method":"none"}`)
+ oversized := []byte(`{"client_name":"Gzip","redirect_uris":["https://example.com/callback"],"padding":"` + strings.Repeat("a", maxOAuthBodyBytes) + `"}`)
+ require.Greater(t, len(oversized), maxOAuthBodyBytes)
+ oversizedGzip := gzipBytes(t, oversized)
+ validGzip := gzipBytes(t, valid)
+ require.Less(t, len(oversizedGzip), maxOAuthBodyBytes, "compressed body must fit under the raw cap")
+ require.Less(t, len(validGzip), maxOAuthBodyBytes)
+
+ cases := []struct {
+ name string
+ path string
+ contentType string
+ encoding string
+ extraEncoding string
+ body []byte
+ }{
+ {name: "identity then gzip header lines", path: "/oauth/register", contentType: "application/json", encoding: "identity", extraEncoding: "gzip", body: valid},
+ {name: "gzip register larger than 16KiB decoded", path: "/oauth/register", contentType: "application/json", encoding: "gzip", body: oversizedGzip},
+ {name: "gzip register that would otherwise succeed", path: "/oauth/register", contentType: "application/json", encoding: "gzip", body: validGzip},
+ {name: "x-gzip register", path: "/oauth/register", contentType: "application/json", encoding: "x-gzip", body: validGzip},
+ {name: "gzip token", path: "/oauth/token", contentType: "application/x-www-form-urlencoded", encoding: "gzip", body: gzipBytes(t, []byte("grant_type=refresh_token&client_id=client&refresh_token=token"))},
+ {name: "deflate register", path: "/oauth/register", contentType: "application/json", encoding: "deflate", body: valid},
+ {name: "br register", path: "/oauth/register", contentType: "application/json", encoding: "br", body: valid},
+ {name: "gzip authorize", path: "/oauth/authorize", contentType: "application/x-www-form-urlencoded", encoding: "gzip", body: gzipBytes(t, []byte("response_type=code&username=user&password=secret"))},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ srv, app := newOAuthTestServer(t, testIssuer, testResource)
+ req := httptest.NewRequest("POST", tc.path, bytes.NewReader(tc.body))
+ req.Header.Set("Content-Type", tc.contentType)
+ req.Header.Set("Content-Encoding", tc.encoding)
+ if tc.extraEncoding != "" {
+ req.Header.Add("Content-Encoding", tc.extraEncoding)
+ }
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusUnsupportedMediaType, resp.StatusCode)
+ assertOAuthError(t, resp, "invalid_request")
+
+ var clients int
+ require.NoError(t, srv.store.db.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM oauth_clients`).Scan(&clients))
+ assert.Zero(t, clients)
+ })
+ }
+
+ t.Run("identity encoding still registers", func(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+ req := httptest.NewRequest("POST", "/oauth/register", bytes.NewReader(valid))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Content-Encoding", "identity")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusCreated, resp.StatusCode)
+ require.NoError(t, resp.Body.Close())
+ })
+}
+
+func gzipBytes(t *testing.T, raw []byte) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zw := gzip.NewWriter(&buf)
+ _, err := zw.Write(raw)
+ require.NoError(t, err)
+ require.NoError(t, zw.Close())
+ return buf.Bytes()
+}
diff --git a/src/ui/mcp/oauth/server.go b/src/ui/mcp/oauth/server.go
index fff6e295..feceac30 100644
--- a/src/ui/mcp/oauth/server.go
+++ b/src/ui/mcp/oauth/server.go
@@ -175,8 +175,11 @@ func (s *Server) RegisterPublic(app *fiber.App) {
app.Post(s.issuerEndpointPath("/oauth/token"), s.token)
}
-// limitPublicPOSTBodies applies the OAuth cap in fasthttp immediately after
+// limitPublicPOSTBodies applies maxOAuthBodyBytes in fasthttp immediately after
// headers are received, before the unauthenticated request body is buffered.
+// The cap is the raw on-the-wire size. Fiber decompresses Content-Encoding
+// later, inside Body and Bind, up to the separate application-wide body limit,
+// so the OAuth POST handlers reject compressed encodings before reading a body.
func (s *Server) limitPublicPOSTBodies(app *fiber.App) {
paths := []string{
routingPathKey(s.issuerEndpointPath("/oauth/register")),
@@ -287,6 +290,9 @@ func (s *Server) protectedResourceMetadata(c fiber.Ctx) error {
func (s *Server) registerClient(c fiber.Ctx) error {
s.setNoStore(c)
+ if rejected, err := rejectCompressedOAuthBody(c); rejected {
+ return err
+ }
if len(c.Body()) > maxOAuthBodyBytes {
return oauthError(c, fiber.StatusRequestEntityTooLarge, "invalid_client_metadata", "registration document is too large")
}
@@ -384,6 +390,9 @@ func (s *Server) authorizeGET(c fiber.Ctx) error {
}
func (s *Server) authorizePOST(c fiber.Ctx) error {
+ if rejected, err := rejectCompressedOAuthBody(c); rejected {
+ return err
+ }
var req authorizationRequest
if err := c.Bind().Body(&req); err != nil {
return oauthError(c, fiber.StatusBadRequest, "invalid_request", "invalid authorization request")
@@ -426,6 +435,9 @@ func (s *Server) authorizePOST(c fiber.Ctx) error {
func (s *Server) token(c fiber.Ctx) error {
s.setNoStore(c)
+ if rejected, err := rejectCompressedOAuthBody(c); rejected {
+ return err
+ }
var req tokenRequest
if err := c.Bind().Body(&req); err != nil {
return oauthError(c, fiber.StatusBadRequest, "invalid_request", "invalid token request")
@@ -750,6 +762,34 @@ func decodeBasicCredentials(encoded string) (string, string, bool) {
return username, password, true
}
+// rejectCompressedOAuthBody refuses every Content-Encoding other than identity.
+// Registration, authorize, and token bodies are small identity-encoded JSON or
+// form documents. Calling Body or Bind first would expand gzip, deflate, or
+// brotli up to the application-wide limit instead of maxOAuthBodyBytes.
+//
+// The bool is true when a response was written. oauthError's JSON write returns
+// nil, so callers must stop on that bool instead of only checking the error.
+func rejectCompressedOAuthBody(c fiber.Ctx) (bool, error) {
+ // Every header line counts, not only the first one c.Get returns.
+ for _, value := range c.Request().Header.PeekAll(fiber.HeaderContentEncoding) {
+ if compressedContentEncoding(string(value)) {
+ return true, oauthError(c, fiber.StatusUnsupportedMediaType, "invalid_request", "compressed request bodies are not supported")
+ }
+ }
+ return false, nil
+}
+
+func compressedContentEncoding(header string) bool {
+ for _, part := range strings.Split(header, ",") {
+ coding := strings.ToLower(strings.TrimSpace(part))
+ if coding == "" || coding == "identity" {
+ continue
+ }
+ return true
+ }
+ return false
+}
+
func oauthError(c fiber.Ctx, status int, code, description string) error {
c.Set(fiber.HeaderCacheControl, "no-store")
c.Set(fiber.HeaderPragma, "no-cache")
diff --git a/src/ui/mcp/oauth/store.go b/src/ui/mcp/oauth/store.go
index 91ababf9..d2687e7c 100644
--- a/src/ui/mcp/oauth/store.go
+++ b/src/ui/mcp/oauth/store.go
@@ -70,6 +70,7 @@ CREATE TABLE IF NOT EXISTS oauth_tokens (
FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_oauth_tokens_family ON oauth_tokens(family_id);
+CREATE INDEX IF NOT EXISTS idx_oauth_tokens_family_live ON oauth_tokens(family_id, revoked_at, expires_at);
CREATE INDEX IF NOT EXISTS idx_oauth_tokens_expires_at ON oauth_tokens(expires_at);
CREATE INDEX IF NOT EXISTS idx_oauth_tokens_client_id ON oauth_tokens(client_id);
`
@@ -336,10 +337,11 @@ func (s *store) rotateRefreshToken(
return TokenPair{}, err
}
defer func() { _ = tx.Rollback() }()
- if err := cleanupExpiredTx(ctx, tx, now); err != nil {
- return TokenPair{}, err
- }
+ // Load the presented refresh token before cleanupExpiredTx. Cleanup removes
+ // expired rows, and a consumed ancestor is the only record that ties a
+ // replay to its family. Deleting that row first turns the replay into a
+ // miss and leaves the replacement usable.
var (
familyID string
clientID string
@@ -367,11 +369,12 @@ WHERE token_hash = ? AND token_type = 'refresh'`, hashSecret(req.RefreshToken)).
if err != nil {
return TokenPair{}, err
}
+ // Reuse of a revoked or consumed token revokes the whole family, including
+ // when that ancestor is already past expires_at. An expired refresh token
+ // that was never consumed is not an ancestor and is rejected below without
+ // revoking any family.
if revokedAt.Valid {
- if _, err := tx.ExecContext(ctx, `
-UPDATE oauth_tokens
-SET revoked_at = ?
-WHERE family_id = ? AND revoked_at IS NULL`, now.Unix(), familyID); err != nil {
+ if err := revokeRefreshFamilyTx(ctx, tx, familyID, now); err != nil {
return TokenPair{}, err
}
if err := tx.Commit(); err != nil {
@@ -403,17 +406,53 @@ WHERE token_hash = ? AND token_type = 'refresh' AND revoked_at IS NULL`,
if err != nil {
return TokenPair{}, err
}
+ if err := cleanupExpiredTx(ctx, tx, now); err != nil {
+ return TokenPair{}, err
+ }
if err := tx.Commit(); err != nil {
return TokenPair{}, err
}
return pair, nil
}
+func revokeRefreshFamilyTx(ctx context.Context, tx *sql.Tx, familyID string, now time.Time) error {
+ if _, err := tx.ExecContext(ctx, `
+UPDATE oauth_tokens
+SET revoked_at = ?
+WHERE family_id = ? AND revoked_at IS NULL`, now.Unix(), familyID); err != nil {
+ return err
+ }
+ return nil
+}
+
+// cleanupExpiredTx drops expired authorization codes and tokens. A consumed
+// refresh-token hash is kept while the family still has a live descendant so a
+// later replay can revoke that family, but for no more than one refresh-token
+// lifetime after it expires. Expired refresh tokens that were never consumed
+// are not ancestors and are deleted with the other expired rows.
func cleanupExpiredTx(ctx context.Context, tx *sql.Tx, now time.Time) error {
if _, err := tx.ExecContext(ctx, `DELETE FROM oauth_authorization_codes WHERE expires_at <= ?`, now.Unix()); err != nil {
return fmt.Errorf("delete expired authorization codes: %w", err)
}
- if _, err := tx.ExecContext(ctx, `DELETE FROM oauth_tokens WHERE expires_at <= ?`, now.Unix()); err != nil {
+ if _, err := tx.ExecContext(ctx, `
+DELETE FROM oauth_tokens
+WHERE token_hash IN (
+ SELECT expired.token_hash
+ FROM oauth_tokens AS expired
+ WHERE expired.expires_at <= ?
+ AND NOT (
+ expired.token_type = 'refresh'
+ AND expired.revoked_at IS NOT NULL
+ AND expired.expires_at > ?
+ AND EXISTS (
+ SELECT 1
+ FROM oauth_tokens AS live
+ WHERE live.family_id = expired.family_id
+ AND live.revoked_at IS NULL
+ AND live.expires_at > ?
+ )
+ )
+)`, now.Unix(), now.Add(-refreshTokenTTL).Unix(), now.Unix()); err != nil {
return fmt.Errorf("delete expired oauth tokens: %w", err)
}
return nil
diff --git a/src/ui/mcp/oauth/store_test.go b/src/ui/mcp/oauth/store_test.go
index cfc6af96..4acb50ce 100644
--- a/src/ui/mcp/oauth/store_test.go
+++ b/src/ui/mcp/oauth/store_test.go
@@ -194,3 +194,196 @@ func TestStoreRegistrationRateLimitUsesDurableWindow(t *testing.T) {
require.NoError(t, store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM oauth_clients`).Scan(&clients))
assert.Equal(t, 2, clients)
}
+
+func TestReplayOfExpiredConsumedRefreshRevokesDescendants(t *testing.T) {
+ ctx := context.Background()
+ dbPath := filepath.Join(t.TempDir(), "oauth.db")
+ store, err := openStore("file:" + filepath.ToSlash(dbPath))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, store.Close()) })
+
+ now := time.Date(2026, 8, 21, 12, 0, 0, 0, time.UTC)
+ client := Client{ID: "client-1", Name: "Claude", RedirectURIs: []string{testRedirect}, ApplicationType: "web", TokenEndpointAuthMethod: "none", CreatedAt: now}
+ require.NoError(t, store.createClient(ctx, client))
+
+ verifier := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~abc"
+ sum := sha256.Sum256([]byte(verifier))
+ code, err := store.issueAuthorizationCode(ctx, AuthorizationGrant{
+ ClientID: client.ID, Subject: "user", RedirectURI: testRedirect,
+ CodeChallenge: base64.RawURLEncoding.EncodeToString(sum[:]),
+ Resource: testResource, Scope: "mcp",
+ }, now, 5*time.Minute)
+ require.NoError(t, err)
+ ancestor, err := store.exchangeAuthorizationCode(ctx, CodeExchange{
+ ClientID: client.ID, Code: code, RedirectURI: testRedirect,
+ CodeVerifier: verifier, Resource: testResource,
+ }, now, time.Hour, 30*24*time.Hour)
+ require.NoError(t, err)
+
+ replacement, err := store.rotateRefreshToken(ctx, RefreshExchange{
+ ClientID: client.ID, RefreshToken: ancestor.RefreshToken, Resource: testResource,
+ }, now.Add(time.Minute), time.Hour, 30*24*time.Hour)
+ require.NoError(t, err)
+ child, err := store.rotateRefreshToken(ctx, RefreshExchange{
+ ClientID: client.ID, RefreshToken: replacement.RefreshToken, Resource: testResource,
+ }, now.Add(2*time.Minute), time.Hour, 30*24*time.Hour)
+ require.NoError(t, err)
+ require.NotEqual(t, ancestor.RefreshToken, replacement.RefreshToken)
+ require.NotEqual(t, replacement.RefreshToken, child.RefreshToken)
+
+ replayAt := now.Add(3 * time.Minute)
+ _, err = store.db.ExecContext(ctx, `
+UPDATE oauth_tokens SET expires_at = ? WHERE token_hash = ?`,
+ replayAt.Add(-time.Minute).Unix(), hashSecret(ancestor.RefreshToken))
+ require.NoError(t, err)
+ _, err = store.db.ExecContext(ctx, `
+INSERT INTO oauth_tokens (
+ token_hash, token_type, family_id, client_id, subject, resource, scope,
+ expires_at, created_at
+) VALUES (?, 'refresh', 'other-family', ?, 'user', ?, 'mcp', ?, ?)`,
+ "expired-unused", client.ID, testResource, replayAt.Add(-time.Minute).Unix(), now.Unix())
+ require.NoError(t, err)
+
+ _, err = store.issueAuthorizationCode(ctx, AuthorizationGrant{
+ ClientID: client.ID, Subject: "user", RedirectURI: testRedirect,
+ CodeChallenge: "challenge", Resource: testResource, Scope: "mcp",
+ }, replayAt, time.Minute)
+ require.NoError(t, err)
+
+ var ancestorLeft, unusedLeft int
+ require.NoError(t, store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM oauth_tokens WHERE token_hash = ?`, hashSecret(ancestor.RefreshToken)).Scan(&ancestorLeft))
+ require.NoError(t, store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM oauth_tokens WHERE token_hash = ?`, "expired-unused").Scan(&unusedLeft))
+ assert.Equal(t, 1, ancestorLeft, "cleanup must keep an expired consumed ancestor while descendants are live")
+ assert.Zero(t, unusedLeft, "cleanup must still drop an expired refresh token that was never consumed")
+
+ _, err = store.rotateRefreshToken(ctx, RefreshExchange{
+ ClientID: client.ID, RefreshToken: ancestor.RefreshToken,
+ }, replayAt, time.Hour, 30*24*time.Hour)
+ assert.ErrorIs(t, err, ErrRefreshReuse)
+
+ for _, token := range []string{replacement.RefreshToken, child.RefreshToken} {
+ _, refreshErr := store.rotateRefreshToken(ctx, RefreshExchange{
+ ClientID: client.ID, RefreshToken: token,
+ }, replayAt, time.Hour, 30*24*time.Hour)
+ assert.ErrorIs(t, refreshErr, ErrRefreshReuse)
+ }
+ _, err = store.validateAccessToken(ctx, replacement.AccessToken, testResource, replayAt)
+ assert.ErrorIs(t, err, ErrInvalidToken)
+ _, err = store.validateAccessToken(ctx, child.AccessToken, testResource, replayAt)
+ assert.ErrorIs(t, err, ErrInvalidToken)
+
+ _, err = store.issueAuthorizationCode(ctx, AuthorizationGrant{
+ ClientID: client.ID, Subject: "user", RedirectURI: testRedirect,
+ CodeChallenge: "challenge", Resource: testResource, Scope: "mcp",
+ }, replayAt, time.Minute)
+ require.NoError(t, err)
+ require.NoError(t, store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM oauth_tokens WHERE token_hash = ?`, hashSecret(ancestor.RefreshToken)).Scan(&ancestorLeft))
+ assert.Zero(t, ancestorLeft, "consumed ancestor can be removed once its family has no live descendants")
+}
+
+func TestExpiredUnusedRefreshDoesNotRevokeActiveFamily(t *testing.T) {
+ ctx := context.Background()
+ dbPath := filepath.Join(t.TempDir(), "oauth.db")
+ store, err := openStore("file:" + filepath.ToSlash(dbPath))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, store.Close()) })
+
+ now := time.Date(2026, 8, 21, 13, 0, 0, 0, time.UTC)
+ client := Client{ID: "client-1", Name: "Claude", RedirectURIs: []string{testRedirect}, ApplicationType: "web", TokenEndpointAuthMethod: "none", CreatedAt: now}
+ require.NoError(t, store.createClient(ctx, client))
+
+ verifier := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~abc"
+ sum := sha256.Sum256([]byte(verifier))
+ code, err := store.issueAuthorizationCode(ctx, AuthorizationGrant{
+ ClientID: client.ID, Subject: "user", RedirectURI: testRedirect,
+ CodeChallenge: base64.RawURLEncoding.EncodeToString(sum[:]),
+ Resource: testResource, Scope: "mcp",
+ }, now, 5*time.Minute)
+ require.NoError(t, err)
+ active, err := store.exchangeAuthorizationCode(ctx, CodeExchange{
+ ClientID: client.ID, Code: code, RedirectURI: testRedirect,
+ CodeVerifier: verifier, Resource: testResource,
+ }, now, time.Hour, 30*24*time.Hour)
+ require.NoError(t, err)
+
+ replayAt := now.Add(time.Minute)
+ unused := "expired-unused-refresh"
+ _, err = store.db.ExecContext(ctx, `
+INSERT INTO oauth_tokens (
+ token_hash, token_type, family_id, client_id, subject, resource, scope,
+ expires_at, created_at
+) VALUES (?, 'refresh', 'expired-family', ?, 'user', ?, 'mcp', ?, ?)`,
+ hashSecret(unused), client.ID, testResource, replayAt.Add(-time.Minute).Unix(), now.Unix())
+ require.NoError(t, err)
+
+ _, err = store.rotateRefreshToken(ctx, RefreshExchange{
+ ClientID: client.ID, RefreshToken: unused,
+ }, replayAt, time.Hour, 30*24*time.Hour)
+ assert.ErrorIs(t, err, ErrInvalidGrant)
+
+ rotated, err := store.rotateRefreshToken(ctx, RefreshExchange{
+ ClientID: client.ID, RefreshToken: active.RefreshToken, Resource: testResource,
+ }, replayAt, time.Hour, 30*24*time.Hour)
+ require.NoError(t, err)
+ assert.NotEmpty(t, rotated.RefreshToken)
+ assert.NotEqual(t, active.RefreshToken, rotated.RefreshToken)
+}
+
+func TestConsumedRefreshRetentionIsBoundedAcrossRotations(t *testing.T) {
+ ctx := context.Background()
+ dbPath := filepath.Join(t.TempDir(), "oauth.db")
+ store, err := openStore("file:" + filepath.ToSlash(dbPath))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, store.Close()) })
+
+ now := time.Date(2026, 8, 21, 14, 0, 0, 0, time.UTC)
+ client := Client{ID: "client-1", Name: "Claude", RedirectURIs: []string{testRedirect}, ApplicationType: "web", TokenEndpointAuthMethod: "none", CreatedAt: now}
+ require.NoError(t, store.createClient(ctx, client))
+
+ verifier := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~abc"
+ sum := sha256.Sum256([]byte(verifier))
+ code, err := store.issueAuthorizationCode(ctx, AuthorizationGrant{
+ ClientID: client.ID, Subject: "user", RedirectURI: testRedirect,
+ CodeChallenge: base64.RawURLEncoding.EncodeToString(sum[:]),
+ Resource: testResource, Scope: "mcp",
+ }, now, 5*time.Minute)
+ require.NoError(t, err)
+ pair, err := store.exchangeAuthorizationCode(ctx, CodeExchange{
+ ClientID: client.ID, Code: code, RedirectURI: testRedirect,
+ CodeVerifier: verifier, Resource: testResource,
+ }, now, time.Hour, refreshTokenTTL)
+ require.NoError(t, err)
+
+ // Rotate ten times per refresh-token lifetime for three lifetimes. A consumed
+ // refresh token is kept at most one lifetime past its expiry, so only the 20
+ // refresh tokens issued during the last two lifetimes remain.
+ interval := refreshTokenTTL / 10
+ for i := 1; i <= 30; i++ {
+ pair, err = store.rotateRefreshToken(ctx, RefreshExchange{
+ ClientID: client.ID, RefreshToken: pair.RefreshToken,
+ }, now.Add(time.Duration(i)*interval), time.Hour, refreshTokenTTL)
+ require.NoError(t, err)
+ }
+
+ var refreshRows int
+ require.NoError(t, store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM oauth_tokens WHERE token_type = 'refresh'`).Scan(&refreshRows))
+ assert.Equal(t, 20, refreshRows)
+}
+
+func TestLiveFamilyLookupUsesCompositeIndex(t *testing.T) {
+ ctx := context.Background()
+ dbPath := filepath.Join(t.TempDir(), "oauth.db")
+ store, err := openStore("file:" + filepath.ToSlash(dbPath))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, store.Close()) })
+
+ // cleanupExpiredTx runs this lookup for every expired consumed refresh token,
+ // so it must not scan the whole family through the family_id-only index.
+ var id, parent, notUsed int
+ var detail string
+ require.NoError(t, store.db.QueryRowContext(ctx, `
+EXPLAIN QUERY PLAN
+SELECT 1 FROM oauth_tokens AS live
+WHERE live.family_id = ? AND live.revoked_at IS NULL AND live.expires_at > ?`, "family", 0).Scan(&id, &parent, &notUsed, &detail))
+ assert.Contains(t, detail, "idx_oauth_tokens_family_live")
+}
diff --git a/src/ui/rest/middleware/compressed_body.go b/src/ui/rest/middleware/compressed_body.go
new file mode 100644
index 00000000..1ea75e09
--- /dev/null
+++ b/src/ui/rest/middleware/compressed_body.go
@@ -0,0 +1,30 @@
+package middleware
+
+import (
+ "strings"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/gofiber/fiber/v3"
+)
+
+// RejectCompressedBody answers 415 for any Content-Encoding other than
+// identity. Mount it in front of routes that read a body before authenticating:
+// Fiber would otherwise expand gzip, deflate, brotli, or zstd up to the
+// application-wide BodyLimit before the handler can refuse the request.
+func RejectCompressedBody() fiber.Handler {
+ return func(c fiber.Ctx) error {
+ // Every header line counts, not only the first one c.Get returns.
+ for _, value := range c.Request().Header.PeekAll(fiber.HeaderContentEncoding) {
+ for _, part := range strings.Split(string(value), ",") {
+ if coding := strings.ToLower(strings.TrimSpace(part)); coding != "" && coding != "identity" {
+ return c.Status(fiber.StatusUnsupportedMediaType).JSON(utils.ResponseData{
+ Status: fiber.StatusUnsupportedMediaType,
+ Code: "UNSUPPORTED_CONTENT_ENCODING",
+ Message: "compressed request bodies are not supported",
+ })
+ }
+ }
+ }
+ return c.Next()
+ }
+}
diff --git a/src/ui/rest/middleware/compressed_body_test.go b/src/ui/rest/middleware/compressed_body_test.go
new file mode 100644
index 00000000..a6d2d8b3
--- /dev/null
+++ b/src/ui/rest/middleware/compressed_body_test.go
@@ -0,0 +1,48 @@
+package middleware
+
+import (
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gofiber/fiber/v3"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestRejectCompressedBody(t *testing.T) {
+ app := fiber.New()
+ app.Use("/hook", RejectCompressedBody())
+ reached := 0
+ handler := func(c fiber.Ctx) error {
+ reached++
+ return c.SendString("ok")
+ }
+ app.Post("/hook", handler)
+ app.Post("/hook/:device_id", handler)
+
+ tests := []struct {
+ path string
+ encodings []string
+ want int
+ }{
+ {"/hook", nil, fiber.StatusOK},
+ {"/hook", []string{"identity"}, fiber.StatusOK},
+ {"/hook", []string{"gzip"}, fiber.StatusUnsupportedMediaType},
+ {"/hook", []string{"BR"}, fiber.StatusUnsupportedMediaType},
+ {"/hook", []string{"identity, zstd"}, fiber.StatusUnsupportedMediaType},
+ {"/hook", []string{"identity", "gzip"}, fiber.StatusUnsupportedMediaType},
+ {"/hook/dev1", []string{"deflate"}, fiber.StatusUnsupportedMediaType},
+ }
+ for _, tt := range tests {
+ reached = 0
+ req := httptest.NewRequest(fiber.MethodPost, tt.path, strings.NewReader(`{}`))
+ for _, encoding := range tt.encodings {
+ req.Header.Add(fiber.HeaderContentEncoding, encoding)
+ }
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ assert.Equal(t, tt.want, resp.StatusCode, "%s %q", tt.path, tt.encodings)
+ assert.Equal(t, tt.want == fiber.StatusOK, reached == 1, "%s %q handler reached", tt.path, tt.encodings)
+ }
+}