Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions mcp/__tests__/mcp.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,24 @@ describe('MCP endpoint with OAuth login', () => {
expect(login.headers['x-frame-options']).toBe('DENY');
});

it('a personal key works as a bearer token until disconnect', async () => {
const provider = app.get(McpOAuthProvider);
expect(await provider.issueApiKey(9)).toBeNull();
const apiKey = await provider.issueApiKey(42);
const whoami = () =>
request(server())
.post('/mcp')
.set('Authorization', `Bearer ${apiKey}`)
.set('Accept', ACCEPT)
.send({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'whoami', arguments: {} } });
const call = await whoami();
expect(call.status).toBe(200);
expect(JSON.parse(call.body.result.content[0].text).userId).toBe(42);

await provider.disconnectAll(42);
expect((await whoami()).status).toBe(401);
});

it('refuses GET', async () => {
expect((await request(server()).get('/mcp')).status).toBe(405);
});
Expand Down
12 changes: 11 additions & 1 deletion mcp/oauth/mcp-oauth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Body, Controller, Post, Request, Res, UseGuards } from '@nestjs/common';
import { Body, Controller, ForbiddenException, Post, Request, Res, UseGuards } from '@nestjs/common';
import { Request as ExpressRequest, Response } from 'express';
import { JwtAuthGuard } from '@shared/auth/jwt-auth.guard';
import { AuthenticatedRequest } from '@shared/auth/auth.types';
Expand Down Expand Up @@ -60,6 +60,16 @@ export class McpOAuthController {
res.redirect(302, this.provider.issueCodeRedirect(request, user.id));
}

/** "Personal key" in the app settings, for AI apps whose OAuth login doesn't work. Not for admins or impersonation. */
@UseGuards(JwtAuthGuard)
@Post('api-key')
async apiKey(@Request() req: AuthenticatedRequest) {
const userId = req.user?.impersonated ? undefined : getUserIdFromUser(req.user, true);
const apiKey = userId ? await this.provider.issueApiKey(userId) : null;
if (!apiKey) throw new ForbiddenException();
return { apiKey };
}

/** "Disconnect" in the app settings: signs every connected AI client out. */
@UseGuards(JwtAuthGuard)
@Post('disconnect')
Expand Down
14 changes: 14 additions & 0 deletions mcp/oauth/mcp-oauth.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const ACCESS_TOKEN_SECONDS = 60 * 60;
const REFRESH_TOKEN_SECONDS = 60 * 60 * 24 * 90;
const CODE_SECONDS = 5 * 60;
const LOGIN_REQUEST_SECONDS = 15 * 60;
const API_KEY_SECONDS = 60 * 60 * 24 * 365;

/** A pending authorization, carried through the login form as a signed token. */
export interface LoginRequest {
Expand Down Expand Up @@ -179,6 +180,19 @@ export class McpOAuthProvider implements OAuthServerProvider {
if (payload) await this.disconnectAll(payload.userId);
}

/**
* A personal key for clients that can't do the OAuth login (sent as `Authorization: Bearer <key>`).
* It is an access token valid for a year; "disconnect all" revokes it with every other token.
*/
async issueApiKey(userId: number): Promise<string | null> {
const version = await this.tokenVersion(userId);
if (version === null) return null;
return this.jwt.sign(
{ typ: 'access', clientId: 'api-key', userId, scopes: [], v: version },
{ expiresIn: API_KEY_SECONDS },
);
}

/** Invalidates every MCP token the user holds, across all clients. */
async disconnectAll(userId: number): Promise<void> {
const user = await this.userRepository.findOneBy({ id: userId });
Expand Down
Loading