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.

feat(mcp): add embedded OAuth 2.1 authorization (#802)

Aldino Kemaleeb30bb632bb
diff --git a/docs/mcp-oauth.md b/docs/mcp-oauth.md
new file mode 100644
index 00000000..1405e5f7
--- /dev/null
+++ b/docs/mcp-oauth.md
@@ -0,0 +1,133 @@
+# MCP OAuth
+
+GOWA can embed an OAuth 2.1 authorization server for its streamable-HTTP MCP endpoint. This is useful for remote MCP clients such as Claude custom connectors that cannot attach GOWA's existing Basic Auth header themselves.
+
+OAuth is **disabled by default**. When it is enabled:
+
+- `/mcp` accepts either `Authorization: Bearer <token>` or the existing Basic Auth credentials.
+- The browser authorization page authenticates against the same `APP_BASIC_AUTH` accounts used by the REST API; there is no second user database.
+- OAuth clients, authorization codes, and token hashes are persisted in `storages/oauth.db` by default.
+- Existing REST/UI authentication is unchanged.
+
+## Configuration
+
+A minimal public deployment without `APP_BASE_PATH` looks like this:
+
+```env
+APP_BASIC_AUTH=admin:replace-with-a-strong-password
+MCP_ENABLED=true
+MCP_OAUTH_ENABLED=true
+MCP_OAUTH_ISSUER_URL=https://gowa.example.com
+# Optional; defaults to issuer origin + APP_BASE_PATH + /mcp
+MCP_OAUTH_RESOURCE_URL=https://gowa.example.com/mcp
+```
+
+`MCP_OAUTH_ISSUER_URL` and the canonical MCP resource must be public HTTPS URLs. OAuth-enabled startup fails if `APP_BASIC_AUTH` is empty or the public URL configuration is invalid.
+
+The equivalent CLI flags are:
+
+```text
+--mcp-oauth-enabled
+--mcp-oauth-issuer-url
+--mcp-oauth-resource-url
+--mcp-oauth-db-uri
+```
+
+## Claude custom connector
+
+Expose the GOWA MCP resource over HTTPS, then use the canonical MCP URL when adding the custom connector:
+
+```text
+https://gowa.example.com/mcp
+```
+
+Claude can dynamically register itself with GOWA and start the authorization-code flow. The browser will show GOWA's authorization page; sign in with one of the users from `APP_BASIC_AUTH`. The page displays both the registered client name and the redirect hostname before credentials are submitted.
+
+GOWA implements RFC 7591 Dynamic Client Registration for compatibility with clients such as Claude. DCR is retained by the current MCP specification for backwards compatibility; GOWA does not advertise Client ID Metadata Document support until that mechanism is implemented.
+
+Because registration is unauthenticated, GOWA limits registration documents to 16 KiB, each redirect URI to 2 KiB, new registrations to 40 per hour, and stored dynamic clients to 1,000. Registrations that remain unused for 24 hours are pruned before accepting new clients. These durable global limits protect the OAuth SQLite database across restarts. If a deployment still reaches the client cap, remove obsolete rows from `oauth_clients` during a maintenance window or replace the OAuth database to start with a new authorization-server state; deleting clients also invalidates their grants and tokens.
+
+## `APP_BASE_PATH`
+
+For a deployment using:
+
+```env
+APP_BASE_PATH=/gowa
+MCP_OAUTH_ISSUER_URL=https://gowa.example.com/gowa
+```
+
+the default canonical resource is:
+
+```text
+https://gowa.example.com/gowa/mcp
+```
+
+OAuth endpoints are under the issuer path:
+
+```text
+https://gowa.example.com/gowa/oauth/authorize
+https://gowa.example.com/gowa/oauth/token
+https://gowa.example.com/gowa/oauth/register
+```
+
+RFC 8414 and RFC 9728 use **path-insertion** well-known URLs, not `APP_BASE_PATH/.well-known/...` URLs. The reverse proxy must therefore route these root paths to GOWA:
+
+```text
+https://gowa.example.com/.well-known/oauth-authorization-server/gowa
+https://gowa.example.com/.well-known/oauth-protected-resource/gowa/mcp
+```
+
+The MCP `401 Unauthorized` challenge includes the exact protected-resource metadata URL, so conforming clients do not have to guess it.
+
+## Cloudflare / reverse proxies
+
+The configured issuer and resource are the **public** URLs seen by the MCP client, not the container's internal address. For example, do not configure `http://gowa:3000` when the public endpoint is `https://gowa.example.com`.
+
+If Cloudflare Access, an authentication proxy, or a bot challenge sits in front of GOWA, make sure it does not replace the OAuth/MCP responses with its own interactive login or challenge. Claude must be able to reach:
+
+- the RFC well-known metadata paths;
+- `<issuer>/oauth/register`;
+- `<issuer>/oauth/authorize`;
+- `<issuer>/oauth/token`;
+- the canonical MCP resource itself.
+
+TLS termination at the reverse proxy is fine; `MCP_OAUTH_ISSUER_URL` and `MCP_OAUTH_RESOURCE_URL` must still describe their externally reachable HTTPS forms.
+
+The authorization form validates the same Basic Auth credentials as the rest of GOWA. Internet-facing deployments should apply per-IP failed-login rate limiting and logging at the reverse proxy for `<issuer>/oauth/authorize`, just as they should for the normal Basic Auth surface.
+
+## Security model
+
+The implementation intentionally uses opaque tokens rather than JWTs:
+
+- authorization codes, access tokens, and refresh tokens are generated with `crypto/rand`;
+- only SHA-256 hashes are persisted;
+- authorization codes are single-use and expire after 5 minutes;
+- access tokens expire after 1 hour;
+- refresh tokens rotate on each use;
+- reusing a rotated refresh token revokes the whole token family;
+- PKCE with `S256` is mandatory;
+- redirect URIs must exactly match the URI registered by the client, except that native loopback-IP clients may change only the port used for their local callback;
+- redirect URIs must use HTTPS, except `native` clients, which may use `http` with a loopback IP literal such as `http://127.0.0.1:PORT/callback` or `http://[::1]:PORT/callback`. For Claude Code compatibility, the exact hostname `localhost` is also accepted only with an explicit port; unlike loopback IP literals, a registered `localhost` redirect receives no dynamic-port exception and must match exactly during authorization;
+- the OAuth `resource` value is bound to the canonical MCP resource and checked when access tokens are used;
+- 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.
+
+No OAuth token is accepted as authentication for the normal REST/UI routes. OAuth only extends the MCP authentication surface.
+
+## Discovery checks
+
+For a root deployment, an unauthenticated MCP request should return a Bearer challenge pointing at protected-resource metadata:
+
+```bash
+curl -i -X POST https://gowa.example.com/mcp
+```
+
+Metadata can then be inspected directly:
+
+```bash
+curl https://gowa.example.com/.well-known/oauth-protected-resource/mcp
+curl https://gowa.example.com/.well-known/oauth-authorization-server
+```
+
+The authorization-server metadata advertises authorization-code and refresh-token grants, PKCE `S256`, and the DCR registration endpoint.
diff --git a/src/.env.example b/src/.env.example
index 98969284..c4c39ef8 100644
--- a/src/.env.example
+++ b/src/.env.example
@@ -23,6 +23,21 @@ APP_UI_GITHUB_TOKEN=
# (hex digest; each release ships a gowa-ui.html.sha256 asset)
APP_UI_ASSET_SHA256=
+# MCP / OAuth Settings
+MCP_ENABLED=true
+# OAuth is opt-in. It reuses APP_BASIC_AUTH accounts for the browser login and
+# lets /mcp accept OAuth Bearer tokens in addition to existing Basic Auth.
+MCP_OAUTH_ENABLED=false
+# Public HTTPS authorization-server issuer. Required when MCP_OAUTH_ENABLED=true.
+# Include APP_BASE_PATH when OAuth endpoints are also exposed under that path,
+# e.g. https://gowa.example.com/gowa.
+MCP_OAUTH_ISSUER_URL=
+# Optional canonical public MCP URL. When empty it is derived from the issuer
+# origin + APP_BASE_PATH + /mcp.
+MCP_OAUTH_RESOURCE_URL=
+# Dedicated OAuth SQLite state; clients, codes, and token hashes only.
+MCP_OAUTH_DB_URI=file:storages/oauth.db
+
# Database Settings
DB_URI=file:storages/whatsapp.db?_foreign_keys=on
DB_KEYS_URI=
diff --git a/src/cmd/mcp_oauth.go b/src/cmd/mcp_oauth.go
new file mode 100644
index 00000000..037d327c
--- /dev/null
+++ b/src/cmd/mcp_oauth.go
@@ -0,0 +1,139 @@
+package cmd
+
+import (
+ "crypto/subtle"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ uimcp "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/mcp"
+ mcpoauth "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/mcp/oauth"
+ "github.com/gofiber/fiber/v3"
+ "github.com/spf13/viper"
+)
+
+func init() {
+ rootCmd.PersistentFlags().BoolVar(
+ &config.McpOAuthEnabled,
+ "mcp-oauth-enabled",
+ config.McpOAuthEnabled,
+ "enable OAuth 2.1 for the MCP endpoint",
+ )
+ rootCmd.PersistentFlags().StringVar(
+ &config.McpOAuthIssuerURL,
+ "mcp-oauth-issuer-url",
+ config.McpOAuthIssuerURL,
+ "public HTTPS OAuth issuer URL, e.g. https://gowa.example.com",
+ )
+ rootCmd.PersistentFlags().StringVar(
+ &config.McpOAuthResourceURL,
+ "mcp-oauth-resource-url",
+ config.McpOAuthResourceURL,
+ "canonical public MCP resource URL; defaults to issuer origin + APP_BASE_PATH + /mcp",
+ )
+ rootCmd.PersistentFlags().StringVar(
+ &config.McpOAuthDBURI,
+ "mcp-oauth-db-uri",
+ config.McpOAuthDBURI,
+ "SQLite URI for OAuth clients, authorization codes, and tokens",
+ )
+}
+
+// loadMcpOAuthEnvConfig runs from restServer after Cobra has parsed flags. It
+// mirrors root.go's Viper binding while preserving the project's flag > env >
+// .env priority for the OAuth settings added in this feature.
+func loadMcpOAuthEnvConfig() {
+ flags := rootCmd.PersistentFlags()
+ if flag := flags.Lookup("mcp-oauth-enabled"); flag == nil || !flag.Changed {
+ if viper.IsSet("mcp_oauth_enabled") {
+ config.McpOAuthEnabled = viper.GetBool("mcp_oauth_enabled")
+ }
+ }
+ if flag := flags.Lookup("mcp-oauth-issuer-url"); flag == nil || !flag.Changed {
+ if value := strings.TrimSpace(viper.GetString("mcp_oauth_issuer_url")); value != "" {
+ config.McpOAuthIssuerURL = value
+ }
+ }
+ if flag := flags.Lookup("mcp-oauth-resource-url"); flag == nil || !flag.Changed {
+ if value := strings.TrimSpace(viper.GetString("mcp_oauth_resource_url")); value != "" {
+ config.McpOAuthResourceURL = value
+ }
+ }
+ if flag := flags.Lookup("mcp-oauth-db-uri"); flag == nil || !flag.Changed {
+ if value := strings.TrimSpace(viper.GetString("mcp_oauth_db_uri")); value != "" {
+ config.McpOAuthDBURI = value
+ }
+ }
+}
+
+// registerMcpOAuth must run before the application's global Basic Auth
+// middleware is installed so standards discovery, authorization, registration,
+// and token endpoints remain reachable by OAuth clients.
+func registerMcpOAuth(app *fiber.App, dm *whatsapp.DeviceManager) (*mcpoauth.Server, bool, error) {
+ if !config.McpEnabled || !config.McpOAuthEnabled {
+ return nil, false, nil
+ }
+
+ validateCredential, err := mcpOAuthCredentialValidator(config.AppBasicAuthCredential)
+ if err != nil {
+ return nil, false, err
+ }
+
+ resourceURL := strings.TrimSpace(config.McpOAuthResourceURL)
+ if resourceURL == "" {
+ resourceURL, err = mcpoauth.DefaultResourceURL(config.McpOAuthIssuerURL, config.AppBasePath)
+ if err != nil {
+ return nil, false, err
+ }
+ }
+
+ oauthServer, err := mcpoauth.New(mcpoauth.Config{
+ IssuerURL: config.McpOAuthIssuerURL,
+ ResourceURL: resourceURL,
+ StorageURI: config.McpOAuthDBURI,
+ }, validateCredential)
+ if err != nil {
+ return nil, false, err
+ }
+
+ oauthServer.RegisterPublic(app)
+
+ var mcpRouter fiber.Router = app
+ if config.AppBasePath != "" {
+ mcpRouter = app.Group(config.AppBasePath)
+ }
+ mcpRouter = mcpRouter.Group("", oauthServer.MCPAuthMiddleware(validateCredential))
+ uimcp.Register(mcpRouter, dm, uimcp.Deps{
+ App: appUsecase,
+ Send: sendUsecase,
+ Chat: chatUsecase,
+ User: userUsecase,
+ Message: messageUsecase,
+ Group: groupUsecase,
+ })
+
+ return oauthServer, true, nil
+}
+
+func mcpOAuthCredentialValidator(credentials []string) (mcpoauth.CredentialValidator, error) {
+ if len(credentials) == 0 {
+ return nil, errors.New("MCP OAuth requires APP_BASIC_AUTH credentials")
+ }
+ accounts := make(map[string]string, len(credentials))
+ for _, credential := range credentials {
+ parts := strings.Split(credential, ":")
+ if len(parts) != 2 || parts[0] == "" {
+ return nil, fmt.Errorf("basic auth is not valid, use <user>:<secret>")
+ }
+ accounts[parts[0]] = parts[1]
+ }
+ return func(username, password string) bool {
+ expected, ok := accounts[username]
+ if !ok {
+ return false
+ }
+ return subtle.ConstantTimeCompare([]byte(password), []byte(expected)) == 1
+ }, nil
+}
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 741ebdff..f82d2a62 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -5,6 +5,7 @@ import (
"crypto/subtle"
"fmt"
"net/http"
+ "net/url"
"os"
"os/signal"
"strings"
@@ -42,6 +43,8 @@ func init() {
rootCmd.AddCommand(restCmd)
}
func restServer(_ *cobra.Command, _ []string) {
+ // registerMcpOAuth depends on these values being loaded after flag parsing.
+ loadMcpOAuthEnvConfig()
fiberConfig := fiber.Config{
TrustProxy: true,
BodyLimit: int(config.WhatsappSettingMaxVideoSize),
@@ -100,6 +103,21 @@ func restServer(_ *cobra.Command, _ []string) {
app.Post(webhookPath+"/:device_id", chatwootHandler.HandleDeviceWebhook)
}
+ // OAuth discovery/login/token routes and the OAuth-protected MCP route must
+ // be registered before the global Basic Auth middleware. When OAuth is off,
+ // this is a no-op and MCP is mounted in its historical location below.
+ oauthServer, mcpOAuthRegistered, err := registerMcpOAuth(app, dm)
+ if err != nil {
+ logrus.Fatalln("Failed to initialize MCP OAuth: ", err.Error())
+ }
+ if oauthServer != nil {
+ defer func() {
+ if err := oauthServer.Close(); err != nil {
+ logrus.Warnf("MCP OAuth storage close: %v", err)
+ }
+ }()
+ }
+
if len(config.AppBasicAuthCredential) > 0 {
account := make(map[string]string)
for _, basicAuth := range config.AppBasicAuthCredential {
@@ -139,8 +157,9 @@ func restServer(_ *cobra.Command, _ []string) {
rest.InitRestAppInfo(apiGroup)
// MCP endpoint — same usecase instances as REST, so both surfaces share
- // one whatsmeow session. Sits behind the basic-auth middleware above.
- if config.McpEnabled {
+ // one whatsmeow session. With OAuth disabled it keeps the existing global
+ // Basic Auth behavior; OAuth-enabled MCP was already mounted above.
+ if config.McpEnabled && !mcpOAuthRegistered {
uimcp.Register(apiGroup, dm, uimcp.Deps{
App: appUsecase,
Send: sendUsecase,
@@ -275,10 +294,19 @@ func newCORSMiddleware() fiber.Handler {
if len(config.AppCORSAllowedOrigins) > 0 {
origins = config.AppCORSAllowedOrigins
}
+ oauthAuthorizePath := ""
+ if config.McpOAuthEnabled {
+ if issuer, err := url.Parse(strings.TrimSpace(config.McpOAuthIssuerURL)); err == nil {
+ oauthAuthorizePath = strings.TrimRight(issuer.Path, "/") + "/oauth/authorize"
+ }
+ }
return cors.New(cors.Config{
AllowOrigins: origins,
AllowMethods: []string{"GET", "POST", "HEAD", "PUT", "PATCH", "DELETE"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", middleware.DeviceIDHeader},
+ Next: func(c fiber.Ctx) bool {
+ return oauthAuthorizePath != "" && c.Path() == oauthAuthorizePath
+ },
})
}
diff --git a/src/cmd/rest_test.go b/src/cmd/rest_test.go
index aece45b5..d4e6e421 100644
--- a/src/cmd/rest_test.go
+++ b/src/cmd/rest_test.go
@@ -76,6 +76,7 @@ func TestCORSPreflightAllowsUIHeaders(t *testing.T) {
resp, err := app.Test(req)
require.NoError(t, err)
+ defer func() { require.NoError(t, resp.Body.Close()) }()
assert.Equal(t, fiber.StatusNoContent, resp.StatusCode)
assert.Equal(t, "*", resp.Header.Get("Access-Control-Allow-Origin"))
allowedHeaders := strings.ToLower(resp.Header.Get("Access-Control-Allow-Headers"))
@@ -83,6 +84,39 @@ func TestCORSPreflightAllowsUIHeaders(t *testing.T) {
assert.Contains(t, allowedHeaders, "x-device-id")
}
+func TestCORSDoesNotApplyToOAuthAuthorizationEndpoint(t *testing.T) {
+ previousEnabled := config.McpOAuthEnabled
+ previousIssuer := config.McpOAuthIssuerURL
+ config.McpOAuthEnabled = true
+ config.McpOAuthIssuerURL = "https://gowa.example.com/gowa"
+ t.Cleanup(func() {
+ config.McpOAuthEnabled = previousEnabled
+ config.McpOAuthIssuerURL = previousIssuer
+ })
+
+ app := fiber.New()
+ app.Use(newCORSMiddleware())
+ app.Get("/gowa/oauth/authorize", func(c fiber.Ctx) error {
+ return c.SendStatus(fiber.StatusOK)
+ })
+
+ req := httptest.NewRequest("GET", "/gowa/oauth/authorize", nil)
+ req.Header.Set("Origin", "https://client.example.com")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ defer func() { require.NoError(t, resp.Body.Close()) }()
+ assert.Equal(t, fiber.StatusOK, resp.StatusCode)
+ assert.Empty(t, resp.Header.Get("Access-Control-Allow-Origin"))
+
+ preflight := httptest.NewRequest("OPTIONS", "/gowa/oauth/authorize", nil)
+ preflight.Header.Set("Origin", "https://client.example.com")
+ preflight.Header.Set("Access-Control-Request-Method", "GET")
+ preflightResp, err := app.Test(preflight)
+ require.NoError(t, err)
+ defer func() { require.NoError(t, preflightResp.Body.Close()) }()
+ assert.Empty(t, preflightResp.Header.Get("Access-Control-Allow-Origin"))
+}
+
func TestWebsocketQueryAuth(t *testing.T) {
validQuery := base64.StdEncoding.EncodeToString([]byte("user:secret"))
wrongQuery := base64.StdEncoding.EncodeToString([]byte("user:wrong"))
diff --git a/src/config/oauth.go b/src/config/oauth.go
new file mode 100644
index 00000000..5c09baaa
--- /dev/null
+++ b/src/config/oauth.go
@@ -0,0 +1,11 @@
+package config
+
+var (
+ // MCP OAuth is opt-in. When enabled, the REST process embeds an OAuth 2.1
+ // authorization server for the MCP endpoint while keeping Basic Auth as a
+ // backward-compatible MCP authentication method.
+ McpOAuthEnabled = false
+ McpOAuthIssuerURL = ""
+ McpOAuthResourceURL = ""
+ McpOAuthDBURI = "file:storages/oauth.db"
+)
diff --git a/src/ui/mcp/oauth/security_test.go b/src/ui/mcp/oauth/security_test.go
new file mode 100644
index 00000000..4668f4dd
--- /dev/null
+++ b/src/ui/mcp/oauth/security_test.go
@@ -0,0 +1,361 @@
+package oauth
+
+import (
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+
+ "github.com/gofiber/fiber/v3"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "github.com/valyala/fasthttp"
+)
+
+func TestAuthorizationRejectsRedirectPrefixMatch(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+ clientID := registerTestClient(t, app)
+ verifier := strings.Repeat("c", 43)
+ sum := sha256.Sum256([]byte(verifier))
+ challenge := base64.RawURLEncoding.EncodeToString(sum[:])
+
+ query := url.Values{
+ "response_type": {"code"},
+ "client_id": {clientID},
+ "redirect_uri": {"https://claude.ai.evil.example/api/mcp/auth_callback"},
+ "code_challenge": {challenge},
+ "code_challenge_method": {"S256"},
+ "resource": {testResource},
+ "scope": {"mcp"},
+ }
+ resp, err := app.Test(httptest.NewRequest("GET", "/oauth/authorize?"+query.Encode(), nil))
+ require.NoError(t, err)
+ assert.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
+ assertOAuthError(t, resp, "invalid_request")
+}
+
+func TestAuthorizationPOSTStopsAfterRedirectValidationError(t *testing.T) {
+ srv, app := newOAuthTestServer(t, testIssuer, testResource)
+ clientID := registerTestClient(t, app)
+ verifier := strings.Repeat("c", 43)
+ sum := sha256.Sum256([]byte(verifier))
+
+ form := url.Values{
+ "response_type": {"code"},
+ "client_id": {clientID},
+ "redirect_uri": {"https://claude.ai.evil.example/api/mcp/auth_callback"},
+ "code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])},
+ "code_challenge_method": {"S256"},
+ "resource": {testResource},
+ "scope": {"mcp"},
+ "username": {"user"},
+ "password": {"secret"},
+ }
+ resp := postForm(t, app, "/oauth/authorize", form)
+ require.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
+ assertOAuthError(t, resp, "invalid_request")
+
+ var codes int
+ require.NoError(t, srv.store.db.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM oauth_authorization_codes`).Scan(&codes))
+ assert.Zero(t, codes, "a rejected authorization request must never issue a code")
+}
+
+func TestAuthorizationReturnsSafeValidationErrorsToClient(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+ clientID := registerTestClient(t, app)
+ verifier := strings.Repeat("f", 43)
+ sum := sha256.Sum256([]byte(verifier))
+ query := url.Values{
+ "response_type": {"code"},
+ "client_id": {clientID},
+ "redirect_uri": {testRedirect},
+ "code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])},
+ "code_challenge_method": {"S256"},
+ "resource": {testResource},
+ "scope": {"admin"},
+ "state": {"state-123"},
+ }
+ resp, err := app.Test(httptest.NewRequest("GET", "/oauth/authorize?"+query.Encode(), nil))
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusFound, resp.StatusCode)
+ callback, err := url.Parse(resp.Header.Get("Location"))
+ require.NoError(t, err)
+ assert.Equal(t, testRedirect, callback.Scheme+"://"+callback.Host+callback.Path)
+ assert.Equal(t, "invalid_scope", callback.Query().Get("error"))
+ assert.Equal(t, "state-123", callback.Query().Get("state"))
+ assert.Equal(t, testIssuer, callback.Query().Get("iss"))
+ assert.Empty(t, callback.Query().Get("code"))
+}
+
+func TestWrongPKCEVerifierDoesNotConsumeAuthorizationCode(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+ clientID := registerTestClient(t, app)
+ code, verifier := authorizeTestClient(t, app, clientID)
+
+ wrongVerifier := strings.Repeat("d", 43)
+ wrong := url.Values{
+ "grant_type": {"authorization_code"},
+ "client_id": {clientID},
+ "code": {code},
+ "redirect_uri": {testRedirect},
+ "code_verifier": {wrongVerifier},
+ "resource": {testResource},
+ }
+ resp := postForm(t, app, "/oauth/token", wrong)
+ assert.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
+ assertOAuthError(t, resp, "invalid_grant")
+
+ // A failed verifier must not burn the code; the legitimate client still
+ // gets exactly one successful redemption with the original verifier.
+ pair := exchangeTestCode(t, app, clientID, code, verifier, testResource)
+ assert.NotEmpty(t, pair.AccessToken)
+}
+
+func TestDCRNativeRedirectAllowsOnlyLoopbackHTTP(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+
+ register := func(body string) int {
+ t.Helper()
+ req := httptest.NewRequest("POST", "/oauth/register", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ return resp.StatusCode
+ }
+
+ assert.Equal(t, fiber.StatusCreated, register(`{"client_name":"Local","redirect_uris":["http://127.0.0.1:49152/callback"],"application_type":"native","token_endpoint_auth_method":"none"}`))
+ assert.Equal(t, fiber.StatusCreated, register(`{"client_name":"Local v6","redirect_uris":["http://[::1]:49152/callback"],"application_type":"native","token_endpoint_auth_method":"none"}`))
+ assert.Equal(t, fiber.StatusCreated, register(`{"client_name":"Named","redirect_uris":["http://localhost:49152/callback"],"application_type":"native","token_endpoint_auth_method":"none"}`))
+ assert.Equal(t, fiber.StatusCreated, register(`{"client_name":"Named upper","redirect_uris":["http://LocalHost:49152/callback"],"application_type":"native","token_endpoint_auth_method":"none"}`))
+ assert.Equal(t, fiber.StatusBadRequest, register(`{"client_name":"Remote","redirect_uris":["http://example.com/callback"],"application_type":"native","token_endpoint_auth_method":"none"}`))
+ assert.Equal(t, fiber.StatusBadRequest, register(`{"client_name":"Lookalike","redirect_uris":["http://localhost.example.com:49152/callback"],"application_type":"native","token_endpoint_auth_method":"none"}`))
+ assert.Equal(t, fiber.StatusBadRequest, register(`{"client_name":"No port","redirect_uris":["http://localhost/callback"],"application_type":"native","token_endpoint_auth_method":"none"}`))
+ assert.Equal(t, fiber.StatusBadRequest, register(`{"client_name":"Web","redirect_uris":["http://localhost:49152/callback"],"application_type":"web","token_endpoint_auth_method":"none"}`))
+}
+
+func TestDCRAcceptsClaudeCodeNativeLocalhostRegistration(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+ body := `{"client_name":"Claude Code (gowa)","redirect_uris":["http://localhost:60390/callback"],"grant_types":["authorization_code","refresh_token"],"response_types":["code"],"token_endpoint_auth_method":"none","application_type":"native","scope":"mcp"}`
+ req := httptest.NewRequestWithContext(t.Context(), "POST", "/oauth/register", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusCreated, resp.StatusCode)
+
+ var registered struct {
+ ClientID string `json:"client_id"`
+ RedirectURIs []string `json:"redirect_uris"`
+ ApplicationType string `json:"application_type"`
+ }
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&registered))
+ assert.NotEmpty(t, registered.ClientID)
+ assert.Equal(t, []string{"http://localhost:60390/callback"}, registered.RedirectURIs)
+ assert.Equal(t, "native", registered.ApplicationType)
+
+ verifier := strings.Repeat("c", 43)
+ sum := sha256.Sum256([]byte(verifier))
+ authorizeQuery := url.Values{
+ "response_type": {"code"},
+ "client_id": {registered.ClientID},
+ "redirect_uri": {"http://localhost:60390/callback"},
+ "code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])},
+ "code_challenge_method": {"S256"},
+ "resource": {testResource},
+ "scope": {"mcp"},
+ "state": {"state-123"},
+ }
+ resp, err = app.Test(httptest.NewRequestWithContext(t.Context(), "GET", "/oauth/authorize?"+authorizeQuery.Encode(), nil))
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ loginBody, err := io.ReadAll(resp.Body)
+ require.NoError(t, err)
+ assert.Contains(t, string(loginBody), "After authorization, you'll return to <strong>Claude Code (gowa)</strong> on this device (<strong>localhost:60390</strong>).")
+ assert.Contains(t, resp.Header.Get("Content-Security-Policy"), "form-action 'self' http://localhost:60390;")
+}
+
+func TestNativeLocalhostRedirectStillRequiresExactMatch(t *testing.T) {
+ client := Client{
+ ApplicationType: "native",
+ RedirectURIs: []string{"http://localhost:60390/callback"},
+ }
+
+ assert.True(t, redirectURIMatches(client, "http://localhost:60390/callback"))
+ assert.False(t, redirectURIMatches(client, "http://localhost:60391/callback"))
+ assert.False(t, redirectURIMatches(client, "http://localhost:60390/other"))
+ assert.False(t, redirectURIMatches(client, "http://127.0.0.1:60390/callback"))
+}
+
+func TestNativeLoopbackRedirectAllowsEphemeralPort(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+ registeredRedirect := "http://127.0.0.1:49152/callback"
+ requestedRedirect := "http://127.0.0.1:53100/callback"
+ registrationBody := `{"client_name":"Local","redirect_uris":["` + registeredRedirect + `"],"application_type":"native","token_endpoint_auth_method":"none"}`
+ registration := httptest.NewRequest("POST", "/oauth/register", strings.NewReader(registrationBody))
+ registration.Header.Set("Content-Type", "application/json")
+ resp, err := app.Test(registration)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusCreated, resp.StatusCode)
+ var registered struct {
+ ClientID string `json:"client_id"`
+ }
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&registered))
+
+ verifier := strings.Repeat("e", 43)
+ sum := sha256.Sum256([]byte(verifier))
+ form := url.Values{
+ "response_type": {"code"},
+ "client_id": {registered.ClientID},
+ "redirect_uri": {requestedRedirect},
+ "code_challenge": {base64.RawURLEncoding.EncodeToString(sum[:])},
+ "code_challenge_method": {"S256"},
+ "resource": {testResource},
+ "scope": {"mcp"},
+ "username": {"user"},
+ "password": {"secret"},
+ }
+ form.Set("redirect_uri", "http://127.0.0.1:53100/other")
+ resp = postForm(t, app, "/oauth/authorize", form)
+ require.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
+ assertOAuthError(t, resp, "invalid_request")
+
+ form.Set("redirect_uri", requestedRedirect)
+ resp = postForm(t, app, "/oauth/authorize", form)
+ require.Equal(t, fiber.StatusFound, resp.StatusCode)
+ callback, err := url.Parse(resp.Header.Get("Location"))
+ require.NoError(t, err)
+ code := callback.Query().Get("code")
+ require.NotEmpty(t, code)
+ assert.Equal(t, requestedRedirect, callback.Scheme+"://"+callback.Host+callback.Path)
+
+ wrongRedirect := url.Values{
+ "grant_type": {"authorization_code"},
+ "client_id": {registered.ClientID},
+ "code": {code},
+ "redirect_uri": {registeredRedirect},
+ "code_verifier": {verifier},
+ "resource": {testResource},
+ }
+ resp = postForm(t, app, "/oauth/token", wrongRedirect)
+ require.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
+ assertOAuthError(t, resp, "invalid_grant")
+
+ wrongRedirect.Set("redirect_uri", requestedRedirect)
+ resp = postForm(t, app, "/oauth/token", wrongRedirect)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+}
+
+func TestDCRRejectsOversizedMetadataBeforeStorage(t *testing.T) {
+ srv, app := newOAuthTestServer(t, testIssuer, testResource)
+ body := `{"client_name":"Large","redirect_uris":["https://example.com/callback"],"padding":"` + strings.Repeat("x", maxOAuthBodyBytes) + `"}`
+ req := httptest.NewRequest("POST", "/oauth/register", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := app.Test(req)
+ require.ErrorIs(t, err, fasthttp.ErrBodyTooLarge)
+ assert.Nil(t, resp)
+
+ var clients int
+ require.NoError(t, srv.store.db.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM oauth_clients`).Scan(&clients))
+ assert.Zero(t, clients)
+}
+
+func TestDCRRejectsOversizedRedirectURI(t *testing.T) {
+ srv, app := newOAuthTestServer(t, testIssuer, testResource)
+ redirect := "https://example.com/" + strings.Repeat("x", maxRedirectURIBytes)
+ body := `{"client_name":"Large redirect","redirect_uris":["` + redirect + `"],"application_type":"web","token_endpoint_auth_method":"none"}`
+ req := httptest.NewRequest("POST", "/oauth/register", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
+ assertOAuthError(t, resp, "invalid_redirect_uri")
+
+ var clients int
+ require.NoError(t, srv.store.db.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM oauth_clients`).Scan(&clients))
+ assert.Zero(t, clients)
+}
+
+func TestDCRAppliesDurableClientQuota(t *testing.T) {
+ srv, app := newOAuthTestServer(t, testIssuer, testResource)
+ srv.store.maxClients = 1
+ srv.store.maxRegistrationsPerWindow = 10
+ _ = registerTestClient(t, app)
+
+ body := `{"client_name":"Second","redirect_uris":["https://example.com/callback"],"application_type":"web","token_endpoint_auth_method":"none"}`
+ req := httptest.NewRequest("POST", "/oauth/register", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusTooManyRequests, resp.StatusCode)
+ assertOAuthError(t, resp, "temporarily_unavailable")
+
+ var clients int
+ require.NoError(t, srv.store.db.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM oauth_clients`).Scan(&clients))
+ assert.Equal(t, 1, clients)
+}
+
+func TestOAuthPOSTEndpointsRejectOversizedBodiesAtServerBoundary(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+ for _, endpoint := range []struct {
+ name string
+ path string
+ contentType string
+ }{
+ {name: "register", path: "/oauth/register", contentType: "application/json"},
+ {name: "authorize", path: "/oauth/authorize", contentType: "application/x-www-form-urlencoded"},
+ {name: "token", path: "/oauth/token", contentType: "application/x-www-form-urlencoded"},
+ } {
+ t.Run(endpoint.name, func(t *testing.T) {
+ req := httptest.NewRequest("POST", endpoint.path, strings.NewReader(strings.Repeat("x", maxOAuthBodyBytes+1)))
+ req.Header.Set("Content-Type", endpoint.contentType)
+ resp, err := app.Test(req)
+ require.ErrorIs(t, err, fasthttp.ErrBodyTooLarge)
+ assert.Nil(t, resp)
+ })
+ }
+}
+
+// Fiber runs with CaseSensitive and StrictRouting disabled, so trailing-slash,
+// case, and absolute-form targets all reach the same OAuth handlers. The
+// header-time cap must cover each of them instead of the byte-exact path only.
+func TestOAuthBodyCapCoversRoutingPathAliases(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+ for _, target := range []string{
+ "/oauth/token/",
+ "/oauth/token//",
+ "/OAUTH/TOKEN",
+ "/oauth/Token/",
+ "/oauth/token?resource=https://gowa.example.com/mcp",
+ "http://gowa.example.com/oauth/token/",
+ "/oauth/authorize/",
+ "/OAUTH/AUTHORIZE",
+ "/oauth/register/",
+ "/OAUTH/REGISTER",
+ } {
+ t.Run(target, func(t *testing.T) {
+ req := httptest.NewRequest("POST", target, strings.NewReader(strings.Repeat("x", maxOAuthBodyBytes+1)))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ resp, err := app.Test(req)
+ require.ErrorIs(t, err, fasthttp.ErrBodyTooLarge)
+ assert.Nil(t, resp)
+ })
+ }
+}
+
+// The cap must stay scoped to the OAuth POST routes so the application's own
+// large-upload endpoints keep the app-wide BodyLimit.
+func TestOAuthBodyCapLeavesOtherRoutesAlone(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+ app.Post("/send/video", func(c fiber.Ctx) error { return c.SendString("ok") })
+
+ req := httptest.NewRequest("POST", "/send/video", strings.NewReader(strings.Repeat("x", maxOAuthBodyBytes+1)))
+ req.Header.Set("Content-Type", "application/octet-stream")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ assert.Equal(t, fiber.StatusOK, resp.StatusCode)
+ require.NoError(t, resp.Body.Close())
+}
diff --git a/src/ui/mcp/oauth/server.go b/src/ui/mcp/oauth/server.go
new file mode 100644
index 00000000..d1c59e93
--- /dev/null
+++ b/src/ui/mcp/oauth/server.go
@@ -0,0 +1,777 @@
+package oauth
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "html/template"
+ "net"
+ "net/url"
+ "path"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/gofiber/fiber/v3"
+ "github.com/valyala/fasthttp"
+)
+
+const (
+ defaultStorageURI = "file:storages/oauth.db"
+ defaultScope = "mcp"
+ codeTTL = 5 * time.Minute
+ accessTokenTTL = time.Hour
+ refreshTokenTTL = 30 * 24 * time.Hour
+ maxOAuthBodyBytes = 16 * 1024
+ maxClientNameBytes = 200
+ maxRedirectURIBytes = 2048
+ maxRedirectURIsBytes = 8 * 1024
+)
+
+type Server struct {
+ issuer *url.URL
+ resource *url.URL
+ store *store
+ validateCredential CredentialValidator
+ now func() time.Time
+}
+
+type dynamicRegistrationRequest struct {
+ ClientName string `json:"client_name"`
+ RedirectURIs []string `json:"redirect_uris"`
+ ApplicationType string `json:"application_type"`
+ TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
+ GrantTypes []string `json:"grant_types"`
+ ResponseTypes []string `json:"response_types"`
+}
+
+type authorizationRequest struct {
+ ResponseType string `form:"response_type"`
+ ClientID string `form:"client_id"`
+ RedirectURI string `form:"redirect_uri"`
+ CodeChallenge string `form:"code_challenge"`
+ CodeChallengeMethod string `form:"code_challenge_method"`
+ Resource string `form:"resource"`
+ Scope string `form:"scope"`
+ State string `form:"state"`
+ Username string `form:"username"`
+ Password string `form:"password"`
+}
+
+type tokenRequest struct {
+ GrantType string `form:"grant_type"`
+ ClientID string `form:"client_id"`
+ Code string `form:"code"`
+ RedirectURI string `form:"redirect_uri"`
+ CodeVerifier string `form:"code_verifier"`
+ RefreshToken string `form:"refresh_token"`
+ Resource string `form:"resource"`
+}
+
+type authorizePageData struct {
+ ClientName string
+ RedirectTarget string
+ LocalRedirect bool
+ AuthorizePath string
+ ResponseType string
+ ClientID string
+ RedirectURI string
+ CodeChallenge string
+ CodeChallengeMethod string
+ Resource string
+ Scope string
+ State string
+ Error string
+}
+
+var authorizeTemplate = template.Must(template.New("oauth-authorize").Parse(`<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width,initial-scale=1">
+ <title>Authorize {{.ClientName}}</title>
+ <style>body{font-family:system-ui,sans-serif;max-width:28rem;margin:4rem auto;padding:0 1rem}label{display:block;margin-top:1rem}input{box-sizing:border-box;width:100%;padding:.65rem}button{margin-top:1.25rem;padding:.7rem 1rem}.error{color:#a00}</style>
+</head>
+<body>
+ <h1>Authorize {{.ClientName}}</h1>
+ <p>Sign in with an existing GOWA Basic Auth account to allow this MCP client to access WhatsApp through GOWA.</p>
+ {{if .LocalRedirect}}<p>After authorization, you'll return to <strong>{{.ClientName}}</strong> on this device (<strong>{{.RedirectTarget}}</strong>).</p>
+ {{else}}<p>After authorization, you'll continue to <strong>{{.RedirectTarget}}</strong>.</p>{{end}}
+ {{if .Error}}<p class="error">{{.Error}}</p>{{end}}
+ <form method="post" action="{{.AuthorizePath}}">
+ <input type="hidden" name="response_type" value="{{.ResponseType}}">
+ <input type="hidden" name="client_id" value="{{.ClientID}}">
+ <input type="hidden" name="redirect_uri" value="{{.RedirectURI}}">
+ <input type="hidden" name="code_challenge" value="{{.CodeChallenge}}">
+ <input type="hidden" name="code_challenge_method" value="{{.CodeChallengeMethod}}">
+ <input type="hidden" name="resource" value="{{.Resource}}">
+ <input type="hidden" name="scope" value="{{.Scope}}">
+ <input type="hidden" name="state" value="{{.State}}">
+ <label>Username<input name="username" autocomplete="username" required></label>
+ <label>Password<input type="password" name="password" autocomplete="current-password" required></label>
+ <button type="submit">Authorize</button>
+ </form>
+</body>
+</html>`))
+
+func New(cfg Config, validateCredential CredentialValidator) (*Server, error) {
+ if validateCredential == nil {
+ return nil, errors.New("MCP OAuth requires a credential validator")
+ }
+ issuer, err := normalizePublicURL(cfg.IssuerURL, "issuer")
+ if err != nil {
+ return nil, err
+ }
+ resource, err := normalizePublicURL(cfg.ResourceURL, "resource")
+ if err != nil {
+ return nil, err
+ }
+ if issuer.Scheme != resource.Scheme || !strings.EqualFold(issuer.Host, resource.Host) {
+ return nil, errors.New("MCP OAuth issuer and resource must use the same public origin")
+ }
+ storageURI := strings.TrimSpace(cfg.StorageURI)
+ if storageURI == "" {
+ storageURI = defaultStorageURI
+ }
+ store, err := openStore(storageURI)
+ if err != nil {
+ return nil, err
+ }
+ return &Server{
+ issuer: issuer,
+ resource: resource,
+ store: store,
+ validateCredential: validateCredential,
+ now: func() time.Time { return time.Now().UTC() },
+ }, nil
+}
+
+func (s *Server) Close() error {
+ if s == nil {
+ return nil
+ }
+ return s.store.Close()
+}
+
+func DefaultResourceURL(issuerURL, appBasePath string) (string, error) {
+ issuer, err := normalizePublicURL(issuerURL, "issuer")
+ if err != nil {
+ return "", err
+ }
+ resource := &url.URL{Scheme: issuer.Scheme, Host: issuer.Host}
+ resource.Path = path.Join("/", strings.TrimSpace(appBasePath), "mcp")
+ return resource.String(), nil
+}
+
+func (s *Server) RegisterPublic(app *fiber.App) {
+ s.limitPublicPOSTBodies(app)
+ app.Get(wellKnownPath("oauth-authorization-server", s.issuer.Path), s.authorizationServerMetadata)
+ app.Get(wellKnownPath("oauth-protected-resource", s.resource.Path), s.protectedResourceMetadata)
+ app.Post(s.issuerEndpointPath("/oauth/register"), s.registerClient)
+ app.Get(s.issuerEndpointPath("/oauth/authorize"), s.authorizeGET)
+ app.Post(s.issuerEndpointPath("/oauth/authorize"), s.authorizePOST)
+ app.Post(s.issuerEndpointPath("/oauth/token"), s.token)
+}
+
+// limitPublicPOSTBodies applies the OAuth cap in fasthttp immediately after
+// headers are received, before the unauthenticated request body is buffered.
+func (s *Server) limitPublicPOSTBodies(app *fiber.App) {
+ paths := []string{
+ routingPathKey(s.issuerEndpointPath("/oauth/register")),
+ routingPathKey(s.issuerEndpointPath("/oauth/authorize")),
+ routingPathKey(s.issuerEndpointPath("/oauth/token")),
+ }
+ previous := app.Server().HeaderReceived
+ app.Server().HeaderReceived = func(header *fasthttp.RequestHeader) fasthttp.RequestConfig {
+ var cfg fasthttp.RequestConfig
+ if previous != nil {
+ cfg = previous(header)
+ }
+ if !bytes.Equal(header.Method(), []byte(fiber.MethodPost)) {
+ return cfg
+ }
+ if cfg.MaxRequestBodySize != 0 && cfg.MaxRequestBodySize <= maxOAuthBodyBytes {
+ return cfg
+ }
+ requestPath := routingPathKey(requestRoutingPath(header))
+ if requestPath != "" && slices.Contains(paths, requestPath) {
+ cfg.MaxRequestBodySize = maxOAuthBodyBytes
+ }
+ return cfg
+ }
+}
+
+// requestRoutingPath extracts the path Fiber will route on using the same
+// fasthttp URI parser Fiber itself uses, so query strings, fragments, and
+// absolute-form request targets are stripped identically. An unparsable target
+// yields an empty path in Fiber too, which cannot match an OAuth route.
+func requestRoutingPath(header *fasthttp.RequestHeader) string {
+ var uri fasthttp.URI
+ if err := uri.Parse(header.Host(), header.RequestURI()); err != nil {
+ return ""
+ }
+ return string(uri.PathOriginal())
+}
+
+// routingPathKey normalizes a path the way Fiber's router does under this
+// application's defaults (CaseSensitive and StrictRouting both disabled), so the
+// header-time cap covers every URL form that reaches the OAuth handlers rather
+// than only the byte-exact registered path. Fiber lowercases ASCII only; for an
+// ASCII-only registered path this can only widen the match, never narrow it.
+func routingPathKey(p string) string {
+ key := strings.ToLower(p)
+ if len(key) > 1 && key[len(key)-1] == '/' {
+ key = strings.TrimRight(key, "/")
+ }
+ return key
+}
+
+func (s *Server) MCPAuthMiddleware(basic CredentialValidator) fiber.Handler {
+ return func(c fiber.Ctx) error {
+ scheme, credentials := splitAuthorization(c.Get(fiber.HeaderAuthorization))
+ switch strings.ToLower(scheme) {
+ case "bearer":
+ if credentials == "" {
+ return s.mcpUnauthorized(c, basic != nil, true)
+ }
+ principal, err := s.store.validateAccessToken(c.Context(), credentials, s.resource.String(), s.now())
+ if err != nil {
+ return s.mcpUnauthorized(c, basic != nil, true)
+ }
+ c.Locals("oauth_subject", principal.Subject)
+ c.Locals("oauth_client_id", principal.ClientID)
+ return c.Next()
+ case "basic":
+ if basic == nil {
+ return s.mcpUnauthorized(c, false, false)
+ }
+ username, password, ok := decodeBasicCredentials(credentials)
+ if !ok || !basic(username, password) {
+ return s.mcpUnauthorized(c, true, false)
+ }
+ return c.Next()
+ default:
+ return s.mcpUnauthorized(c, basic != nil, false)
+ }
+ }
+}
+
+func (s *Server) authorizationServerMetadata(c fiber.Ctx) error {
+ s.setNoStore(c)
+ return c.JSON(fiber.Map{
+ "issuer": s.issuer.String(),
+ "authorization_endpoint": s.issuerEndpointURL("/oauth/authorize"),
+ "token_endpoint": s.issuerEndpointURL("/oauth/token"),
+ "registration_endpoint": s.issuerEndpointURL("/oauth/register"),
+ "response_types_supported": []string{"code"},
+ "grant_types_supported": []string{"authorization_code", "refresh_token"},
+ "token_endpoint_auth_methods_supported": []string{"none"},
+ "code_challenge_methods_supported": []string{"S256"},
+ "scopes_supported": []string{defaultScope},
+ "authorization_response_iss_parameter_supported": true,
+ })
+}
+
+func (s *Server) protectedResourceMetadata(c fiber.Ctx) error {
+ s.setNoStore(c)
+ return c.JSON(fiber.Map{
+ "resource": s.resource.String(),
+ "authorization_servers": []string{s.issuer.String()},
+ "bearer_methods_supported": []string{"header"},
+ "scopes_supported": []string{defaultScope},
+ "resource_name": "GOWA MCP",
+ })
+}
+
+func (s *Server) registerClient(c fiber.Ctx) error {
+ s.setNoStore(c)
+ if len(c.Body()) > maxOAuthBodyBytes {
+ return oauthError(c, fiber.StatusRequestEntityTooLarge, "invalid_client_metadata", "registration document is too large")
+ }
+ var req dynamicRegistrationRequest
+ if err := c.Bind().Body(&req); err != nil {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_client_metadata", "invalid registration document")
+ }
+ if len(req.RedirectURIs) == 0 || len(req.RedirectURIs) > 10 {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_redirect_uri", "redirect_uris must contain between 1 and 10 entries")
+ }
+ if req.ApplicationType == "" {
+ req.ApplicationType = "web"
+ }
+ if req.ApplicationType != "web" && req.ApplicationType != "native" {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_client_metadata", "unsupported application_type")
+ }
+ if req.TokenEndpointAuthMethod == "" {
+ req.TokenEndpointAuthMethod = "none"
+ }
+ if req.TokenEndpointAuthMethod != "none" {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_client_metadata", "only public clients are supported")
+ }
+ if !onlySupported(req.ResponseTypes, "code") || !onlySupported(req.GrantTypes, "authorization_code", "refresh_token") {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_client_metadata", "unsupported response_type or grant_type")
+ }
+ redirectBytes := 0
+ for _, redirectURI := range req.RedirectURIs {
+ if len(redirectURI) > maxRedirectURIBytes {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_redirect_uri", "redirect URI is too long")
+ }
+ redirectBytes += len(redirectURI)
+ if !validRedirectURI(redirectURI, req.ApplicationType) {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_redirect_uri", "redirect URI must use HTTPS, except native loopback redirects")
+ }
+ }
+ if redirectBytes > maxRedirectURIsBytes {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_redirect_uri", "redirect URIs are too large")
+ }
+ name := strings.TrimSpace(req.ClientName)
+ if name == "" {
+ name = "MCP client"
+ }
+ if len(name) > maxClientNameBytes {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_client_metadata", "client_name is too long")
+ }
+ clientID, err := randomSecret("gowa_client_", 24)
+ if err != nil {
+ return oauthError(c, fiber.StatusInternalServerError, "server_error", "could not register client")
+ }
+ client := Client{
+ ID: clientID,
+ Name: name,
+ RedirectURIs: append([]string(nil), req.RedirectURIs...),
+ ApplicationType: req.ApplicationType,
+ TokenEndpointAuthMethod: req.TokenEndpointAuthMethod,
+ CreatedAt: s.now(),
+ }
+ if err := s.store.registerClient(c.Context(), client); err != nil {
+ if errors.Is(err, ErrRegistrationLimit) {
+ return oauthError(c, fiber.StatusTooManyRequests, "temporarily_unavailable", "dynamic client registration limit reached; retry later")
+ }
+ return oauthError(c, fiber.StatusInternalServerError, "server_error", "could not register client")
+ }
+ return c.Status(fiber.StatusCreated).JSON(fiber.Map{
+ "client_id": client.ID,
+ "client_id_issued_at": client.CreatedAt.Unix(),
+ "client_name": client.Name,
+ "redirect_uris": client.RedirectURIs,
+ "application_type": client.ApplicationType,
+ "token_endpoint_auth_method": client.TokenEndpointAuthMethod,
+ "grant_types": []string{"authorization_code", "refresh_token"},
+ "response_types": []string{"code"},
+ })
+}
+
+func (s *Server) authorizeGET(c fiber.Ctx) error {
+ req := authorizationRequest{
+ ResponseType: c.Query("response_type"),
+ ClientID: c.Query("client_id"),
+ RedirectURI: c.Query("redirect_uri"),
+ CodeChallenge: c.Query("code_challenge"),
+ CodeChallengeMethod: c.Query("code_challenge_method"),
+ Resource: c.Query("resource"),
+ Scope: c.Query("scope"),
+ State: c.Query("state"),
+ }
+ client, valid, err := s.validateAuthorizationRequest(c, &req)
+ if err != nil {
+ return err
+ }
+ if !valid {
+ return nil
+ }
+ return s.renderAuthorize(c, fiber.StatusOK, req, client, "")
+}
+
+func (s *Server) authorizePOST(c fiber.Ctx) error {
+ var req authorizationRequest
+ if err := c.Bind().Body(&req); err != nil {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_request", "invalid authorization request")
+ }
+ client, valid, err := s.validateAuthorizationRequest(c, &req)
+ if err != nil {
+ return err
+ }
+ if !valid {
+ return nil
+ }
+ if !s.validateCredential(req.Username, req.Password) {
+ return s.renderAuthorize(c, fiber.StatusUnauthorized, req, client, "Invalid username or password.")
+ }
+ code, err := s.store.issueAuthorizationCode(c.Context(), AuthorizationGrant{
+ ClientID: req.ClientID,
+ Subject: req.Username,
+ RedirectURI: req.RedirectURI,
+ CodeChallenge: req.CodeChallenge,
+ Resource: req.Resource,
+ Scope: req.Scope,
+ }, s.now(), codeTTL)
+ if err != nil {
+ return oauthError(c, fiber.StatusInternalServerError, "server_error", "could not issue authorization code")
+ }
+ redirectURL, err := url.Parse(req.RedirectURI)
+ if err != nil {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_request", "redirect_uri is not a valid URI")
+ }
+ query := redirectURL.Query()
+ query.Set("code", code)
+ if req.State != "" {
+ query.Set("state", req.State)
+ }
+ query.Set("iss", s.issuer.String())
+ redirectURL.RawQuery = query.Encode()
+ s.setNoStore(c)
+ return c.Redirect().Status(fiber.StatusFound).To(redirectURL.String())
+}
+
+func (s *Server) token(c fiber.Ctx) error {
+ s.setNoStore(c)
+ var req tokenRequest
+ if err := c.Bind().Body(&req); err != nil {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_request", "invalid token request")
+ }
+ if req.Resource != s.resource.String() {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_target", "resource does not match this MCP server")
+ }
+ var (
+ pair TokenPair
+ err error
+ )
+ switch req.GrantType {
+ case "authorization_code":
+ if !validPKCEVerifier(req.CodeVerifier) {
+ return oauthError(c, fiber.StatusBadRequest, "invalid_grant", "invalid authorization code or PKCE verifier")
+ }
+ pair, err = s.store.exchangeAuthorizationCode(c.Context(), CodeExchange{
+ ClientID: req.ClientID,
+ Code: req.Code,
+ RedirectURI: req.RedirectURI,
+ CodeVerifier: req.CodeVerifier,
+ Resource: req.Resource,
+ }, s.now(), accessTokenTTL, refreshTokenTTL)
+ case "refresh_token":
+ pair, err = s.store.rotateRefreshToken(c.Context(), RefreshExchange{
+ ClientID: req.ClientID,
+ RefreshToken: req.RefreshToken,
+ Resource: req.Resource,
+ }, s.now(), accessTokenTTL, refreshTokenTTL)
+ default:
+ return oauthError(c, fiber.StatusBadRequest, "unsupported_grant_type", "supported grant types are authorization_code and refresh_token")
+ }
+ if err != nil {
+ switch {
+ case errors.Is(err, ErrInvalidTarget):
+ return oauthError(c, fiber.StatusBadRequest, "invalid_target", "resource does not match the authorization grant")
+ case errors.Is(err, ErrInvalidGrant), errors.Is(err, ErrRefreshReuse):
+ return oauthError(c, fiber.StatusBadRequest, "invalid_grant", "authorization grant is invalid, expired, or already used")
+ default:
+ return oauthError(c, fiber.StatusInternalServerError, "server_error", "token request failed")
+ }
+ }
+ return c.JSON(tokenResponse{
+ AccessToken: pair.AccessToken,
+ TokenType: "Bearer",
+ ExpiresIn: pair.ExpiresIn,
+ RefreshToken: pair.RefreshToken,
+ Scope: pair.Scope,
+ })
+}
+
+func (s *Server) validateAuthorizationRequest(c fiber.Ctx, req *authorizationRequest) (Client, bool, error) {
+ client, err := s.store.getClient(c.Context(), req.ClientID)
+ if err != nil {
+ return Client{}, false, oauthError(c, fiber.StatusBadRequest, "invalid_request", "unknown client_id")
+ }
+ if !redirectURIMatches(client, req.RedirectURI) {
+ return Client{}, false, oauthError(c, fiber.StatusBadRequest, "invalid_request", "redirect_uri does not match the registered client")
+ }
+ // Once the client and redirect URI are known to be safe, OAuth errors must
+ // be returned to the client at that redirect URI rather than as an endpoint
+ // response in the user's browser.
+ if req.ResponseType != "code" {
+ return Client{}, false, s.authorizationError(c, *req, "unsupported_response_type", "response_type must be code")
+ }
+ if req.CodeChallengeMethod != "S256" || !validPKCEChallenge(req.CodeChallenge) {
+ return Client{}, false, s.authorizationError(c, *req, "invalid_request", "PKCE S256 is required")
+ }
+ if req.Resource != s.resource.String() {
+ return Client{}, false, s.authorizationError(c, *req, "invalid_target", "resource does not match this MCP server")
+ }
+ if req.Scope == "" {
+ req.Scope = defaultScope
+ }
+ if req.Scope != defaultScope {
+ return Client{}, false, s.authorizationError(c, *req, "invalid_scope", "only the mcp scope is supported")
+ }
+ return client, true, nil
+}
+
+func (s *Server) renderAuthorize(c fiber.Ctx, status int, req authorizationRequest, client Client, pageError string) error {
+ s.setNoStore(c)
+ c.Set(fiber.HeaderContentSecurityPolicy, authorizationPageCSP(req.RedirectURI))
+ c.Set(fiber.HeaderXFrameOptions, "DENY")
+ c.Set(fiber.HeaderReferrerPolicy, "no-referrer")
+ c.Type("html", "utf-8")
+ c.Status(status)
+ redirectTarget, localRedirect := redirectDisplay(req.RedirectURI)
+ return authorizeTemplate.Execute(c, authorizePageData{
+ ClientName: client.Name,
+ RedirectTarget: redirectTarget,
+ LocalRedirect: localRedirect,
+ AuthorizePath: s.issuerEndpointPath("/oauth/authorize"),
+ ResponseType: req.ResponseType,
+ ClientID: req.ClientID,
+ RedirectURI: req.RedirectURI,
+ CodeChallenge: req.CodeChallenge,
+ CodeChallengeMethod: req.CodeChallengeMethod,
+ Resource: req.Resource,
+ Scope: req.Scope,
+ State: req.State,
+ Error: pageError,
+ })
+}
+
+func authorizationPageCSP(redirectURI string) string {
+ formAction := "'self'"
+ if redirectOrigin := redirectOrigin(redirectURI); redirectOrigin != "" {
+ // Chrome applies form-action across redirects. Allow only the origin of
+ // the already-validated OAuth callback so the authorization POST can
+ // complete its redirect without weakening the rest of the page policy.
+ formAction += " " + redirectOrigin
+ }
+ return "default-src 'none'; style-src 'unsafe-inline'; form-action " + formAction + "; frame-ancestors 'none'; base-uri 'none'"
+}
+
+func redirectOrigin(raw string) string {
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme == "" || u.Host == "" {
+ return ""
+ }
+ return (&url.URL{Scheme: u.Scheme, Host: u.Host}).String()
+}
+
+func (s *Server) mcpUnauthorized(c fiber.Ctx, advertiseBasic, invalidBearer bool) error {
+ challenge := fmt.Sprintf(`Bearer resource_metadata="%s", scope="%s"`, s.protectedResourceMetadataURL(), defaultScope)
+ if invalidBearer {
+ challenge += `, error="invalid_token"`
+ }
+ c.Set(fiber.HeaderWWWAuthenticate, challenge)
+ if advertiseBasic {
+ c.Append(fiber.HeaderWWWAuthenticate, `Basic realm="GOWA MCP"`)
+ }
+ s.setNoStore(c)
+ return c.SendStatus(fiber.StatusUnauthorized)
+}
+
+func (s *Server) setNoStore(c fiber.Ctx) {
+ c.Set(fiber.HeaderCacheControl, "no-store")
+ c.Set(fiber.HeaderPragma, "no-cache")
+}
+
+func (s *Server) issuerEndpointPath(suffix string) string {
+ base := strings.TrimRight(s.issuer.Path, "/")
+ if base == "" {
+ return suffix
+ }
+ return base + suffix
+}
+
+func (s *Server) issuerEndpointURL(suffix string) string {
+ u := *s.issuer
+ u.Path = s.issuerEndpointPath(suffix)
+ u.RawPath = ""
+ return u.String()
+}
+
+func (s *Server) protectedResourceMetadataURL() string {
+ u := *s.resource
+ u.Path = wellKnownPath("oauth-protected-resource", s.resource.Path)
+ u.RawPath = ""
+ return u.String()
+}
+
+func normalizePublicURL(raw, label string) (*url.URL, error) {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return nil, fmt.Errorf("MCP OAuth %s URL is required", label)
+ }
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
+ return nil, fmt.Errorf("MCP OAuth %s URL must be an absolute public HTTPS URL without credentials, query, or fragment", label)
+ }
+ u.Path = strings.TrimRight(u.Path, "/")
+ u.RawPath = ""
+ return u, nil
+}
+
+func wellKnownPath(metadataName, resourcePath string) string {
+ cleaned := strings.Trim(resourcePath, "/")
+ if cleaned == "" {
+ return "/.well-known/" + metadataName
+ }
+ return "/.well-known/" + metadataName + "/" + cleaned
+}
+
+func validRedirectURI(raw, applicationType string) bool {
+ u, err := url.Parse(raw)
+ if err != nil || u.Host == "" || u.User != nil || u.Fragment != "" {
+ return false
+ }
+ if u.Scheme == "https" {
+ return true
+ }
+ if applicationType != "native" || u.Scheme != "http" {
+ return false
+ }
+ hostname := u.Hostname()
+ // Claude Code registers its native callback as localhost with an explicit
+ // ephemeral port. Accept that narrow compatibility form, but keep the
+ // authorization-time port exception limited to IP literals in
+ // loopbackRedirectMatches so localhost redirects remain exact matches.
+ if strings.EqualFold(hostname, "localhost") {
+ return u.Port() != ""
+ }
+ ip := net.ParseIP(hostname)
+ return ip != nil && ip.IsLoopback()
+}
+
+func redirectDisplay(raw string) (string, bool) {
+ u, err := url.Parse(raw)
+ if err != nil || u.Hostname() == "" {
+ return "the registered client", false
+ }
+ hostname := u.Hostname()
+ if strings.EqualFold(hostname, "localhost") {
+ return u.Host, true
+ }
+ ip := net.ParseIP(hostname)
+ return u.Host, ip != nil && ip.IsLoopback()
+}
+
+func validPKCEChallenge(challenge string) bool {
+ if len(challenge) != 43 {
+ return false
+ }
+ decoded, err := base64.RawURLEncoding.DecodeString(challenge)
+ return err == nil && len(decoded) == sha256.Size
+}
+
+func validPKCEVerifier(verifier string) bool {
+ if len(verifier) < 43 || len(verifier) > 128 {
+ return false
+ }
+ for _, r := range verifier {
+ if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || strings.ContainsRune("-._~", r) {
+ continue
+ }
+ return false
+ }
+ return true
+}
+
+func containsExact(values []string, want string) bool {
+ for _, value := range values {
+ if value == want {
+ return true
+ }
+ }
+ return false
+}
+
+// redirectURIMatches uses exact string matching for every registered redirect
+// except the port of native loopback-IP redirects. OAuth 2.1 requires that
+// exception so desktop and CLI clients can bind an ephemeral local port.
+func redirectURIMatches(client Client, requested string) bool {
+ for _, registered := range client.RedirectURIs {
+ if registered == requested {
+ return true
+ }
+ if client.ApplicationType == "native" && loopbackRedirectMatches(registered, requested) {
+ return true
+ }
+ }
+ return false
+}
+
+func loopbackRedirectMatches(registered, requested string) bool {
+ registeredURL, err := url.Parse(registered)
+ if err != nil {
+ return false
+ }
+ requestedURL, err := url.Parse(requested)
+ if err != nil {
+ return false
+ }
+ if registeredURL.Scheme != "http" || requestedURL.Scheme != "http" ||
+ registeredURL.User != nil || requestedURL.User != nil ||
+ registeredURL.Fragment != "" || requestedURL.Fragment != "" {
+ return false
+ }
+ registeredIP := net.ParseIP(registeredURL.Hostname())
+ requestedIP := net.ParseIP(requestedURL.Hostname())
+ if registeredIP == nil || requestedIP == nil || !registeredIP.IsLoopback() || !requestedIP.IsLoopback() ||
+ registeredURL.Hostname() != requestedURL.Hostname() {
+ return false
+ }
+ return registeredURL.EscapedPath() == requestedURL.EscapedPath() &&
+ registeredURL.RawQuery == requestedURL.RawQuery &&
+ registeredURL.ForceQuery == requestedURL.ForceQuery
+}
+
+func onlySupported(values []string, supported ...string) bool {
+ if len(values) == 0 {
+ return true
+ }
+ for _, value := range values {
+ if !containsExact(supported, value) {
+ return false
+ }
+ }
+ return true
+}
+
+func splitAuthorization(header string) (string, string) {
+ parts := strings.Fields(strings.TrimSpace(header))
+ if len(parts) != 2 {
+ return "", ""
+ }
+ return parts[0], parts[1]
+}
+
+func decodeBasicCredentials(encoded string) (string, string, bool) {
+ decoded, err := base64.StdEncoding.DecodeString(encoded)
+ if err != nil {
+ return "", "", false
+ }
+ username, password, ok := strings.Cut(string(decoded), ":")
+ if !ok || username == "" {
+ return "", "", false
+ }
+ return username, password, true
+}
+
+func oauthError(c fiber.Ctx, status int, code, description string) error {
+ c.Set(fiber.HeaderCacheControl, "no-store")
+ c.Set(fiber.HeaderPragma, "no-cache")
+ return c.Status(status).JSON(fiber.Map{
+ "error": code,
+ "error_description": description,
+ })
+}
+
+func (s *Server) authorizationError(c fiber.Ctx, req authorizationRequest, code, description string) error {
+ redirectURL, err := url.Parse(req.RedirectURI)
+ if err != nil {
+ return oauthError(c, fiber.StatusBadRequest, code, description)
+ }
+ query := redirectURL.Query()
+ query.Set("error", code)
+ query.Set("error_description", description)
+ if req.State != "" {
+ query.Set("state", req.State)
+ }
+ query.Set("iss", s.issuer.String())
+ redirectURL.RawQuery = query.Encode()
+ s.setNoStore(c)
+ return c.Redirect().Status(fiber.StatusFound).To(redirectURL.String())
+}
diff --git a/src/ui/mcp/oauth/server_test.go b/src/ui/mcp/oauth/server_test.go
new file mode 100644
index 00000000..670b3c0d
--- /dev/null
+++ b/src/ui/mcp/oauth/server_test.go
@@ -0,0 +1,329 @@
+package oauth
+
+import (
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/gofiber/fiber/v3"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+const (
+ testIssuer = "https://gowa.example.com"
+ testResource = "https://gowa.example.com/mcp"
+ testRedirect = "https://claude.ai/api/mcp/auth_callback"
+)
+
+func newOAuthTestServer(t *testing.T, issuer, resource string) (*Server, *fiber.App) {
+ t.Helper()
+
+ dbPath := filepath.Join(t.TempDir(), "oauth.db")
+ srv, err := New(Config{
+ IssuerURL: issuer,
+ ResourceURL: resource,
+ StorageURI: "file:" + filepath.ToSlash(dbPath),
+ }, func(username, password string) bool {
+ return username == "user" && password == "secret"
+ })
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, srv.Close()) })
+
+ app := fiber.New()
+ srv.RegisterPublic(app)
+ return srv, app
+}
+
+func TestMetadataUsesRFCWellKnownPathInsertion(t *testing.T) {
+ _, app := newOAuthTestServer(t,
+ "https://gowa.example.com/gowa",
+ "https://gowa.example.com/gowa/mcp",
+ )
+
+ resp, err := app.Test(httptest.NewRequest("GET", "/.well-known/oauth-authorization-server/gowa", nil))
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+
+ var authMetadata map[string]any
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&authMetadata))
+ assert.Equal(t, "https://gowa.example.com/gowa", authMetadata["issuer"])
+ assert.Equal(t, "https://gowa.example.com/gowa/oauth/authorize", authMetadata["authorization_endpoint"])
+ assert.Equal(t, "https://gowa.example.com/gowa/oauth/token", authMetadata["token_endpoint"])
+ assert.Equal(t, "https://gowa.example.com/gowa/oauth/register", authMetadata["registration_endpoint"])
+ assert.Equal(t, []any{"S256"}, authMetadata["code_challenge_methods_supported"])
+ assert.Equal(t, true, authMetadata["authorization_response_iss_parameter_supported"])
+ _, claimsCIMD := authMetadata["client_id_metadata_document_supported"]
+ assert.False(t, claimsCIMD, "DCR compatibility must not claim unimplemented CIMD support")
+
+ resp, err = app.Test(httptest.NewRequest("GET", "/.well-known/oauth-protected-resource/gowa/mcp", nil))
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+
+ var resourceMetadata map[string]any
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&resourceMetadata))
+ assert.Equal(t, "https://gowa.example.com/gowa/mcp", resourceMetadata["resource"])
+ assert.Equal(t, []any{"https://gowa.example.com/gowa"}, resourceMetadata["authorization_servers"])
+}
+
+func TestDynamicClientRegistrationRequiresSafeExactRedirects(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+
+ register := func(body string) (int, map[string]any) {
+ t.Helper()
+ req := httptest.NewRequest("POST", "/oauth/register", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ var payload map[string]any
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&payload))
+ return resp.StatusCode, payload
+ }
+
+ status, payload := register(`{"client_name":"Claude","redirect_uris":["https://claude.ai/api/mcp/auth_callback"],"application_type":"web","token_endpoint_auth_method":"none"}`)
+ assert.Equal(t, fiber.StatusCreated, status)
+ assert.NotEmpty(t, payload["client_id"])
+ assert.Equal(t, "none", payload["token_endpoint_auth_method"])
+
+ status, payload = register(`{"client_name":"Bad","redirect_uris":["http://evil.example/callback"],"application_type":"web","token_endpoint_auth_method":"none"}`)
+ assert.Equal(t, fiber.StatusBadRequest, status)
+ assert.Equal(t, "invalid_redirect_uri", payload["error"])
+}
+
+func TestDynamicClientRegistrationReturnsActualFixedCapabilities(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+ body := `{"client_name":"Fixed capabilities","redirect_uris":["https://example.com/callback"],"grant_types":["authorization_code"],"response_types":["code"]}`
+ req := httptest.NewRequest("POST", "/oauth/register", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ defer func() { require.NoError(t, resp.Body.Close()) }()
+ require.Equal(t, fiber.StatusCreated, resp.StatusCode)
+
+ var registration map[string]any
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&registration))
+ assert.Equal(t, []any{"authorization_code", "refresh_token"}, registration["grant_types"])
+ assert.Equal(t, []any{"code"}, registration["response_types"])
+}
+
+func TestAuthorizationCodeFlowBearerAndBasicFallback(t *testing.T) {
+ srv, app := newOAuthTestServer(t, testIssuer, testResource)
+ clientID := registerTestClient(t, app)
+
+ verifier := strings.Repeat("a", 43)
+ sum := sha256.Sum256([]byte(verifier))
+ challenge := base64.RawURLEncoding.EncodeToString(sum[:])
+
+ authorizeQuery := url.Values{
+ "response_type": {"code"},
+ "client_id": {clientID},
+ "redirect_uri": {testRedirect},
+ "code_challenge": {challenge},
+ "code_challenge_method": {"S256"},
+ "resource": {testResource},
+ "scope": {"mcp"},
+ "state": {"state-123"},
+ }
+
+ resp, err := app.Test(httptest.NewRequest("GET", "/oauth/authorize?"+authorizeQuery.Encode(), nil))
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ loginBody, err := io.ReadAll(resp.Body)
+ require.NoError(t, err)
+ assert.Contains(t, string(loginBody), "Authorize Claude")
+ assert.Contains(t, string(loginBody), "After authorization, you'll continue to <strong>claude.ai</strong>.")
+ assert.Equal(t, "no-store", resp.Header.Get("Cache-Control"))
+ assert.Contains(t, resp.Header.Get("Content-Security-Policy"), "frame-ancestors 'none'")
+ assert.Contains(t, resp.Header.Get("Content-Security-Policy"), "form-action 'self' https://claude.ai;")
+
+ loginForm := authorizeQuery
+ loginForm.Set("username", "user")
+ loginForm.Set("password", "secret")
+ loginReq := httptest.NewRequest("POST", "/oauth/authorize", strings.NewReader(loginForm.Encode()))
+ loginReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ resp, err = app.Test(loginReq)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusFound, resp.StatusCode)
+
+ callback, err := url.Parse(resp.Header.Get("Location"))
+ require.NoError(t, err)
+ code := callback.Query().Get("code")
+ require.NotEmpty(t, code)
+ assert.Equal(t, "state-123", callback.Query().Get("state"))
+ assert.Equal(t, testIssuer, callback.Query().Get("iss"))
+
+ tokens := exchangeTestCode(t, app, clientID, code, verifier, testResource)
+ require.NotEmpty(t, tokens.AccessToken)
+ require.NotEmpty(t, tokens.RefreshToken)
+ assert.Equal(t, "Bearer", tokens.TokenType)
+ assert.Positive(t, tokens.ExpiresIn)
+
+ protected := app.Group("", srv.MCPAuthMiddleware(func(username, password string) bool {
+ return username == "user" && password == "secret"
+ }))
+ protected.Post("/mcp", func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusNoContent) })
+
+ bearerReq := httptest.NewRequest("POST", "/mcp", nil)
+ bearerReq.Header.Set("Authorization", "Bearer "+tokens.AccessToken)
+ resp, err = app.Test(bearerReq)
+ require.NoError(t, err)
+ assert.Equal(t, fiber.StatusNoContent, resp.StatusCode)
+
+ basicReq := httptest.NewRequest("POST", "/mcp", nil)
+ basicReq.SetBasicAuth("user", "secret")
+ resp, err = app.Test(basicReq)
+ require.NoError(t, err)
+ assert.Equal(t, fiber.StatusNoContent, resp.StatusCode)
+
+ resp, err = app.Test(httptest.NewRequest("POST", "/mcp", nil))
+ require.NoError(t, err)
+ assert.Equal(t, fiber.StatusUnauthorized, resp.StatusCode)
+ assert.Contains(t, resp.Header.Get("WWW-Authenticate"), `Bearer resource_metadata="https://gowa.example.com/.well-known/oauth-protected-resource/mcp"`)
+}
+
+func TestTokenExchangeRejectsWrongResourceAndCodeReplay(t *testing.T) {
+ _, app := newOAuthTestServer(t, testIssuer, testResource)
+ clientID := registerTestClient(t, app)
+ code, verifier := authorizeTestClient(t, app, clientID)
+
+ bad := url.Values{
+ "grant_type": {"authorization_code"},
+ "client_id": {clientID},
+ "code": {code},
+ "redirect_uri": {testRedirect},
+ "code_verifier": {verifier},
+ "resource": {"https://gowa.example.com/other"},
+ }
+ resp := postForm(t, app, "/oauth/token", bad)
+ assert.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
+ assertOAuthError(t, resp, "invalid_target")
+
+ _ = exchangeTestCode(t, app, clientID, code, verifier, testResource)
+
+ replay := url.Values{
+ "grant_type": {"authorization_code"},
+ "client_id": {clientID},
+ "code": {code},
+ "redirect_uri": {testRedirect},
+ "code_verifier": {verifier},
+ "resource": {testResource},
+ }
+ resp = postForm(t, app, "/oauth/token", replay)
+ assert.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
+ assertOAuthError(t, resp, "invalid_grant")
+}
+
+func TestRefreshRotationDetectsReuseAndRevokesFamily(t *testing.T) {
+ srv, app := newOAuthTestServer(t, testIssuer, testResource)
+ clientID := registerTestClient(t, app)
+ code, verifier := authorizeTestClient(t, app, clientID)
+ initial := exchangeTestCode(t, app, clientID, code, verifier, testResource)
+
+ firstRefresh := url.Values{
+ "grant_type": {"refresh_token"},
+ "client_id": {clientID},
+ "refresh_token": {initial.RefreshToken},
+ "resource": {testResource},
+ }
+ resp := postForm(t, app, "/oauth/token", firstRefresh)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ var rotated tokenResponse
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&rotated))
+ require.NotEmpty(t, rotated.AccessToken)
+ require.NotEmpty(t, rotated.RefreshToken)
+ assert.NotEqual(t, initial.RefreshToken, rotated.RefreshToken)
+
+ resp = postForm(t, app, "/oauth/token", firstRefresh)
+ require.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
+ assertOAuthError(t, resp, "invalid_grant")
+
+ protected := app.Group("", srv.MCPAuthMiddleware(nil))
+ protected.Post("/mcp", func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusNoContent) })
+ bearerReq := httptest.NewRequest("POST", "/mcp", nil)
+ bearerReq.Header.Set("Authorization", "Bearer "+rotated.AccessToken)
+ resp, err := app.Test(bearerReq)
+ require.NoError(t, err)
+ assert.Equal(t, fiber.StatusUnauthorized, resp.StatusCode, "reuse must revoke access tokens in the refresh family")
+}
+
+func registerTestClient(t *testing.T, app *fiber.App) string {
+ t.Helper()
+ body := `{"client_name":"Claude","redirect_uris":["https://claude.ai/api/mcp/auth_callback"],"application_type":"web","token_endpoint_auth_method":"none"}`
+ req := httptest.NewRequest("POST", "/oauth/register", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusCreated, resp.StatusCode)
+ var payload struct {
+ ClientID string `json:"client_id"`
+ }
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&payload))
+ require.NotEmpty(t, payload.ClientID)
+ return payload.ClientID
+}
+
+func authorizeTestClient(t *testing.T, app *fiber.App, clientID string) (string, string) {
+ t.Helper()
+ verifier := strings.Repeat("b", 43)
+ sum := sha256.Sum256([]byte(verifier))
+ challenge := base64.RawURLEncoding.EncodeToString(sum[:])
+ form := url.Values{
+ "response_type": {"code"},
+ "client_id": {clientID},
+ "redirect_uri": {testRedirect},
+ "code_challenge": {challenge},
+ "code_challenge_method": {"S256"},
+ "resource": {testResource},
+ "scope": {"mcp"},
+ "state": {"state-123"},
+ "username": {"user"},
+ "password": {"secret"},
+ }
+ resp := postForm(t, app, "/oauth/authorize", form)
+ require.Equal(t, fiber.StatusFound, resp.StatusCode)
+ callback, err := url.Parse(resp.Header.Get("Location"))
+ require.NoError(t, err)
+ code := callback.Query().Get("code")
+ require.NotEmpty(t, code)
+ return code, verifier
+}
+
+func exchangeTestCode(t *testing.T, app *fiber.App, clientID, code, verifier, resource string) tokenResponse {
+ t.Helper()
+ form := url.Values{
+ "grant_type": {"authorization_code"},
+ "client_id": {clientID},
+ "code": {code},
+ "redirect_uri": {testRedirect},
+ "code_verifier": {verifier},
+ "resource": {resource},
+ }
+ resp := postForm(t, app, "/oauth/token", form)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ var payload tokenResponse
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&payload))
+ return payload
+}
+
+func postForm(t *testing.T, app *fiber.App, path string, form url.Values) *http.Response {
+ t.Helper()
+ req := httptest.NewRequest("POST", path, strings.NewReader(form.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ return resp
+}
+
+func assertOAuthError(t *testing.T, resp *http.Response, want string) {
+ t.Helper()
+ var payload map[string]any
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&payload))
+ assert.Equal(t, want, payload["error"])
+}
diff --git a/src/ui/mcp/oauth/store.go b/src/ui/mcp/oauth/store.go
new file mode 100644
index 00000000..46c02b92
--- /dev/null
+++ b/src/ui/mcp/oauth/store.go
@@ -0,0 +1,535 @@
+package oauth
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/subtle"
+ "database/sql"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sqlite"
+)
+
+type store struct {
+ db *sql.DB
+ maxClients int
+ maxRegistrationsPerWindow int
+ registrationWindow time.Duration
+ unusedClientTTL time.Duration
+}
+
+const (
+ defaultMaxClients = 1000
+ defaultMaxRegistrationsPerWindow = 40
+ defaultRegistrationWindow = time.Hour
+ defaultUnusedClientTTL = 24 * time.Hour
+)
+
+const oauthSchema = `
+CREATE TABLE IF NOT EXISTS oauth_clients (
+ client_id TEXT PRIMARY KEY,
+ client_name TEXT NOT NULL,
+ redirect_uris_json TEXT NOT NULL,
+ application_type TEXT NOT NULL,
+ token_endpoint_auth_method TEXT NOT NULL,
+ created_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS idx_oauth_clients_created_at ON oauth_clients(created_at);
+CREATE TABLE IF NOT EXISTS oauth_authorization_codes (
+ code_hash TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL,
+ subject TEXT NOT NULL,
+ redirect_uri TEXT NOT NULL,
+ code_challenge TEXT NOT NULL,
+ resource TEXT NOT NULL,
+ scope TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ used_at INTEGER,
+ created_at INTEGER NOT NULL,
+ FOREIGN KEY (client_id) REFERENCES oauth_clients(client_id) ON DELETE CASCADE
+);
+CREATE INDEX IF NOT EXISTS idx_oauth_codes_expires_at ON oauth_authorization_codes(expires_at);
+CREATE INDEX IF NOT EXISTS idx_oauth_codes_client_id ON oauth_authorization_codes(client_id);
+CREATE TABLE IF NOT EXISTS oauth_tokens (
+ token_hash TEXT PRIMARY KEY,
+ token_type TEXT NOT NULL CHECK (token_type IN ('access', 'refresh')),
+ family_id TEXT NOT NULL,
+ client_id TEXT NOT NULL,
+ subject TEXT NOT NULL,
+ resource TEXT NOT NULL,
+ scope TEXT NOT NULL,
+ expires_at INTEGER NOT NULL,
+ revoked_at INTEGER,
+ created_at INTEGER NOT NULL,
+ 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_expires_at ON oauth_tokens(expires_at);
+CREATE INDEX IF NOT EXISTS idx_oauth_tokens_client_id ON oauth_tokens(client_id);
+`
+
+func openStore(uri string) (*store, error) {
+ db, err := sql.Open(sqlite.DriverName, sqlite.FormatChatStorageURI(uri, true, true))
+ if err != nil {
+ return nil, fmt.Errorf("open oauth storage: %w", err)
+ }
+ // OAuth writes are low-volume and transaction-sensitive. One connection
+ // avoids SQLite write races while still keeping WAL enabled for durability.
+ db.SetMaxOpenConns(1)
+
+ ctx := context.Background()
+ if err := db.PingContext(ctx); err != nil {
+ _ = db.Close()
+ return nil, fmt.Errorf("ping oauth storage: %w", err)
+ }
+ if _, err := db.ExecContext(ctx, oauthSchema); err != nil {
+ _ = db.Close()
+ return nil, fmt.Errorf("initialize oauth storage: %w", err)
+ }
+ return &store{
+ db: db,
+ maxClients: defaultMaxClients,
+ maxRegistrationsPerWindow: defaultMaxRegistrationsPerWindow,
+ registrationWindow: defaultRegistrationWindow,
+ unusedClientTTL: defaultUnusedClientTTL,
+ }, nil
+}
+
+func (s *store) Close() error {
+ if s == nil || s.db == nil {
+ return nil
+ }
+ return s.db.Close()
+}
+
+func (s *store) createClient(ctx context.Context, client Client) error {
+ return insertClient(ctx, s.db, client)
+}
+
+type execer interface {
+ ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
+}
+
+func insertClient(ctx context.Context, ex execer, client Client) error {
+ redirects, err := json.Marshal(client.RedirectURIs)
+ if err != nil {
+ return fmt.Errorf("encode oauth redirect URIs: %w", err)
+ }
+ _, err = ex.ExecContext(ctx, `
+INSERT INTO oauth_clients (
+ client_id, client_name, redirect_uris_json, application_type,
+ token_endpoint_auth_method, created_at
+) VALUES (?, ?, ?, ?, ?, ?)`,
+ client.ID,
+ client.Name,
+ string(redirects),
+ client.ApplicationType,
+ client.TokenEndpointAuthMethod,
+ client.CreatedAt.Unix(),
+ )
+ if err != nil {
+ return fmt.Errorf("store oauth client: %w", err)
+ }
+ return nil
+}
+
+// registerClient applies durable global bounds to the unauthenticated DCR
+// surface. The database-backed window works across process restarts, and the
+// total cap prevents registrations from growing the SQLite file indefinitely.
+func (s *store) registerClient(ctx context.Context, client Client) error {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback() }()
+
+ if err := cleanupExpiredTx(ctx, tx, client.CreatedAt); err != nil {
+ return err
+ }
+ if err := cleanupUnusedClientsTx(ctx, tx, client.CreatedAt.Add(-s.unusedClientTTL)); err != nil {
+ return err
+ }
+ var total int
+ if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM oauth_clients`).Scan(&total); err != nil {
+ return err
+ }
+ if total >= s.maxClients {
+ return ErrRegistrationLimit
+ }
+ var recent int
+ windowStart := client.CreatedAt.Add(-s.registrationWindow).Unix()
+ if err := tx.QueryRowContext(ctx, `
+SELECT COUNT(*) FROM oauth_clients WHERE created_at > ?`, windowStart).Scan(&recent); err != nil {
+ return err
+ }
+ if recent >= s.maxRegistrationsPerWindow {
+ return ErrRegistrationLimit
+ }
+
+ if err := insertClient(ctx, tx, client); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+func (s *store) getClient(ctx context.Context, clientID string) (Client, error) {
+ var (
+ client Client
+ redirectsJSON string
+ createdAt int64
+ )
+ err := s.db.QueryRowContext(ctx, `
+SELECT client_id, client_name, redirect_uris_json, application_type,
+ token_endpoint_auth_method, created_at
+FROM oauth_clients WHERE client_id = ?`, clientID).Scan(
+ &client.ID,
+ &client.Name,
+ &redirectsJSON,
+ &client.ApplicationType,
+ &client.TokenEndpointAuthMethod,
+ &createdAt,
+ )
+ if err != nil {
+ return Client{}, err
+ }
+ if err := json.Unmarshal([]byte(redirectsJSON), &client.RedirectURIs); err != nil {
+ return Client{}, fmt.Errorf("decode oauth redirect URIs: %w", err)
+ }
+ client.CreatedAt = time.Unix(createdAt, 0).UTC()
+ return client, nil
+}
+
+func (s *store) issueAuthorizationCode(ctx context.Context, grant AuthorizationGrant, now time.Time, ttl time.Duration) (string, error) {
+ code, err := randomSecret("gowa_code_", 32)
+ if err != nil {
+ return "", err
+ }
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return "", err
+ }
+ defer func() { _ = tx.Rollback() }()
+ if err := cleanupExpiredTx(ctx, tx, now); err != nil {
+ return "", err
+ }
+ _, err = tx.ExecContext(ctx, `
+INSERT INTO oauth_authorization_codes (
+ code_hash, client_id, subject, redirect_uri, code_challenge,
+ resource, scope, expires_at, created_at
+) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ hashSecret(code),
+ grant.ClientID,
+ grant.Subject,
+ grant.RedirectURI,
+ grant.CodeChallenge,
+ grant.Resource,
+ grant.Scope,
+ now.Add(ttl).Unix(),
+ now.Unix(),
+ )
+ if err != nil {
+ return "", fmt.Errorf("store authorization code: %w", err)
+ }
+ if err := tx.Commit(); err != nil {
+ return "", err
+ }
+ return code, nil
+}
+
+func (s *store) exchangeAuthorizationCode(
+ ctx context.Context,
+ req CodeExchange,
+ now time.Time,
+ accessTTL time.Duration,
+ refreshTTL time.Duration,
+) (TokenPair, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return TokenPair{}, err
+ }
+ defer func() { _ = tx.Rollback() }()
+ if err := cleanupExpiredTx(ctx, tx, now); err != nil {
+ return TokenPair{}, err
+ }
+
+ var (
+ clientID string
+ subject string
+ redirectURI string
+ codeChallenge string
+ resource string
+ scope string
+ expiresAt int64
+ usedAt sql.NullInt64
+ )
+ err = tx.QueryRowContext(ctx, `
+SELECT client_id, subject, redirect_uri, code_challenge, resource, scope,
+ expires_at, used_at
+FROM oauth_authorization_codes
+WHERE code_hash = ?`, hashSecret(req.Code)).Scan(
+ &clientID,
+ &subject,
+ &redirectURI,
+ &codeChallenge,
+ &resource,
+ &scope,
+ &expiresAt,
+ &usedAt,
+ )
+ if errors.Is(err, sql.ErrNoRows) {
+ return TokenPair{}, ErrInvalidGrant
+ }
+ if err != nil {
+ return TokenPair{}, err
+ }
+ if usedAt.Valid || now.Unix() >= expiresAt || clientID != req.ClientID || redirectURI != req.RedirectURI {
+ return TokenPair{}, ErrInvalidGrant
+ }
+ if resource != req.Resource {
+ return TokenPair{}, ErrInvalidTarget
+ }
+ if !verifyPKCES256(req.CodeVerifier, codeChallenge) {
+ return TokenPair{}, ErrInvalidGrant
+ }
+
+ result, err := tx.ExecContext(ctx, `
+UPDATE oauth_authorization_codes
+SET used_at = ?
+WHERE code_hash = ? AND used_at IS NULL`, now.Unix(), hashSecret(req.Code))
+ if err != nil {
+ return TokenPair{}, err
+ }
+ rows, err := result.RowsAffected()
+ if err != nil || rows != 1 {
+ return TokenPair{}, ErrInvalidGrant
+ }
+
+ familyID, err := randomSecret("gowa_family_", 18)
+ if err != nil {
+ return TokenPair{}, err
+ }
+ pair, err := issueTokenPairTx(ctx, tx, familyID, clientID, subject, resource, scope, now, accessTTL, refreshTTL)
+ if err != nil {
+ return TokenPair{}, err
+ }
+ if err := tx.Commit(); err != nil {
+ return TokenPair{}, err
+ }
+ return pair, nil
+}
+
+func (s *store) rotateRefreshToken(
+ ctx context.Context,
+ req RefreshExchange,
+ now time.Time,
+ accessTTL time.Duration,
+ refreshTTL time.Duration,
+) (TokenPair, error) {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return TokenPair{}, err
+ }
+ defer func() { _ = tx.Rollback() }()
+ if err := cleanupExpiredTx(ctx, tx, now); err != nil {
+ return TokenPair{}, err
+ }
+
+ var (
+ familyID string
+ clientID string
+ subject string
+ resource string
+ scope string
+ expiresAt int64
+ revokedAt sql.NullInt64
+ )
+ err = tx.QueryRowContext(ctx, `
+SELECT family_id, client_id, subject, resource, scope, expires_at, revoked_at
+FROM oauth_tokens
+WHERE token_hash = ? AND token_type = 'refresh'`, hashSecret(req.RefreshToken)).Scan(
+ &familyID,
+ &clientID,
+ &subject,
+ &resource,
+ &scope,
+ &expiresAt,
+ &revokedAt,
+ )
+ if errors.Is(err, sql.ErrNoRows) {
+ return TokenPair{}, ErrInvalidGrant
+ }
+ if err != nil {
+ return TokenPair{}, err
+ }
+ 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 {
+ return TokenPair{}, err
+ }
+ if err := tx.Commit(); err != nil {
+ return TokenPair{}, err
+ }
+ return TokenPair{}, ErrRefreshReuse
+ }
+ if now.Unix() >= expiresAt || clientID != req.ClientID {
+ return TokenPair{}, ErrInvalidGrant
+ }
+ if resource != req.Resource {
+ return TokenPair{}, ErrInvalidTarget
+ }
+
+ result, err := tx.ExecContext(ctx, `
+UPDATE oauth_tokens
+SET revoked_at = ?
+WHERE token_hash = ? AND token_type = 'refresh' AND revoked_at IS NULL`,
+ now.Unix(), hashSecret(req.RefreshToken))
+ if err != nil {
+ return TokenPair{}, err
+ }
+ rows, err := result.RowsAffected()
+ if err != nil || rows != 1 {
+ return TokenPair{}, ErrInvalidGrant
+ }
+
+ pair, err := issueTokenPairTx(ctx, tx, familyID, clientID, subject, resource, scope, now, accessTTL, refreshTTL)
+ if err != nil {
+ return TokenPair{}, err
+ }
+ if err := tx.Commit(); err != nil {
+ return TokenPair{}, err
+ }
+ return pair, nil
+}
+
+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 {
+ return fmt.Errorf("delete expired oauth tokens: %w", err)
+ }
+ return nil
+}
+
+func cleanupUnusedClientsTx(ctx context.Context, tx *sql.Tx, cutoff time.Time) error {
+ if _, err := tx.ExecContext(ctx, `
+DELETE FROM oauth_clients
+WHERE created_at <= ?
+ AND NOT EXISTS (
+ SELECT 1 FROM oauth_authorization_codes
+ WHERE oauth_authorization_codes.client_id = oauth_clients.client_id
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM oauth_tokens
+ WHERE oauth_tokens.client_id = oauth_clients.client_id
+ )`, cutoff.Unix()); err != nil {
+ return fmt.Errorf("delete unused oauth clients: %w", err)
+ }
+ return nil
+}
+
+func (s *store) validateAccessToken(ctx context.Context, rawToken, resource string, now time.Time) (Principal, error) {
+ var (
+ principal Principal
+ storedTarget string
+ expiresAt int64
+ revokedAt sql.NullInt64
+ )
+ err := s.db.QueryRowContext(ctx, `
+SELECT subject, client_id, scope, resource, expires_at, revoked_at
+FROM oauth_tokens
+WHERE token_hash = ? AND token_type = 'access'`, hashSecret(rawToken)).Scan(
+ &principal.Subject,
+ &principal.ClientID,
+ &principal.Scope,
+ &storedTarget,
+ &expiresAt,
+ &revokedAt,
+ )
+ if errors.Is(err, sql.ErrNoRows) {
+ return Principal{}, ErrInvalidToken
+ }
+ if err != nil {
+ return Principal{}, err
+ }
+ if revokedAt.Valid || now.Unix() >= expiresAt || storedTarget != resource {
+ return Principal{}, ErrInvalidToken
+ }
+ return principal, nil
+}
+
+func issueTokenPairTx(
+ ctx context.Context,
+ tx *sql.Tx,
+ familyID,
+ clientID,
+ subject,
+ resource,
+ scope string,
+ now time.Time,
+ accessTTL,
+ refreshTTL time.Duration,
+) (TokenPair, error) {
+ accessToken, err := randomSecret("gowa_at_", 32)
+ if err != nil {
+ return TokenPair{}, err
+ }
+ refreshToken, err := randomSecret("gowa_rt_", 32)
+ if err != nil {
+ return TokenPair{}, err
+ }
+ if _, err := tx.ExecContext(ctx, `
+INSERT INTO oauth_tokens (
+ token_hash, token_type, family_id, client_id, subject, resource, scope,
+ expires_at, created_at
+) VALUES (?, 'access', ?, ?, ?, ?, ?, ?, ?)`,
+ hashSecret(accessToken), familyID, clientID, subject, resource, scope,
+ now.Add(accessTTL).Unix(), now.Unix()); err != nil {
+ return TokenPair{}, err
+ }
+ if _, err := tx.ExecContext(ctx, `
+INSERT INTO oauth_tokens (
+ token_hash, token_type, family_id, client_id, subject, resource, scope,
+ expires_at, created_at
+) VALUES (?, 'refresh', ?, ?, ?, ?, ?, ?, ?)`,
+ hashSecret(refreshToken), familyID, clientID, subject, resource, scope,
+ now.Add(refreshTTL).Unix(), now.Unix()); err != nil {
+ return TokenPair{}, err
+ }
+ return TokenPair{
+ AccessToken: accessToken,
+ RefreshToken: refreshToken,
+ ExpiresIn: int64(accessTTL / time.Second),
+ Scope: scope,
+ }, nil
+}
+
+func hashSecret(secret string) string {
+ sum := sha256.Sum256([]byte(secret))
+ return hex.EncodeToString(sum[:])
+}
+
+func verifyPKCES256(verifier, challenge string) bool {
+ if verifier == "" || challenge == "" {
+ return false
+ }
+ sum := sha256.Sum256([]byte(verifier))
+ got := base64.RawURLEncoding.EncodeToString(sum[:])
+ return subtle.ConstantTimeCompare([]byte(got), []byte(challenge)) == 1
+}
+
+func randomSecret(prefix string, byteLen int) (string, error) {
+ buf := make([]byte, byteLen)
+ if _, err := rand.Read(buf); err != nil {
+ return "", fmt.Errorf("generate oauth secret: %w", err)
+ }
+ return prefix + base64.RawURLEncoding.EncodeToString(buf), nil
+}
diff --git a/src/ui/mcp/oauth/store_test.go b/src/ui/mcp/oauth/store_test.go
new file mode 100644
index 00000000..cfc6af96
--- /dev/null
+++ b/src/ui/mcp/oauth/store_test.go
@@ -0,0 +1,196 @@
+package oauth
+
+import (
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/base64"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestStorePersistsOnlyHashesForCodesAndTokens(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, 7, 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))
+ challenge := base64.RawURLEncoding.EncodeToString(sum[:])
+ code, err := store.issueAuthorizationCode(ctx, AuthorizationGrant{
+ ClientID: client.ID,
+ Subject: "user",
+ RedirectURI: testRedirect,
+ CodeChallenge: challenge,
+ Resource: testResource,
+ Scope: "mcp",
+ }, now, 5*time.Minute)
+ require.NoError(t, err)
+
+ var storedCodeHash string
+ require.NoError(t, store.db.QueryRowContext(ctx, `SELECT code_hash FROM oauth_authorization_codes`).Scan(&storedCodeHash))
+ assert.Equal(t, hashSecret(code), storedCodeHash)
+ assert.NotEqual(t, code, storedCodeHash)
+
+ pair, err := store.exchangeAuthorizationCode(ctx, CodeExchange{
+ ClientID: client.ID,
+ Code: code,
+ RedirectURI: testRedirect,
+ CodeVerifier: verifier,
+ Resource: testResource,
+ }, now.Add(time.Minute), time.Hour, 30*24*time.Hour)
+ require.NoError(t, err)
+
+ rows, err := store.db.QueryContext(ctx, `SELECT token_hash FROM oauth_tokens ORDER BY token_type`)
+ require.NoError(t, err)
+ defer func() { require.NoError(t, rows.Close()) }()
+ var hashes []string
+ for rows.Next() {
+ var hash string
+ require.NoError(t, rows.Scan(&hash))
+ hashes = append(hashes, hash)
+ }
+ require.NoError(t, rows.Err())
+ require.Len(t, hashes, 2)
+ assert.Contains(t, hashes, hashSecret(pair.AccessToken))
+ assert.Contains(t, hashes, hashSecret(pair.RefreshToken))
+ assert.NotContains(t, hashes, pair.AccessToken)
+ assert.NotContains(t, hashes, pair.RefreshToken)
+}
+
+func TestStoreAccessTokenIsBoundToResource(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.Now().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, 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, 30*24*time.Hour)
+ require.NoError(t, err)
+
+ principal, err := store.validateAccessToken(ctx, pair.AccessToken, testResource, now.Add(time.Minute))
+ require.NoError(t, err)
+ assert.Equal(t, "user", principal.Subject)
+
+ _, err = store.validateAccessToken(ctx, pair.AccessToken, "https://gowa.example.com/other", now.Add(time.Minute))
+ assert.ErrorIs(t, err, ErrInvalidToken)
+}
+
+func TestStorePrunesExpiredCodesAndTokensBeforeWrites(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, 9, 0, 0, 0, time.UTC)
+ client := Client{ID: "client-1", Name: "Claude", RedirectURIs: []string{testRedirect}, ApplicationType: "web", TokenEndpointAuthMethod: "none", CreatedAt: now.Add(-time.Hour)}
+ require.NoError(t, store.createClient(ctx, client))
+ _, err = store.db.ExecContext(ctx, `
+INSERT INTO oauth_authorization_codes (
+ code_hash, client_id, subject, redirect_uri, code_challenge,
+ resource, scope, expires_at, created_at
+) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ "expired-code", client.ID, "user", testRedirect, "challenge", testResource, "mcp", now.Add(-time.Minute).Unix(), now.Add(-time.Hour).Unix())
+ require.NoError(t, err)
+ for _, tokenType := range []string{"access", "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 (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ "expired-"+tokenType, tokenType, "family-1", client.ID, "user", testResource, "mcp", now.Add(-time.Minute).Unix(), now.Add(-time.Hour).Unix())
+ require.NoError(t, err)
+ }
+
+ _, err = store.issueAuthorizationCode(ctx, AuthorizationGrant{
+ ClientID: client.ID, Subject: "user", RedirectURI: testRedirect,
+ CodeChallenge: "challenge", Resource: testResource, Scope: "mcp",
+ }, now, time.Minute)
+ require.NoError(t, err)
+
+ var codes, tokens int
+ require.NoError(t, store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM oauth_authorization_codes`).Scan(&codes))
+ require.NoError(t, store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM oauth_tokens`).Scan(&tokens))
+ assert.Equal(t, 1, codes, "the new code remains after expired codes are removed")
+ assert.Zero(t, tokens)
+}
+
+func TestStoreRegistrationPrunesStaleUnusedClients(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, 10, 0, 0, 0, time.UTC)
+ store.maxClients = 1
+ store.maxRegistrationsPerWindow = 10
+ store.unusedClientTTL = time.Hour
+ stale := Client{ID: "stale", Name: "Stale", RedirectURIs: []string{testRedirect}, ApplicationType: "web", TokenEndpointAuthMethod: "none", CreatedAt: now.Add(-2 * time.Hour)}
+ require.NoError(t, store.createClient(ctx, stale))
+
+ fresh := Client{ID: "fresh", Name: "Fresh", RedirectURIs: []string{testRedirect}, ApplicationType: "web", TokenEndpointAuthMethod: "none", CreatedAt: now}
+ require.NoError(t, store.registerClient(ctx, fresh))
+
+ _, err = store.getClient(ctx, stale.ID)
+ assert.ErrorIs(t, err, sql.ErrNoRows)
+ stored, err := store.getClient(ctx, fresh.ID)
+ require.NoError(t, err)
+ assert.Equal(t, fresh.ID, stored.ID)
+}
+
+func TestStoreRegistrationRateLimitUsesDurableWindow(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, 11, 0, 0, 0, time.UTC)
+ store.maxClients = 10
+ store.maxRegistrationsPerWindow = 1
+ store.registrationWindow = time.Hour
+ store.unusedClientTTL = 24 * time.Hour
+ client := func(id string, createdAt time.Time) Client {
+ return Client{ID: id, Name: id, RedirectURIs: []string{testRedirect}, ApplicationType: "web", TokenEndpointAuthMethod: "none", CreatedAt: createdAt}
+ }
+
+ require.NoError(t, store.registerClient(ctx, client("first", now)))
+ assert.ErrorIs(t, store.registerClient(ctx, client("blocked", now.Add(time.Minute))), ErrRegistrationLimit)
+ require.NoError(t, store.registerClient(ctx, client("later", now.Add(time.Hour+time.Second))))
+
+ var clients int
+ require.NoError(t, store.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM oauth_clients`).Scan(&clients))
+ assert.Equal(t, 2, clients)
+}
diff --git a/src/ui/mcp/oauth/types.go b/src/ui/mcp/oauth/types.go
new file mode 100644
index 00000000..1f2c2e05
--- /dev/null
+++ b/src/ui/mcp/oauth/types.go
@@ -0,0 +1,75 @@
+package oauth
+
+import (
+ "errors"
+ "time"
+)
+
+var (
+ ErrInvalidGrant = errors.New("invalid grant")
+ ErrInvalidTarget = errors.New("invalid target")
+ ErrInvalidToken = errors.New("invalid token")
+ ErrRefreshReuse = errors.New("refresh token reuse detected")
+ ErrRegistrationLimit = errors.New("dynamic client registration limit reached")
+)
+
+type CredentialValidator func(username, password string) bool
+
+type Config struct {
+ IssuerURL string
+ ResourceURL string
+ StorageURI string
+}
+
+type Client struct {
+ ID string
+ Name string
+ RedirectURIs []string
+ ApplicationType string
+ TokenEndpointAuthMethod string
+ CreatedAt time.Time
+}
+
+type AuthorizationGrant struct {
+ ClientID string
+ Subject string
+ RedirectURI string
+ CodeChallenge string
+ Resource string
+ Scope string
+}
+
+type CodeExchange struct {
+ ClientID string
+ Code string
+ RedirectURI string
+ CodeVerifier string
+ Resource string
+}
+
+type RefreshExchange struct {
+ ClientID string
+ RefreshToken string
+ Resource string
+}
+
+type TokenPair struct {
+ AccessToken string
+ RefreshToken string
+ ExpiresIn int64
+ Scope string
+}
+
+type Principal struct {
+ Subject string
+ ClientID string
+ Scope string
+}
+
+type tokenResponse struct {
+ AccessToken string `json:"access_token"`
+ TokenType string `json:"token_type"`
+ ExpiresIn int64 `json:"expires_in"`
+ RefreshToken string `json:"refresh_token,omitempty"`
+ Scope string `json:"scope,omitempty"`
+}