⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix: an MCP authorization error reaches the person instead of being lost (#565)
Pasqual Troncone9cf575e8b4cd
diff --git a/apps/api/src/__tests__/integration/auth-urls.test.ts b/apps/api/src/__tests__/integration/auth-urls.test.tsindex 6a2f1bd6..6bd832bc 100644--- a/apps/api/src/__tests__/integration/auth-urls.test.ts+++ b/apps/api/src/__tests__/integration/auth-urls.test.ts@@ -92,13 +92,14 @@ const EMAIL_LINKS = `describe('auth URLs from the environment', () => {beforeEach(resetDb);- it('leaves better-auth its own error page when API_URL has no path', async () => {+ // better-auth's own error page redirects a production browser to the api's root.+ it('sends early OAuth failures to the sign-in page when the api has its own host', async () => {const loaded = await runAuth({ API_URL: 'http://localhost:3000/', APP_URL: 'http://app.test' },ERROR_URL,);- expect(loaded.errorURL).toBeNull();+ expect(loaded.errorURL).toBe('http://app.test/login');});it('sends early OAuth failures to the sign-in page when API_URL has a path', async () => {diff --git a/apps/api/src/__tests__/integration/mcp-authorize-consent.test.ts b/apps/api/src/__tests__/integration/mcp-authorize-consent.test.tsindex 902012df..a4f2be94 100644--- a/apps/api/src/__tests__/integration/mcp-authorize-consent.test.ts+++ b/apps/api/src/__tests__/integration/mcp-authorize-consent.test.ts@@ -75,4 +75,55 @@ describe('MCP authorization asks for consent', () => {const { url } = (await res.json()) as { url: string };expect(new URL(url).pathname).toBe('/oauth/consent');});++ // The api cannot send this error back to a client it does not know, so the person sees+ // it: on the web's sign-in screen, in either form of API_URL.+ it('sends an authorization for an unknown client to the sign-in screen with the reason', async () => {+ const res = await app.handle(+ new Request(+ `http://localhost/api/auth/oauth2/authorize?${new URLSearchParams({+ response_type: 'code',+ client_id: 'no-such-client',+ redirect_uri: 'https://client.example.com/callback',+ code_challenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',+ code_challenge_method: 'S256',+ state: 'st',+ })}`,+ ),+ );++ const location = new URL(res.headers.get('location') ?? '');+ expect(`${location.origin}${location.pathname}`).toBe(`${process.env.APP_URL}/login`);+ expect(location.searchParams.get('error')).toBe('invalid_client');+ });++ async function authorizeWith(overrides: Record<string, string>): Promise<URL> {+ const params = new URLSearchParams({+ response_type: 'code',+ client_id: await registerClient(),+ redirect_uri: 'https://client.example.com/callback',+ code_challenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',+ code_challenge_method: 'S256',+ state: 'st',+ ...overrides,+ });+ const res = await app.handle(+ new Request(`http://localhost/api/auth/oauth2/authorize?${params}`),+ );+ return new URL(res.headers.get('location') ?? '');+ }++ it('sends an authorization for an unregistered redirect URI to the sign-in screen', async () => {+ const location = await authorizeWith({ redirect_uri: 'https://other.example.com/callback' });++ expect(`${location.origin}${location.pathname}`).toBe(`${process.env.APP_URL}/login`);+ expect(location.searchParams.get('error')).toBe('invalid_redirect');+ });++ it('still answers the client an error it can send back', async () => {+ const location = await authorizeWith({ scope: 'no-such-scope' });++ expect(`${location.origin}${location.pathname}`).toBe('https://client.example.com/callback');+ expect(location.searchParams.get('error')).toBe('invalid_scope');+ });});diff --git a/apps/web/messages/ar/auth.json b/apps/web/messages/ar/auth.jsonindex bc5c4ed0..211d37da 100644--- a/apps/web/messages/ar/auth.json+++ b/apps/web/messages/ar/auth.json@@ -95,6 +95,9 @@"passwordDisabled": "يتم تسجيل الدخول على هذا الخادم عبر مزوّد الهوية فقط.","accountDeactivated": "هذا الحساب معطّل. اطلب من المسؤول إعادة تفعيله.","registrationClosed": "هذه النسخة لا تقبل حسابات جديدة. اطلب الوصول من المسؤول.",- "inviteOnly": "هذه النسخة تقبل المدعوّين فقط. اطلب دعوة من المسؤول."+ "inviteOnly": "هذه النسخة تقبل المدعوّين فقط. اطلب دعوة من المسؤول.",+ "oauthClientUnknown": "التطبيق الذي يطلب الوصول غير مسجّل هنا. أزل هذا الخادم من التطبيق ثم أضفه من جديد ليُسجَّل مرة أخرى.",+ "oauthRedirectUnknown": "طلب التطبيق العودة إلى عنوان لم يسجّله، لذلك أُوقف التفويض. أزل هذا الخادم من التطبيق ثم أضفه من جديد.",+ "oauthClientRefused": "لا يُسمح لهذا التطبيق بالاتصال بحسابك."}}diff --git a/apps/web/messages/en/auth.json b/apps/web/messages/en/auth.jsonindex 01c123cb..fd6f5bf7 100644--- a/apps/web/messages/en/auth.json+++ b/apps/web/messages/en/auth.json@@ -95,6 +95,9 @@"passwordDisabled": "This instance signs people in through its identity provider only.","accountDeactivated": "This account is deactivated. Ask your administrator to restore it.","registrationClosed": "This instance is not open for new accounts. Ask your administrator for access.",- "inviteOnly": "This instance only admits people who have been invited. Ask your administrator for an invite."+ "inviteOnly": "This instance only admits people who have been invited. Ask your administrator for an invite.",+ "oauthClientUnknown": "The app asking for access is not registered here. Remove this server from the app and add it again, so that it registers anew.",+ "oauthRedirectUnknown": "The app asked to come back to an address it has not registered, so the authorization was stopped. Remove this server from the app and add it again.",+ "oauthClientRefused": "This app is not allowed to connect to your account."}}diff --git a/apps/web/messages/es-ES/auth.json b/apps/web/messages/es-ES/auth.jsonindex 3d772ecd..dae7ab39 100644--- a/apps/web/messages/es-ES/auth.json+++ b/apps/web/messages/es-ES/auth.json@@ -95,6 +95,9 @@"passwordDisabled": "Esta instancia inicia sesión de las personas solo a través de su proveedor de identidades.","accountDeactivated": "Esta cuenta está desactivada. Pide a tu administrador que la restaure.","registrationClosed": "Esta instancia no admite cuentas nuevas. Pide acceso a tu administrador.",- "inviteOnly": "Esta instancia solo admite a quienes han sido invitados. Pide una invitación a tu administrador."+ "inviteOnly": "Esta instancia solo admite a quienes han sido invitados. Pide una invitación a tu administrador.",+ "oauthClientUnknown": "La aplicación que pide acceso no está registrada aquí. Quita este servidor en la aplicación y vuelve a añadirlo para que se registre de nuevo.",+ "oauthRedirectUnknown": "La aplicación pidió volver a una dirección que no tiene registrada, así que se ha detenido la autorización. Quita este servidor en la aplicación y vuelve a añadirlo.",+ "oauthClientRefused": "Esta aplicación no puede conectarse a tu cuenta."}}diff --git a/apps/web/messages/fr/auth.json b/apps/web/messages/fr/auth.jsonindex c765c573..eb1e0aea 100644--- a/apps/web/messages/fr/auth.json+++ b/apps/web/messages/fr/auth.json@@ -95,6 +95,9 @@"passwordDisabled": "Cette instance ne connecte les utilisateurs que via son fournisseur d'identité.","accountDeactivated": "Ce compte est désactivé. Demandez à votre administrateur de le rétablir.","registrationClosed": "Cette instance n'accepte pas de nouveaux comptes. Demandez l'accès à votre administrateur.",- "inviteOnly": "Cette instance n'admet que les personnes invitées. Demandez une invitation à votre administrateur."+ "inviteOnly": "Cette instance n'admet que les personnes invitées. Demandez une invitation à votre administrateur.",+ "oauthClientUnknown": "L’application qui demande l’accès n’est pas enregistrée ici. Retirez ce serveur de l’application puis ajoutez-le de nouveau pour qu’elle s’enregistre à nouveau.",+ "oauthRedirectUnknown": "L’application a demandé à revenir à une adresse qu’elle n’a pas enregistrée ; l’autorisation a donc été arrêtée. Retirez ce serveur de l’application puis ajoutez-le de nouveau.",+ "oauthClientRefused": "Cette application n’est pas autorisée à se connecter à votre compte."}}diff --git a/apps/web/messages/id/auth.json b/apps/web/messages/id/auth.jsonindex 51d4d71f..3abbf4fd 100644--- a/apps/web/messages/id/auth.json+++ b/apps/web/messages/id/auth.json@@ -95,6 +95,9 @@"passwordDisabled": "Instance ini hanya mengizinkan pengguna masuk melalui penyedia identitasnya.","accountDeactivated": "Akun ini telah dinonaktifkan. Minta administrator Anda untuk memulihkannya.","registrationClosed": "Instance ini tidak menerima akun baru. Minta akses kepada administrator Anda.",- "inviteOnly": "Instance ini hanya menerima orang yang diundang. Minta undangan kepada administrator Anda."+ "inviteOnly": "Instance ini hanya menerima orang yang diundang. Minta undangan kepada administrator Anda.",+ "oauthClientUnknown": "Aplikasi yang meminta akses tidak terdaftar di sini. Hapus server ini dari aplikasi lalu tambahkan lagi agar aplikasi mendaftar ulang.",+ "oauthRedirectUnknown": "Aplikasi meminta kembali ke alamat yang tidak didaftarkannya, sehingga otorisasi dihentikan. Hapus server ini dari aplikasi lalu tambahkan lagi.",+ "oauthClientRefused": "Aplikasi ini tidak diizinkan terhubung ke akun Anda."}}diff --git a/apps/web/messages/ko/auth.json b/apps/web/messages/ko/auth.jsonindex 2eb098dc..dc8c2927 100644--- a/apps/web/messages/ko/auth.json+++ b/apps/web/messages/ko/auth.json@@ -95,6 +95,9 @@"passwordDisabled": "이 서버에서는 ID 공급자를 통해서만 로그인할 수 있습니다.","accountDeactivated": "비활성화된 계정입니다. 관리자에게 계정 복구를 요청하세요.","registrationClosed": "이 서버는 새 계정을 받지 않습니다. 관리자에게 접근 권한을 요청하세요.",- "inviteOnly": "이 서버는 초대받은 사람만 가입할 수 있습니다. 관리자에게 초대를 요청하세요."+ "inviteOnly": "이 서버는 초대받은 사람만 가입할 수 있습니다. 관리자에게 초대를 요청하세요.",+ "oauthClientUnknown": "접근을 요청한 앱이 여기에 등록되어 있지 않습니다. 앱에서 이 서버를 제거한 뒤 다시 추가해 새로 등록되게 하세요.",+ "oauthRedirectUnknown": "앱이 등록하지 않은 주소로 돌아가려고 해서 인증이 중단되었습니다. 앱에서 이 서버를 제거한 뒤 다시 추가하세요.",+ "oauthClientRefused": "이 앱은 계정에 연결할 수 없습니다."}}diff --git a/apps/web/messages/pt-BR/auth.json b/apps/web/messages/pt-BR/auth.jsonindex 5e7d6742..89cc5a15 100644--- a/apps/web/messages/pt-BR/auth.json+++ b/apps/web/messages/pt-BR/auth.json@@ -95,6 +95,9 @@"passwordDisabled": "Esta instância conecta pessoas apenas pelo seu provedor de identidade.","accountDeactivated": "Esta conta está desativada. Peça ao seu administrador para restaurá-la.","registrationClosed": "Esta instância não aceita contas novas. Peça acesso ao seu administrador.",- "inviteOnly": "Esta instância só admite pessoas convidadas. Peça um convite ao seu administrador."+ "inviteOnly": "Esta instância só admite pessoas convidadas. Peça um convite ao seu administrador.",+ "oauthClientUnknown": "O aplicativo que pede acesso não está registrado aqui. Remova este servidor do aplicativo e adicione-o de novo para que ele se registre novamente.",+ "oauthRedirectUnknown": "O aplicativo pediu para voltar a um endereço que não registrou, então a autorização foi interrompida. Remova este servidor do aplicativo e adicione-o de novo.",+ "oauthClientRefused": "Este aplicativo não tem permissão para se conectar à sua conta."}}diff --git a/apps/web/messages/ru/auth.json b/apps/web/messages/ru/auth.jsonindex a8c04246..76f153cd 100644--- a/apps/web/messages/ru/auth.json+++ b/apps/web/messages/ru/auth.json@@ -95,6 +95,9 @@"passwordDisabled": "На этом сервере вход выполняется только через поставщика удостоверений.","accountDeactivated": "Учётная запись отключена. Обратитесь к администратору.","registrationClosed": "Этот инстанс не принимает новые учётные записи. Запросите доступ у администратора.",- "inviteOnly": "В этот инстанс допускаются только приглашённые. Попросите приглашение у администратора."+ "inviteOnly": "В этот инстанс допускаются только приглашённые. Попросите приглашение у администратора.",+ "oauthClientUnknown": "Приложение, запрашивающее доступ, здесь не зарегистрировано. Удалите этот сервер в приложении и добавьте его снова, чтобы оно зарегистрировалось заново.",+ "oauthRedirectUnknown": "Приложение запросило возврат на адрес, который оно не регистрировало, поэтому авторизация остановлена. Удалите этот сервер в приложении и добавьте его снова.",+ "oauthClientRefused": "Этому приложению запрещено подключаться к вашему аккаунту."}}diff --git a/apps/web/messages/uk/auth.json b/apps/web/messages/uk/auth.jsonindex e8951bf6..10e56bf3 100644--- a/apps/web/messages/uk/auth.json+++ b/apps/web/messages/uk/auth.json@@ -95,6 +95,9 @@"passwordDisabled": "На цьому сервері вхід виконується лише через постачальника ідентифікації.","accountDeactivated": "Обліковий запис вимкнено. Зверніться до адміністратора.","registrationClosed": "Цей інстанс не приймає нових облікових записів. Попросіть доступ в адміністратора.",- "inviteOnly": "До цього інстансу допускаються лише запрошені. Попросіть запрошення в адміністратора."+ "inviteOnly": "До цього інстансу допускаються лише запрошені. Попросіть запрошення в адміністратора.",+ "oauthClientUnknown": "Застосунок, що запитує доступ, тут не зареєстрований. Видаліть цей сервер у застосунку й додайте його знову, щоб він зареєструвався повторно.",+ "oauthRedirectUnknown": "Застосунок попросив повернутися на адресу, яку не реєстрував, тому авторизацію зупинено. Видаліть цей сервер у застосунку й додайте його знову.",+ "oauthClientRefused": "Цьому застосунку не дозволено під’єднуватися до вашого облікового запису."}}diff --git a/apps/web/messages/zh-CN/auth.json b/apps/web/messages/zh-CN/auth.jsonindex e6018626..c164c89c 100644--- a/apps/web/messages/zh-CN/auth.json+++ b/apps/web/messages/zh-CN/auth.json@@ -95,6 +95,9 @@"passwordDisabled": "此实例仅通过身份提供方登录。","accountDeactivated": "该账号已停用,请联系管理员恢复。","registrationClosed": "此实例不接受新账户,请联系管理员申请访问权限。",- "inviteOnly": "此实例仅限受邀用户加入,请联系管理员获取邀请。"+ "inviteOnly": "此实例仅限受邀用户加入,请联系管理员获取邀请。",+ "oauthClientUnknown": "请求访问的应用未在此处注册。请在该应用中移除此服务器并重新添加,让它重新注册。",+ "oauthRedirectUnknown": "该应用要求返回到一个未注册的地址,因此授权已停止。请在该应用中移除此服务器并重新添加。",+ "oauthClientRefused": "此应用不允许连接到你的账户。"}}diff --git a/apps/web/src/features/auth/hooks/useRedirectError.test.tsx b/apps/web/src/features/auth/hooks/useRedirectError.test.tsxindex d773540a..edbd2583 100644--- a/apps/web/src/features/auth/hooks/useRedirectError.test.tsx+++ b/apps/web/src/features/auth/hooks/useRedirectError.test.tsx@@ -82,4 +82,11 @@ describe('useRedirectError', () => {assert.equal(render('something_else', 'Provider said no'), 'Provider said no');assert.equal(render('something_else'), auth.errors.generic);});++ it('names an MCP authorization for a client the instance does not know', () => {+ assert.equal(render('invalid_client', 'client_id is required'), auth.errors.oauthClientUnknown);+ assert.equal(render('invalid_redirect'), auth.errors.oauthRedirectUnknown);+ assert.equal(render('client_disabled'), auth.errors.oauthClientRefused);+ assert.equal(render('unauthorized_client'), auth.errors.oauthClientRefused);+ });});diff --git a/apps/web/src/features/auth/hooks/useRedirectError.ts b/apps/web/src/features/auth/hooks/useRedirectError.tsindex 22ad210a..7fd567da 100644--- a/apps/web/src/features/auth/hooks/useRedirectError.ts+++ b/apps/web/src/features/auth/hooks/useRedirectError.ts@@ -6,10 +6,12 @@ import { REGISTRATION_REFUSAL_KEYS } from '@/utils/registrationRefusals';// Some auth failures reach the sign-in screen as a redirect rather than a rejected// promise, and carry their reason in ?error=<code> (plus ?error_description=<text>// when the instance itself refused — the registration gate passes its own message-// that way). Four flows land here: the Google round trip, the OIDC one, the magic link,-// and the confirmation link from the address verification email. Codes raised by-// better-auth carry no description, and the gate's is in English, so the ones a visitor-// can act on are spelled out here.+// that way). Five flows land here: the Google round trip, the OIDC one, the magic link,+// the confirmation link from the address verification email, and an MCP authorization+// the api could not hand back to its client. Codes raised by better-auth carry no+// description, or one written for developers (an unknown MCP client arrives as+// "client_id is required"), and the gate's is in English, so the ones a visitor can act+// on are spelled out here.//// Linking a provider account to an account whose email was never confirmed is refused// unless the instance trusts provider addresses: anyone could have registered that@@ -28,6 +30,12 @@ const MESSAGE_KEYS = {INVALID_TOKEN: 'invalidToken',USER_NOT_FOUND: 'userNotFound',...REGISTRATION_REFUSAL_KEYS,+ // The client or its return address is unknown: a client can keep a registration the+ // instance has since lost, as an upgrade that drops the old ones does.+ invalid_client: 'oauthClientUnknown',+ invalid_redirect: 'oauthRedirectUnknown',+ client_disabled: 'oauthClientRefused',+ unauthorized_client: 'oauthClientRefused',} as const;export function useRedirectError() {diff --git a/apps/web/src/proxy.test.ts b/apps/web/src/proxy.test.tsindex c6b8c992..3a3902b0 100644--- a/apps/web/src/proxy.test.ts+++ b/apps/web/src/proxy.test.ts@@ -46,6 +46,11 @@ describe('proxy', () => {assert.equal(res.headers.get('location'), 'http://localhost/');});+ it('leaves a signed-in user on the login page when it carries an error', () => {+ const res = run('/login?error=invalid_client', COOKIE);+ assert.equal(res.headers.get('location'), null);+ });+// Over HTTPS the api names the session cookie with the __Host- prefix.it('treats a __Host- session cookie as a session', () => {const res = run('/login', '__Host-better-auth.session_token=value');diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.tsindex 72d7fa19..c435cbf2 100644--- a/apps/web/src/proxy.ts+++ b/apps/web/src/proxy.ts@@ -74,7 +74,10 @@ function gate(request: NextRequest): NextResponse {// check below and bounces the browser back into the app, where the next 401 starts// the cycle over.if (request.nextUrl.searchParams.get('expired') === '1') return clearSession(request);- if (hasSession) return NextResponse.redirect(new URL('/', request.url));+ // An error the api could not hand back to the page that asked (an MCP client it+ // does not know, a provider callback that failed) has only this screen to say so.+ const showsError = request.nextUrl.searchParams.has('error');+ if (hasSession && !showsError) return NextResponse.redirect(new URL('/', request.url));return NextResponse.next();}diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 3a5e2c81..88668748 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -68,6 +68,10 @@ host to the api: `/.well-known/oauth-authorization-server*`,MCP clients sign in with OAuth only over HTTPS. On an `API_URL` that is plain HTTP and not`localhost`, MCP takes personal API keys only.+An authorization the api cannot hand back to the client, because it does not know the client+or its redirect URI, ends on the web's sign-in page, which says what happened. A client that+keeps a registration the instance no longer has is told to remove the server and add it again.+The OAuth redirect URIs that god mode shows include the path. An api on a differentregistrable domain than the web app (`api.other.com`) does not work: the session cookiecannot be shared across sites.diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.tsindex b6660780..3233610d 100644--- a/packages/auth/src/index.ts+++ b/packages/auth/src/index.ts@@ -207,9 +207,10 @@ export async function verifyMcpAccessToken(token: string): Promise<string | nullreturn claims.sub;}-// The fallback for a callback that fails early is better-auth's own /api/auth/error;-// under a path prefix that route is outside it, and /login turns ?error= into a message.-const oauthErrorURL = apiHasPath ? `${trustedOrigins[0]}/login` : undefined;+// An error better-auth cannot hand back to the page that started the flow lands here.+// Its own /api/auth/error is outside a path prefix and, on the api's own host, sends a+// production browser to the api's root; /login turns ?error= into a message.+const oauthErrorURL = `${trustedOrigins[0]}/login`;// User roles. "god" is the owner of the instance: the very first registered user// gets it automatically; everyone after is a plain "user". The role is assigned@@ -505,7 +506,7 @@ export const API_KEY_MAX_EXPIRES_IN_DAYS = 365;export const auth = betterAuth({baseURL,secret: process.env.BETTER_AUTH_SECRET,- onAPIError: oauthErrorURL ? { errorURL: oauthErrorURL } : undefined,+ onAPIError: { errorURL: oauthErrorURL },database: drizzleAdapter(db, {provider: 'pg',