Skip to content

⭐️⭐️⭐️ 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.

feat: a person can see and disconnect the MCP clients connected to their account (#574)

Pasqual Tronconeae654859b493
diff --git a/apps/api/src/__tests__/helpers/mcp.ts b/apps/api/src/__tests__/helpers/mcp.ts
index 3752a6ab..ffc60e4a 100644
--- a/apps/api/src/__tests__/helpers/mcp.ts
+++ b/apps/api/src/__tests__/helpers/mcp.ts
@@ -18,9 +18,7 @@ const MCP_RESOURCE = `${process.env.API_URL}/mcp`;
const CODE_VERIFIER = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
const CODE_CHALLENGE = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM';
-// The MCP OAuth token a person gets by approving a client: register, authorize with
-// their session, consent, and exchange the code.
-export async function mcpAccessToken(cookie: string): Promise<string> {
+export async function registerMcpClient(name = 'Test client'): Promise<string> {
const registered = await app.handle(
new Request('http://localhost/api/auth/oauth2/register', {
method: 'POST',
@@ -28,11 +26,20 @@ export async function mcpAccessToken(cookie: string): Promise<string> {
body: JSON.stringify({
redirect_uris: [REDIRECT_URI],
token_endpoint_auth_method: 'none',
- client_name: 'Test client',
+ client_name: name,
}),
}),
);
- const clientId = ((await registered.json()) as { client_id: string }).client_id;
+ return ((await registered.json()) as { client_id: string }).client_id;
+}
+
+// Where the authorize endpoint sends the person: the consent page while the client has
+// no consent from them, straight back to the client with a code once it has.
+export async function authorizeMcpClient(
+ cookie: string,
+ clientId: string,
+ scope = 'openid',
+): Promise<URL> {
const authorize = await app.handle(
new Request(
`http://localhost/api/auth/oauth2/authorize?${new URLSearchParams({
@@ -41,15 +48,25 @@ export async function mcpAccessToken(cookie: string): Promise<string> {
redirect_uri: REDIRECT_URI,
code_challenge: CODE_CHALLENGE,
code_challenge_method: 'S256',
- scope: 'openid',
+ scope,
state: 'st',
resource: MCP_RESOURCE,
})}`,
{ headers: { cookie } },
),
);
+ return new URL(authorize.headers.get('location') ?? '');
+}
+
+// The MCP OAuth token a person gets by approving a client: authorize with their session,
+// consent, and exchange the code.
+export async function connectMcpClient(
+ cookie: string,
+ clientId: string,
+ scope = 'openid',
+): Promise<string> {
// The consent page receives the signed authorization request and posts it back.
- const consentPage = new URL(authorize.headers.get('location') ?? '');
+ const consentPage = await authorizeMcpClient(cookie, clientId, scope);
const consent = await app.handle(
new Request('http://localhost/api/auth/oauth2/consent', {
method: 'POST',
@@ -58,18 +75,26 @@ export async function mcpAccessToken(cookie: string): Promise<string> {
}),
);
const { url } = (await consent.json()) as { url: string };
- const token = await app.handle(
+ const token = await exchangeMcpCode(clientId, new URL(url).searchParams.get('code') ?? '');
+ return ((await token.json()) as { access_token: string }).access_token;
+}
+
+export function exchangeMcpCode(clientId: string, code: string): Promise<Response> {
+ return app.handle(
new Request('http://localhost/api/auth/oauth2/token', {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
- code: new URL(url).searchParams.get('code') ?? '',
+ code,
redirect_uri: REDIRECT_URI,
client_id: clientId,
code_verifier: CODE_VERIFIER,
}),
}),
);
- return ((await token.json()) as { access_token: string }).access_token;
+}
+
+export async function mcpAccessToken(cookie: string): Promise<string> {
+ return connectMcpClient(cookie, await registerMcpClient());
}
diff --git a/apps/api/src/modules/connected-apps/__tests__/integration/connected-apps.test.ts b/apps/api/src/modules/connected-apps/__tests__/integration/connected-apps.test.ts
new file mode 100644
index 00000000..a692e0b2
--- /dev/null
+++ b/apps/api/src/modules/connected-apps/__tests__/integration/connected-apps.test.ts
@@ -0,0 +1,177 @@
+import { beforeEach, describe, expect, it } from 'bun:test';
+import { auth } from '@repo/auth';
+import { app } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import {
+ authorizeMcpClient,
+ connectMcpClient,
+ exchangeMcpCode,
+ registerMcpClient,
+ untaggedRoutes,
+} from '#tests/helpers/mcp';
+import { setMcpOAuthToken } from '#shared/mcp-request';
+
+// offline_access gives the client a refresh token, as real MCP clients ask for.
+const connect = (cookie: string, clientId: string) =>
+ connectMcpClient(cookie, clientId, 'openid offline_access');
+
+function mcpCall(bearer: string) {
+ return app.handle(
+ new Request('http://localhost/mcp', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ accept: 'application/json, text/event-stream',
+ authorization: `Bearer ${bearer}`,
+ },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2025-06-18',
+ capabilities: {},
+ clientInfo: { name: 'test', version: '1' },
+ },
+ }),
+ }),
+ );
+}
+
+function call(path: string, init: RequestInit & { cookie: string }) {
+ const { cookie, headers, ...rest } = init;
+ return app.handle(
+ new Request(`http://localhost${path}`, {
+ ...rest,
+ headers: { cookie, ...(headers as Record<string, string>) },
+ }),
+ );
+}
+
+describe('connected applications', () => {
+ beforeEach(resetDb);
+
+ it('lists the applications the person authorized, and only theirs', async () => {
+ const ana = await signUpTestUser({ team: false });
+ const luis = await signUpTestUser({ team: false });
+ const claude = await registerMcpClient('Claude');
+ const chatgpt = await registerMcpClient('ChatGPT');
+ await connect(ana.cookie, claude);
+ await connect(luis.cookie, chatgpt);
+
+ const res = await call('/account/connected-apps', { cookie: ana.cookie });
+
+ expect(res.status).toBe(200);
+ const apps = (await res.json()) as { clientId: string; name: string; scopes: string[] }[];
+ expect(apps).toHaveLength(1);
+ expect(apps[0]).toMatchObject({ clientId: claude, name: 'Claude' });
+ expect(apps[0]!.scopes).toEqual(expect.arrayContaining(['openid', 'offline_access']));
+ });
+
+ it('cuts an application off: its token stops working at once', async () => {
+ const ana = await signUpTestUser({ team: false });
+ const claude = await registerMcpClient('Claude');
+ const token = await connect(ana.cookie, claude);
+ expect((await mcpCall(token)).status).toBe(200);
+
+ const res = await call(`/account/connected-apps/${claude}`, {
+ method: 'DELETE',
+ cookie: ana.cookie,
+ });
+
+ expect(res.status).toBe(204);
+ expect((await mcpCall(token)).status).toBe(401);
+ const left = await call('/account/connected-apps', { cookie: ana.cookie });
+ expect(await left.json()).toEqual([]);
+ });
+
+ it('asks for consent again when the application connects again', async () => {
+ const ana = await signUpTestUser({ team: false });
+ const claude = await registerMcpClient('Claude');
+ await connect(ana.cookie, claude);
+ // With the consent standing, authorize sends the person straight back to the client.
+ expect((await authorizeMcpClient(ana.cookie, claude)).searchParams.has('code')).toBe(true);
+
+ await call(`/account/connected-apps/${claude}`, { method: 'DELETE', cookie: ana.cookie });
+
+ // The registration stays, since other people may use it; the consent does not.
+ const next = await authorizeMcpClient(ana.cookie, claude);
+ expect(next.searchParams.has('code')).toBe(false);
+ expect(next.searchParams.get('client_id')).toBe(claude);
+ });
+
+ it('refuses a code issued before the disconnection', async () => {
+ const ana = await signUpTestUser({ team: false });
+ const claude = await registerMcpClient('Claude');
+ await connect(ana.cookie, claude);
+ // Authorize again while connected: the code comes straight back, still unexchanged.
+ const pending = await authorizeMcpClient(ana.cookie, claude);
+
+ await call(`/account/connected-apps/${claude}`, { method: 'DELETE', cookie: ana.cookie });
+
+ const res = await exchangeMcpCode(claude, pending.searchParams.get('code') ?? '');
+ expect(res.status).toBe(400);
+ expect(await res.json()).toMatchObject({ error: 'invalid_grant' });
+ const left = await call('/account/connected-apps', { cookie: ana.cookie });
+ expect(await left.json()).toEqual([]);
+ });
+
+ it("leaves another person's connection to the same application alone", async () => {
+ const ana = await signUpTestUser({ team: false });
+ const luis = await signUpTestUser({ team: false });
+ const claude = await registerMcpClient('Claude');
+ await connect(ana.cookie, claude);
+ const luisToken = await connect(luis.cookie, claude);
+
+ await call(`/account/connected-apps/${claude}`, { method: 'DELETE', cookie: ana.cookie });
+
+ const res = await call('/account/connected-apps', { cookie: luis.cookie });
+ expect(((await res.json()) as unknown[]).length).toBe(1);
+ expect((await mcpCall(luisToken)).status).toBe(200);
+ });
+
+ it('answers 404 for an application that is not connected', async () => {
+ const ana = await signUpTestUser({ team: false });
+
+ const res = await call('/account/connected-apps/nobody', {
+ method: 'DELETE',
+ cookie: ana.cookie,
+ });
+
+ expect(res.status).toBe(404);
+ expect(await res.json()).toMatchObject({ error: 'Application not connected' });
+ });
+
+ it('refuses an API key', async () => {
+ const ana = await signUpTestUser({ team: false });
+ const key = await auth.api.createApiKey({ body: { userId: ana.userId, name: 'script' } });
+
+ const res = await app.handle(
+ new Request('http://localhost/account/connected-apps', {
+ headers: { 'x-api-key': key.key },
+ }),
+ );
+
+ expect(res.status).toBe(403);
+ });
+
+ it('keeps both routes out of the MCP tools', () => {
+ expect(untaggedRoutes((route) => route.includes('/account/connected-apps'))).toEqual([
+ 'GET /account/connected-apps',
+ 'DELETE /account/connected-apps/:clientId',
+ ]);
+ });
+
+ it('refuses an OAuth token, so a connected agent cannot see or revoke the others', async () => {
+ const ana = await signUpTestUser({ team: false });
+ const token = await connect(ana.cookie, await registerMcpClient('Claude'));
+
+ // How an MCP tool call reaches a route: the token rides on the request object.
+ const request = new Request('http://localhost/account/connected-apps');
+ setMcpOAuthToken(request, token);
+ const res = await app.handle(request);
+
+ expect(res.status).toBe(403);
+ });
+});
diff --git a/apps/api/src/modules/connected-apps/index.ts b/apps/api/src/modules/connected-apps/index.ts
new file mode 100644
index 00000000..4ce3c2f0
--- /dev/null
+++ b/apps/api/src/modules/connected-apps/index.ts
@@ -0,0 +1,61 @@
+import { Elysia, t } from 'elysia';
+import { requireUser } from '#shared/access';
+import { authContext } from '#shared/auth-context';
+import { noContent } from '#shared/http';
+import { HttpError } from '#shared/lib';
+import { getMcpOAuthToken } from '#shared/mcp-request';
+import { errors } from '#shared/responses';
+import { ConnectedApp, ConnectedAppParams } from './model';
+import { listConnectedApps, revokeConnectedApp } from './service';
+
+// Only the person, signed in through the browser, manages what reaches their account:
+// an API key or an OAuth token of an agent must not see the other grants, or lift the
+// revocation of one by revoking the rest.
+function requireBrowserSession(request: Request) {
+ if (
+ request.headers.get('authorization') ||
+ request.headers.get('x-api-key') ||
+ getMcpOAuthToken(request)
+ ) {
+ throw new HttpError(403, 'Connected applications are managed from a browser session');
+ }
+}
+
+// The OAuth applications (MCP clients such as Claude or ChatGPT) the session user let
+// act on their behalf, and the way to cut one off.
+export const connectedAppRoutes = new Elysia({
+ name: 'connected-apps',
+ detail: { tags: ['Settings'] },
+})
+ .use(authContext)
+ .onBeforeHandle(({ request }) => {
+ requireBrowserSession(request);
+ })
+
+ .get('/account/connected-apps', ({ user }) => listConnectedApps(requireUser(user).id), {
+ response: { 200: t.Array(ConnectedApp), ...errors(401, 403) },
+ detail: {
+ summary: 'List connected applications',
+ description:
+ 'List the OAuth applications the current user authorized to act on their behalf.',
+ },
+ })
+
+ .delete(
+ '/account/connected-apps/:clientId',
+ async ({ user, params }) => {
+ if (!(await revokeConnectedApp(requireUser(user).id, params.clientId))) {
+ throw new HttpError(404, 'Application not connected');
+ }
+ return noContent();
+ },
+ {
+ params: ConnectedAppParams,
+ response: { 204: t.Void(), ...errors(401, 403, 404) },
+ detail: {
+ summary: 'Disconnect an application',
+ description:
+ "Revoke an application's access: its tokens stop working at once and the next connection asks for consent again.",
+ },
+ },
+ );
diff --git a/apps/api/src/modules/connected-apps/model.ts b/apps/api/src/modules/connected-apps/model.ts
new file mode 100644
index 00000000..78a5dd53
--- /dev/null
+++ b/apps/api/src/modules/connected-apps/model.ts
@@ -0,0 +1,14 @@
+import { t } from 'elysia';
+
+export const ConnectedApp = t.Object({
+ clientId: t.String(),
+ name: t.String(),
+ icon: t.Union([t.String(), t.Null()]),
+ scopes: t.Array(t.String()),
+ connectedAt: t.String({ format: 'date-time' }),
+ // The last refresh token issued to it: every refresh rotates it, so this is roughly
+ // the last time the application renewed its access.
+ lastUsedAt: t.Union([t.String({ format: 'date-time' }), t.Null()]),
+});
+
+export const ConnectedAppParams = t.Object({ clientId: t.String({ minLength: 1 }) });
diff --git a/apps/api/src/modules/connected-apps/service.ts b/apps/api/src/modules/connected-apps/service.ts
new file mode 100644
index 00000000..17c019ed
--- /dev/null
+++ b/apps/api/src/modules/connected-apps/service.ts
@@ -0,0 +1,117 @@
+import {
+ db,
+ oauthAccessToken,
+ oauthClient,
+ oauthConsent,
+ oauthRefreshToken,
+ verification,
+} from '@repo/db';
+import { and, eq, gt, inArray, isNull, like } from 'drizzle-orm';
+
+export interface ConnectedApp {
+ clientId: string;
+ name: string;
+ icon: string | null;
+ scopes: string[];
+ connectedAt: string;
+ lastUsedAt: string | null;
+}
+
+// An application is connected while the user's consent stands or one of its refresh
+// tokens can still mint access tokens; an expired token alone is history.
+export async function listConnectedApps(userId: string): Promise<ConnectedApp[]> {
+ const [consents, refreshTokens] = await Promise.all([
+ db.select().from(oauthConsent).where(eq(oauthConsent.userId, userId)),
+ db
+ .select()
+ .from(oauthRefreshToken)
+ .where(
+ and(
+ eq(oauthRefreshToken.userId, userId),
+ isNull(oauthRefreshToken.revoked),
+ gt(oauthRefreshToken.expiresAt, new Date()),
+ ),
+ ),
+ ]);
+ const clientIds = [...new Set([...consents, ...refreshTokens].map((row) => row.clientId))];
+ if (clientIds.length === 0) return [];
+ const clients = await db
+ .select()
+ .from(oauthClient)
+ .where(inArray(oauthClient.clientId, clientIds));
+
+ return clients
+ .map((client) => {
+ const consent = consents.find((c) => c.clientId === client.clientId);
+ const issued = refreshTokens
+ .filter((tk) => tk.clientId === client.clientId)
+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
+ const connectedAt = consent?.createdAt ?? issued.at(-1)!.createdAt;
+ return {
+ clientId: client.clientId,
+ name: client.name || client.clientId,
+ icon: client.icon,
+ scopes: consent?.scopes ?? issued[0]!.scopes,
+ connectedAt: connectedAt.toISOString(),
+ lastUsedAt: issued[0]?.createdAt.toISOString() ?? null,
+ };
+ })
+ .sort((a, b) => b.connectedAt.localeCompare(a.connectedAt));
+}
+
+type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];
+
+// better-auth keeps an authorization code in `verification` as JSON until it is exchanged,
+// and the exchange checks neither the consent nor the tokens, so a code issued just before
+// the disconnection would connect the client again. Only a code carries that marker; the
+// exact match below rejects anything else the prefilter lets through.
+async function deletePendingCodes(tx: Transaction, userId: string, clientId: string) {
+ const candidates = await tx
+ .select({ id: verification.id, value: verification.value })
+ .from(verification)
+ .where(
+ and(
+ like(verification.value, '%"authorization_code"%'),
+ like(verification.value, `%${userId}%`),
+ ),
+ );
+ const ids = candidates
+ .filter((row) => {
+ try {
+ const code = JSON.parse(row.value) as {
+ type?: string;
+ userId?: string;
+ query?: { client_id?: string };
+ };
+ return (
+ code.type === 'authorization_code' &&
+ code.userId === userId &&
+ code.query?.client_id === clientId
+ );
+ } catch {
+ return false;
+ }
+ })
+ .map((row) => row.id);
+ if (ids.length > 0) await tx.delete(verification).where(inArray(verification.id, ids));
+}
+
+// Drops the consent with the tokens: a client left with the consent would get new
+// tokens on its next authorize. The client registration stays; it is not the user's.
+export async function revokeConnectedApp(userId: string, clientId: string): Promise<boolean> {
+ return db.transaction(async (tx) => {
+ await deletePendingCodes(tx, userId, clientId);
+ await tx
+ .delete(oauthAccessToken)
+ .where(and(eq(oauthAccessToken.userId, userId), eq(oauthAccessToken.clientId, clientId)));
+ const tokens = await tx
+ .delete(oauthRefreshToken)
+ .where(and(eq(oauthRefreshToken.userId, userId), eq(oauthRefreshToken.clientId, clientId)))
+ .returning({ id: oauthRefreshToken.id });
+ const consents = await tx
+ .delete(oauthConsent)
+ .where(and(eq(oauthConsent.userId, userId), eq(oauthConsent.clientId, clientId)))
+ .returning({ id: oauthConsent.id });
+ return tokens.length + consents.length > 0;
+ });
+}
diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.ts
index 32bea3ec..8203823d 100644
--- a/apps/api/src/planner.ts
+++ b/apps/api/src/planner.ts
@@ -44,6 +44,7 @@ import { notificationRoutes } from './modules/notifications';
import { notificationSettingsRoutes } from './modules/notification-settings';
import { notificationPreferenceRoutes } from './modules/notification-preferences';
import { userPreferenceRoutes } from './modules/user-preferences';
+import { connectedAppRoutes } from './modules/connected-apps';
import { telegramRoutes } from './modules/telegram';
import { syncRoutes } from './modules/sync';
import { linkPreviewRoutes } from './modules/link-previews';
@@ -128,6 +129,7 @@ export const planner = new Elysia({ name: 'planner' })
.use(notificationSettingsRoutes)
.use(notificationPreferenceRoutes)
.use(userPreferenceRoutes)
+ .use(connectedAppRoutes)
.use(telegramRoutes)
.use(syncRoutes)
.use(linkPreviewRoutes)
diff --git a/apps/web/messages/ar/account.json b/apps/web/messages/ar/account.json
index 2fe3fa5f..f8701fd6 100644
--- a/apps/web/messages/ar/account.json
+++ b/apps/web/messages/ar/account.json
@@ -50,7 +50,16 @@
"thisDevice": "هذا الجهاز",
"deleteWarning": "مش هتقدر تسجّل دخول بمفتاح المرور ده تاني، وده مش هينفع ترجع فيه.",
"passkeyFallback": "مفتاح مرور",
- "passkeysLoadFailed": "تعذّر تحميل مفاتيح المرور."
+ "passkeysLoadFailed": "تعذّر تحميل مفاتيح المرور.",
+ "connectedAppsTitle": "التطبيقات المتصلة",
+ "connectedAppsDescription": "تطبيقات مثل Claude أو ChatGPT سمحت لها بالتصرف نيابةً عنك عبر MCP. ترى وتفعل ما يمكنك فعله.",
+ "connectedAppsEmpty": "لا يوجد أي تطبيق متصل بحسابك.",
+ "connectedAppUsed": "متصل منذ {connected} · آخر استخدام {used}",
+ "connectedAppSince": "متصل منذ {connected}",
+ "disconnectApp": "قطع الاتصال",
+ "disconnectAppTitle": "قطع اتصال {name}؟",
+ "disconnectAppWarning": "سيفقد الوصول فورًا. وعند توصيله مجددًا ستُطلب موافقتك مرة أخرى.",
+ "disconnectAppFailed": "تعذّر قطع اتصال التطبيق."
},
"accounts": {
"label": "الحسابات",
diff --git a/apps/web/messages/en/account.json b/apps/web/messages/en/account.json
index 46031556..49736386 100644
--- a/apps/web/messages/en/account.json
+++ b/apps/web/messages/en/account.json
@@ -50,7 +50,16 @@
"thisDevice": "This device",
"deleteWarning": "You will no longer be able to sign in with this passkey. This cannot be undone.",
"passkeyFallback": "Passkey",
- "passkeysLoadFailed": "Could not load passkeys."
+ "passkeysLoadFailed": "Could not load passkeys.",
+ "connectedAppsTitle": "Connected applications",
+ "connectedAppsDescription": "Applications such as Claude or ChatGPT that you allowed to act on your behalf through MCP. They see and do what you can.",
+ "connectedAppsEmpty": "No application is connected to your account.",
+ "connectedAppUsed": "Connected {connected} · last used {used}",
+ "connectedAppSince": "Connected {connected}",
+ "disconnectApp": "Disconnect",
+ "disconnectAppTitle": "Disconnect {name}?",
+ "disconnectAppWarning": "It loses access at once. Connecting it again will ask for your consent again.",
+ "disconnectAppFailed": "Could not disconnect the application."
},
"accounts": {
"label": "Accounts",
diff --git a/apps/web/messages/es-ES/account.json b/apps/web/messages/es-ES/account.json
index ebf37ca3..273f44ab 100644
--- a/apps/web/messages/es-ES/account.json
+++ b/apps/web/messages/es-ES/account.json
@@ -50,7 +50,16 @@
"thisDevice": "Este dispositivo",
"deleteWarning": "Ya no podrás iniciar sesión con este passkey. No se puede deshacer.",
"passkeyFallback": "Passkey",
- "passkeysLoadFailed": "No se han podido cargar los passkeys."
+ "passkeysLoadFailed": "No se han podido cargar los passkeys.",
+ "connectedAppsTitle": "Aplicaciones conectadas",
+ "connectedAppsDescription": "Aplicaciones como Claude o ChatGPT a las que permitiste actuar en tu nombre mediante MCP. Ven y hacen lo mismo que tú.",
+ "connectedAppsEmpty": "No hay ninguna aplicación conectada a tu cuenta.",
+ "connectedAppUsed": "Conectada el {connected} · último uso el {used}",
+ "connectedAppSince": "Conectada el {connected}",
+ "disconnectApp": "Desconectar",
+ "disconnectAppTitle": "¿Desconectar {name}?",
+ "disconnectAppWarning": "Pierde el acceso al momento. Si vuelves a conectarla, se te pedirá de nuevo tu consentimiento.",
+ "disconnectAppFailed": "No se pudo desconectar la aplicación."
},
"accounts": {
"label": "Cuentas",
diff --git a/apps/web/messages/fr/account.json b/apps/web/messages/fr/account.json
index d4ee442e..ce0f29e1 100644
--- a/apps/web/messages/fr/account.json
+++ b/apps/web/messages/fr/account.json
@@ -50,7 +50,16 @@
"thisDevice": "Cet appareil",
"deleteWarning": "Vous ne pourrez plus vous connecter avec cette clé d'accès. Cette action est irréversible.",
"passkeyFallback": "Clé d'accès",
- "passkeysLoadFailed": "Impossible de charger les clés d'accès."
+ "passkeysLoadFailed": "Impossible de charger les clés d'accès.",
+ "connectedAppsTitle": "Applications connectées",
+ "connectedAppsDescription": "Des applications comme Claude ou ChatGPT que vous avez autorisées à agir en votre nom via MCP. Elles voient et font ce que vous pouvez faire.",
+ "connectedAppsEmpty": "Aucune application n’est connectée à votre compte.",
+ "connectedAppUsed": "Connectée le {connected} · dernière utilisation le {used}",
+ "connectedAppSince": "Connectée le {connected}",
+ "disconnectApp": "Déconnecter",
+ "disconnectAppTitle": "Déconnecter {name} ?",
+ "disconnectAppWarning": "Elle perd l’accès immédiatement. La reconnecter demandera à nouveau votre consentement.",
+ "disconnectAppFailed": "Impossible de déconnecter l’application."
},
"accounts": {
"label": "Comptes",
diff --git a/apps/web/messages/id/account.json b/apps/web/messages/id/account.json
index b9f42347..9f960cae 100644
--- a/apps/web/messages/id/account.json
+++ b/apps/web/messages/id/account.json
@@ -50,7 +50,16 @@
"thisDevice": "Perangkat ini",
"deleteWarning": "Anda tidak akan dapat masuk lagi dengan passkey ini. Tindakan ini tidak dapat dibatalkan.",
"passkeyFallback": "Passkey",
- "passkeysLoadFailed": "Gagal memuat passkey."
+ "passkeysLoadFailed": "Gagal memuat passkey.",
+ "connectedAppsTitle": "Aplikasi terhubung",
+ "connectedAppsDescription": "Aplikasi seperti Claude atau ChatGPT yang Anda izinkan bertindak atas nama Anda melalui MCP. Aplikasi ini melihat dan melakukan apa yang bisa Anda lakukan.",
+ "connectedAppsEmpty": "Tidak ada aplikasi yang terhubung ke akun Anda.",
+ "connectedAppUsed": "Terhubung {connected} · terakhir digunakan {used}",
+ "connectedAppSince": "Terhubung {connected}",
+ "disconnectApp": "Putuskan",
+ "disconnectAppTitle": "Putuskan {name}?",
+ "disconnectAppWarning": "Aksesnya langsung dicabut. Menghubungkannya lagi akan meminta persetujuan Anda kembali.",
+ "disconnectAppFailed": "Tidak dapat memutuskan aplikasi."
},
"accounts": {
"label": "Akun",
diff --git a/apps/web/messages/ko/account.json b/apps/web/messages/ko/account.json
index 771c7d92..e115a08d 100644
--- a/apps/web/messages/ko/account.json
+++ b/apps/web/messages/ko/account.json
@@ -50,7 +50,16 @@
"thisDevice": "이 기기",
"deleteWarning": "이 패스키로 더 이상 로그인할 수 없게 됩니다. 이 작업은 되돌릴 수 없습니다.",
"passkeyFallback": "패스키",
- "passkeysLoadFailed": "패스키를 불러올 수 없습니다."
+ "passkeysLoadFailed": "패스키를 불러올 수 없습니다.",
+ "connectedAppsTitle": "연결된 애플리케이션",
+ "connectedAppsDescription": "MCP를 통해 나를 대신하여 작업하도록 허용한 Claude 또는 ChatGPT 같은 애플리케이션입니다. 내가 볼 수 있고 할 수 있는 것을 똑같이 할 수 있습니다.",
+ "connectedAppsEmpty": "계정에 연결된 애플리케이션이 없습니다.",
+ "connectedAppUsed": "{connected}에 연결 · 마지막 사용 {used}",
+ "connectedAppSince": "{connected}에 연결",
+ "disconnectApp": "연결 해제",
+ "disconnectAppTitle": "{name} 연결을 해제하시겠습니까?",
+ "disconnectAppWarning": "즉시 접근 권한을 잃습니다. 다시 연결하면 동의를 다시 요청합니다.",
+ "disconnectAppFailed": "애플리케이션 연결을 해제할 수 없습니다."
},
"accounts": {
"label": "계정",
diff --git a/apps/web/messages/pt-BR/account.json b/apps/web/messages/pt-BR/account.json
index 919e21d2..9e13d436 100644
--- a/apps/web/messages/pt-BR/account.json
+++ b/apps/web/messages/pt-BR/account.json
@@ -50,7 +50,16 @@
"thisDevice": "Este dispositivo",
"deleteWarning": "Você não poderá mais entrar com esta chave de acesso. Isso não pode ser desfeito.",
"passkeyFallback": "Chave de acesso",
- "passkeysLoadFailed": "Não foi possível carregar as chaves de acesso."
+ "passkeysLoadFailed": "Não foi possível carregar as chaves de acesso.",
+ "connectedAppsTitle": "Aplicativos conectados",
+ "connectedAppsDescription": "Aplicativos como Claude ou ChatGPT que você autorizou a agir em seu nome via MCP. Eles veem e fazem o que você pode.",
+ "connectedAppsEmpty": "Nenhum aplicativo está conectado à sua conta.",
+ "connectedAppUsed": "Conectado em {connected} · último uso em {used}",
+ "connectedAppSince": "Conectado em {connected}",
+ "disconnectApp": "Desconectar",
+ "disconnectAppTitle": "Desconectar {name}?",
+ "disconnectAppWarning": "Ele perde o acesso imediatamente. Conectá-lo de novo pedirá seu consentimento outra vez.",
+ "disconnectAppFailed": "Não foi possível desconectar o aplicativo."
},
"accounts": {
"label": "Contas",
diff --git a/apps/web/messages/ru/account.json b/apps/web/messages/ru/account.json
index 8a353e67..5235eaed 100644
--- a/apps/web/messages/ru/account.json
+++ b/apps/web/messages/ru/account.json
@@ -50,7 +50,16 @@
"thisDevice": "Это устройство",
"deleteWarning": "Вы больше не сможете входить по этому passkey. Это действие нельзя отменить.",
"passkeyFallback": "Passkey",
- "passkeysLoadFailed": "Не удалось загрузить passkey."
+ "passkeysLoadFailed": "Не удалось загрузить passkey.",
+ "connectedAppsTitle": "Подключённые приложения",
+ "connectedAppsDescription": "Приложения вроде Claude или ChatGPT, которым вы разрешили действовать от вашего имени через MCP. Они видят и делают то же, что и вы.",
+ "connectedAppsEmpty": "К вашему аккаунту не подключено ни одного приложения.",
+ "connectedAppUsed": "Подключено {connected} · последнее использование {used}",
+ "connectedAppSince": "Подключено {connected}",
+ "disconnectApp": "Отключить",
+ "disconnectAppTitle": "Отключить {name}?",
+ "disconnectAppWarning": "Приложение сразу потеряет доступ. При повторном подключении ваше согласие будет запрошено снова.",
+ "disconnectAppFailed": "Не удалось отключить приложение."
},
"accounts": {
"label": "Аккаунты",
diff --git a/apps/web/messages/uk/account.json b/apps/web/messages/uk/account.json
index 7fd642fa..910dea72 100644
--- a/apps/web/messages/uk/account.json
+++ b/apps/web/messages/uk/account.json
@@ -50,7 +50,16 @@
"thisDevice": "Цей пристрій",
"deleteWarning": "Ви більше не зможете входити за цим passkey. Цю дію не можна скасувати.",
"passkeyFallback": "Passkey",
- "passkeysLoadFailed": "Не вдалося завантажити passkey."
+ "passkeysLoadFailed": "Не вдалося завантажити passkey.",
+ "connectedAppsTitle": "Під’єднані застосунки",
+ "connectedAppsDescription": "Застосунки на кшталт Claude чи ChatGPT, яким ви дозволили діяти від вашого імені через MCP. Вони бачать і роблять те саме, що й ви.",
+ "connectedAppsEmpty": "До вашого облікового запису не під’єднано жодного застосунку.",
+ "connectedAppUsed": "Під’єднано {connected} · востаннє використано {used}",
+ "connectedAppSince": "Під’єднано {connected}",
+ "disconnectApp": "Від’єднати",
+ "disconnectAppTitle": "Від’єднати {name}?",
+ "disconnectAppWarning": "Застосунок одразу втратить доступ. Під час повторного під’єднання вашу згоду буде запитано знову.",
+ "disconnectAppFailed": "Не вдалося від’єднати застосунок."
},
"accounts": {
"label": "Акаунти",
diff --git a/apps/web/messages/zh-CN/account.json b/apps/web/messages/zh-CN/account.json
index 0f6b2360..8d382e1e 100644
--- a/apps/web/messages/zh-CN/account.json
+++ b/apps/web/messages/zh-CN/account.json
@@ -50,7 +50,16 @@
"thisDevice": "此设备",
"deleteWarning": "移除后将无法再使用此通行密钥登录。此操作无法撤销。",
"passkeyFallback": "通行密钥",
- "passkeysLoadFailed": "无法加载通行密钥。"
+ "passkeysLoadFailed": "无法加载通行密钥。",
+ "connectedAppsTitle": "已连接的应用",
+ "connectedAppsDescription": "你允许通过 MCP 代表你操作的应用,例如 Claude 或 ChatGPT。它们能看到和执行你能看到和执行的内容。",
+ "connectedAppsEmpty": "你的账户尚未连接任何应用。",
+ "connectedAppUsed": "连接于 {connected} · 最近使用于 {used}",
+ "connectedAppSince": "连接于 {connected}",
+ "disconnectApp": "断开连接",
+ "disconnectAppTitle": "断开 {name}?",
+ "disconnectAppWarning": "它将立即失去访问权限。再次连接时会重新征求你的同意。",
+ "disconnectAppFailed": "无法断开该应用。"
},
"accounts": {
"label": "关联账户",
diff --git a/apps/web/src/features/account/AccountSecurityPage.tsx b/apps/web/src/features/account/AccountSecurityPage.tsx
index 7ff3b073..d8f9f8ad 100644
--- a/apps/web/src/features/account/AccountSecurityPage.tsx
+++ b/apps/web/src/features/account/AccountSecurityPage.tsx
@@ -6,15 +6,20 @@ import { useQueryClient } from '@tanstack/react-query';
import { useSession } from '@/lib/auth-client';
import { qk } from '@/services/queryKeys';
import FullPageView from '@/components/common/page/FullPageView';
+import type { ConnectedApp } from '@/lib/api/endpoints/connectedApps';
import { hasPasswordCredential, useLinkedAccountsQuery } from './services/accounts.service';
import { usePasskeysQuery, type PasskeyRow } from './services/passkeys.service';
+import { useConnectedAppsQuery } from './services/connectedApps.service';
import AccountSection from './components/AccountSection';
import AccountSecurityPasswordForm from './components/security/AccountSecurityPasswordForm';
import AccountSecurityAddPasskey from './components/security/AccountSecurityAddPasskey';
import AccountSecurityPasskeyList from './components/security/AccountSecurityPasskeyList';
import AccountSecurityDeletePasskeyDialog from './components/security/AccountSecurityDeletePasskeyDialog';
+import AccountSecurityConnectedApps from './components/security/AccountSecurityConnectedApps';
+import AccountSecurityDisconnectAppDialog from './components/security/AccountSecurityDisconnectAppDialog';
-// How the account is signed in to: the password and the passkeys registered for it.
+// How the account is signed in to: the password and the passkeys registered for it,
+// and the applications it let in through OAuth (MCP clients).
// Owns the passkey list query and the delete target; the child components refresh
// the list through the callbacks after a change.
export default function AccountSecurityPage() {
@@ -22,6 +27,7 @@ export default function AccountSecurityPage() {
const { data: session } = useSession();
const queryClient = useQueryClient();
const [deleting, setDeleting] = useState<PasskeyRow | null>(null);
+ const [disconnecting, setDisconnecting] = useState<ConnectedApp | null>(null);
const { data: linkedAccounts } = useLinkedAccountsQuery();
// An account created through single sign-on has no password to change; while the
// list loads the form stays, as it does when the list cannot be read.
@@ -29,6 +35,7 @@ export default function AccountSecurityPage() {
const { data: passkeys, isPending } = usePasskeysQuery();
const invalidate = () => queryClient.invalidateQueries({ queryKey: qk.passkeys });
+ const { data: connectedApps, isPending: connectedAppsPending } = useConnectedAppsQuery();
return (
<FullPageView
@@ -54,6 +61,25 @@ export default function AccountSecurityPage() {
/>
</AccountSection>
+ <AccountSection title={t('connectedAppsTitle')} description={t('connectedAppsDescription')}>
+ <AccountSecurityConnectedApps
+ apps={connectedApps ?? []}
+ isPending={connectedAppsPending}
+ onDisconnect={setDisconnecting}
+ />
+ </AccountSection>
+
+ {disconnecting && (
+ <AccountSecurityDisconnectAppDialog
+ app={disconnecting}
+ onClose={() => setDisconnecting(null)}
+ onDisconnected={async () => {
+ setDisconnecting(null);
+ await queryClient.invalidateQueries({ queryKey: qk.connectedApps });
+ }}
+ />
+ )}
+
{deleting && (
<AccountSecurityDeletePasskeyDialog
passkey={deleting}
diff --git a/apps/web/src/features/account/components/security/AccountSecurityConnectedApps.test.tsx b/apps/web/src/features/account/components/security/AccountSecurityConnectedApps.test.tsx
new file mode 100644
index 00000000..a387bb96
--- /dev/null
+++ b/apps/web/src/features/account/components/security/AccountSecurityConnectedApps.test.tsx
@@ -0,0 +1,103 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import account from '../../../../../messages/en/account.json';
+import type { ConnectedApp } from '@/lib/api/endpoints/connectedApps';
+
+// The list a person reviews before cutting an MCP client off: who is connected, since
+// when and when it last used the account, and the button that starts the revocation.
+const replacedGlobals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'Node',
+ 'Element',
+ 'HTMLElement',
+ 'SVGElement',
+ 'Event',
+ 'MutationObserver',
+ 'getComputedStyle',
+ 'IS_REACT_ACT_ENVIRONMENT',
+] as const;
+
+let dom: JSDOM;
+let root: Root;
+let originals: Map<string, PropertyDescriptor | undefined>;
+
+const claude: ConnectedApp = {
+ clientId: 'claude',
+ name: 'Claude',
+ icon: null,
+ scopes: ['openid', 'offline_access'],
+ connectedAt: '2026-09-01T10:00:00.000Z',
+ lastUsedAt: '2026-10-03T10:00:00.000Z',
+};
+
+beforeEach(async () => {
+ originals = new Map(
+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'https://example.test/' });
+ for (const name of replacedGlobals) {
+ if (name in dom.window) {
+ Object.defineProperty(globalThis, name, {
+ configurable: true,
+ value: dom.window[name as keyof typeof dom.window],
+ });
+ }
+ }
+ Object.defineProperties(globalThis, {
+ getComputedStyle: { configurable: true, value: dom.window.getComputedStyle.bind(dom.window) },
+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },
+ });
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.querySelector('#root')!);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ dom.window.close();
+ for (const [name, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+async function render(apps: ConnectedApp[], onDisconnect: (app: ConnectedApp) => void = () => {}) {
+ const { default: AccountSecurityConnectedApps } = await import('./AccountSecurityConnectedApps');
+ await act(async () =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={{ account }} timeZone="UTC">
+ <AccountSecurityConnectedApps apps={apps} isPending={false} onDisconnect={onDisconnect} />
+ </NextIntlClientProvider>,
+ ),
+ );
+}
+
+describe('AccountSecurityConnectedApps', () => {
+ it('says so when no application is connected', async () => {
+ await render([]);
+ assert.ok(document.body.textContent?.includes('No application is connected'));
+ });
+
+ it('names each application with when it was connected and last used', async () => {
+ await render([claude]);
+ const text = document.body.textContent ?? '';
+ assert.ok(text.includes('Claude'));
+ assert.ok(text.includes('last used'));
+ });
+
+ it('hands the chosen application to the disconnect flow', async () => {
+ const chosen: ConnectedApp[] = [];
+ await render([claude], (app) => chosen.push(app));
+
+ const button = document.querySelector<HTMLButtonElement>('button[title="Disconnect"]');
+ assert.ok(button);
+ await act(async () => button!.click());
+
+ assert.deepEqual(chosen, [claude]);
+ });
+});
diff --git a/apps/web/src/features/account/components/security/AccountSecurityConnectedApps.tsx b/apps/web/src/features/account/components/security/AccountSecurityConnectedApps.tsx
new file mode 100644
index 00000000..68c18470
--- /dev/null
+++ b/apps/web/src/features/account/components/security/AccountSecurityConnectedApps.tsx
@@ -0,0 +1,78 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { Plug, Unplug } from 'lucide-react';
+import { formatDate } from '@/utils/dates';
+import { Button } from '@/components/ui/button';
+import {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemGroup,
+ ItemMedia,
+ ItemTitle,
+} from '@/components/ui/item';
+import { Skeleton } from '@/components/ui/skeleton';
+import type { ConnectedApp } from '@/lib/api/endpoints/connectedApps';
+
+export default function AccountSecurityConnectedApps({
+ apps,
+ isPending,
+ onDisconnect,
+}: {
+ apps: ConnectedApp[];
+ isPending: boolean;
+ onDisconnect: (app: ConnectedApp) => void;
+}) {
+ const t = useTranslations('account.security');
+ if (isPending) {
+ return (
+ <div className="space-y-2 py-3">
+ <Skeleton className="h-10 w-full" />
+ </div>
+ );
+ }
+
+ if (apps.length === 0) {
+ return <p className="py-6 text-sm text-muted-foreground">{t('connectedAppsEmpty')}</p>;
+ }
+
+ return (
+ <ItemGroup>
+ {apps.map((app) => (
+ <Item
+ key={app.clientId}
+ size="sm"
+ className="rounded-none border-0 border-b border-border px-1 last:border-b-0 hover:bg-accent/50"
+ >
+ <ItemMedia>
+ <Plug className="size-4" />
+ </ItemMedia>
+ <ItemContent>
+ <ItemTitle>{app.name}</ItemTitle>
+ <ItemDescription>
+ {app.lastUsedAt
+ ? t('connectedAppUsed', {
+ connected: formatDate(app.connectedAt),
+ used: formatDate(app.lastUsedAt),
+ })
+ : t('connectedAppSince', { connected: formatDate(app.connectedAt) })}
+ </ItemDescription>
+ </ItemContent>
+ <ItemActions>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7 text-muted-foreground hover:text-destructive"
+ title={t('disconnectApp')}
+ onClick={() => onDisconnect(app)}
+ >
+ <Unplug className="size-4" />
+ </Button>
+ </ItemActions>
+ </Item>
+ ))}
+ </ItemGroup>
+ );
+}
diff --git a/apps/web/src/features/account/components/security/AccountSecurityDisconnectAppDialog.tsx b/apps/web/src/features/account/components/security/AccountSecurityDisconnectAppDialog.tsx
new file mode 100644
index 00000000..933300eb
--- /dev/null
+++ b/apps/web/src/features/account/components/security/AccountSecurityDisconnectAppDialog.tsx
@@ -0,0 +1,38 @@
+'use client';
+
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import ConfirmDialog from '@/components/common/overlay/ConfirmDialog';
+import { disconnectApp, type ConnectedApp } from '@/lib/api/endpoints/connectedApps';
+
+export default function AccountSecurityDisconnectAppDialog({
+ app,
+ onClose,
+ onDisconnected,
+}: {
+ app: ConnectedApp;
+ onClose: () => void;
+ onDisconnected: () => void | Promise<void>;
+}) {
+ const t = useTranslations('account.security');
+ return (
+ <ConfirmDialog
+ title={t('disconnectAppTitle', { name: app.name })}
+ confirmLabel={t('disconnectApp')}
+ onClose={onClose}
+ onConfirm={async () => {
+ // A plain request, not a React Query mutation, so the global error toast does
+ // not cover it; throwing keeps the dialog open.
+ try {
+ await disconnectApp(app.clientId);
+ } catch (error) {
+ toast.error(t('disconnectAppFailed'));
+ throw error;
+ }
+ await onDisconnected();
+ }}
+ >
+ <p className="text-sm text-muted-foreground">{t('disconnectAppWarning')}</p>
+ </ConfirmDialog>
+ );
+}
diff --git a/apps/web/src/features/account/services/connectedApps.service.ts b/apps/web/src/features/account/services/connectedApps.service.ts
new file mode 100644
index 00000000..96dc7b94
--- /dev/null
+++ b/apps/web/src/features/account/services/connectedApps.service.ts
@@ -0,0 +1,9 @@
+'use client';
+
+import { useQuery } from '@tanstack/react-query';
+import { getConnectedApps } from '@/lib/api/endpoints/connectedApps';
+import { qk } from '@/services/queryKeys';
+
+export function useConnectedAppsQuery() {
+ return useQuery({ queryKey: qk.connectedApps, queryFn: getConnectedApps });
+}
diff --git a/apps/web/src/lib/api/endpoints/connectedApps.ts b/apps/web/src/lib/api/endpoints/connectedApps.ts
new file mode 100644
index 00000000..b0798373
--- /dev/null
+++ b/apps/web/src/lib/api/endpoints/connectedApps.ts
@@ -0,0 +1,19 @@
+import { request } from '@/lib/api/core/client';
+
+// An OAuth application (an MCP client such as Claude or ChatGPT) the signed-in user
+// let act on their behalf. lastUsedAt is when it was last issued a token, which every
+// refresh does; null once only the consent is left.
+export interface ConnectedApp {
+ clientId: string;
+ name: string;
+ icon: string | null;
+ scopes: string[];
+ connectedAt: string;
+ lastUsedAt: string | null;
+}
+
+export const getConnectedApps = () => request<ConnectedApp[]>('/account/connected-apps');
+
+// Its tokens stop working at once, and connecting it again asks for consent again.
+export const disconnectApp = (clientId: string) =>
+ request<void>(`/account/connected-apps/${encodeURIComponent(clientId)}`, { method: 'DELETE' });
diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.ts
index 42b6fb63..94afe7d1 100644
--- a/apps/web/src/services/queryKeys.ts
+++ b/apps/web/src/services/queryKeys.ts
@@ -277,6 +277,8 @@ export const qk = {
notificationsUnreadTotal: ['notificationsUnreadTotal'] as const,
// The signed-in user's WebAuthn passkeys (account security page).
passkeys: ['passkeys'] as const,
+ // The OAuth applications the signed-in user authorized (account security page).
+ connectedApps: ['connectedApps'] as const,
// The signed-in user's connected external accounts (accounts page): the linked
// Telegram account, and the auth providers better-auth reports.
telegramAccount: ['telegramAccount'] as const,
diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.md
index ded116b2..8b7a1764 100644
--- a/packages/auth/AGENTS.md
+++ b/packages/auth/AGENTS.md
@@ -271,7 +271,10 @@ links in auth emails do.
`verifyMcpAccessToken` checks a token against the instance's own keys in-process, then
reads what a JWT cannot carry: the account must not be deactivated, and a token issued in
a session ends with that session, as better-auth's introspection has it. That is what
-makes deactivation, which deletes the sessions, end every MCP token at once.
+makes deactivation, which deletes the sessions, end every MCP token at once. The token's
+client must also still be connected to the account, through the person's consent or a
+refresh token that has not expired: disconnecting it on the account's Security page
+(`DELETE /account/connected-apps/:clientId`, which deletes both) ends its tokens at once.
better-auth accepts a plain-HTTP MCP resource only on a loopback host, so any other
instance without HTTPS leaves `mcp()` and `jwt()` out and serves MCP to personal API keys
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index 6bf0a1ca..94aa00d8 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -1,6 +1,6 @@
import { randomInt } from 'node:crypto';
import { createWorkspace, db, instanceWorkspaceId } from '@repo/db';
-import { and, eq, gt, sql, type SQL } from 'drizzle-orm';
+import { and, eq, gt, isNull, sql, type SQL } from 'drizzle-orm';
import { betterAuth, type BetterAuthPlugin } from 'better-auth';
import { createAuthMiddleware, APIError } from 'better-auth/api';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
@@ -185,7 +185,7 @@ export function mcpUnauthorized(): Response {
// which this check does not take.
export async function verifyMcpAccessToken(token: string): Promise<string | null> {
if (!mcpOAuth) return null;
- let claims: { sub?: string; sid?: unknown; cnf?: unknown };
+ let claims: { sub?: string; sid?: unknown; cnf?: unknown; client_id?: unknown };
try {
({ payload: claims } = await jwtVerify(token, createLocalJWKSet(await auth.api.getJwks()), {
issuer: MCP_ISSUER,
@@ -200,6 +200,9 @@ export async function verifyMcpAccessToken(token: string): Promise<string | null
.from(schema.user)
.where(eq(schema.user.id, claims.sub));
if (!account || isAccountDeactivated(account)) return null;
+ // Disconnecting the application on the account's Security page ends its tokens at once.
+ if (typeof claims.client_id !== 'string') return null;
+ if (!(await isClientConnected(claims.sub, claims.client_id))) return null;
if (typeof claims.sid === 'string') {
const [open] = await db
.select({ n: sql`1` })
@@ -210,6 +213,30 @@ export async function verifyMcpAccessToken(token: string): Promise<string | null
return claims.sub;
}
+// Connected while the person's consent stands or a refresh token can still mint tokens,
+// the same rule the Security page lists applications by.
+async function isClientConnected(userId: string, clientId: string): Promise<boolean> {
+ const [consent] = await db
+ .select({ n: sql`1` })
+ .from(schema.oauthConsent)
+ .where(and(eq(schema.oauthConsent.userId, userId), eq(schema.oauthConsent.clientId, clientId)))
+ .limit(1);
+ if (consent) return true;
+ const [refresh] = await db
+ .select({ n: sql`1` })
+ .from(schema.oauthRefreshToken)
+ .where(
+ and(
+ eq(schema.oauthRefreshToken.userId, userId),
+ eq(schema.oauthRefreshToken.clientId, clientId),
+ isNull(schema.oauthRefreshToken.revoked),
+ gt(schema.oauthRefreshToken.expiresAt, new Date()),
+ ),
+ )
+ .limit(1);
+ return Boolean(refresh);
+}
+
// 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.