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
120 changes: 106 additions & 14 deletions mcp/__tests__/mcp.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Test } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import * as request from 'supertest';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { createHash, randomBytes } from 'crypto';
import { User } from '@shared/entities/User.entity';
import { McpController } from '../mcp.controller';
Expand All @@ -24,9 +25,10 @@ describe('MCP endpoint with OAuth login', () => {
};

beforeAll(async () => {
process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-secret';
const password = await bcrypt.hash('secret', 4);
users = {
42: { id: 42, email: 'user@test', password, permissions: {}, additionalData: {} },
42: { id: 42, name: 'Test User', email: 'user@test', password, permissions: {}, additionalData: {} },
9: { id: 9, email: 'admin@test', password, permissions: { admin: true }, additionalData: {} },
};
const userRepo = {
Expand All @@ -53,8 +55,32 @@ describe('MCP endpoint with OAuth login', () => {

const server = () => app.getHttpServer();

// Requests below go to Host: localhost, so the page's own origin is http://localhost.
const origin = () => 'http://localhost';
/** The site's login cookie, as the app's own login sets it. */
const siteCookie = (payload: object) =>
`Authentication=${new JwtService({ secret: process.env.JWT_SECRET }).sign(payload)}`;

type LoginStep = (loginRequest: string) => request.Test;
const passwordLogin =
(email: string, password: string): LoginStep =>
(loginRequest) =>
request(server()).post('/mcp/oauth/login').type('form').send({ request: loginRequest, email, password });
const sessionApprove =
(cookie?: string, from = origin()): LoginStep =>
(loginRequest) => {
const req = request(server()).post('/mcp/oauth/approve').set('Host', 'localhost').type('form');
if (cookie) req.set('Cookie', cookie);
if (from) req.set('Origin', from);
return req.send({ request: loginRequest });
};

/** Runs the whole flow a client does: register, authorize page, login form, token exchange. */
async function connect(email: string, password: string) {
return connectWith(passwordLogin(email, password));
}

async function connectWith(loginStep: LoginStep) {
const redirectUri = 'http://localhost:9999/callback';
const registered = await request(server())
.post('/register')
Expand All @@ -74,30 +100,42 @@ describe('MCP endpoint with OAuth login', () => {
});
expect(page.status).toBe(200);
expect(page.text).toContain('Claude');
expect(page.text).toContain('localhost:9999');
const loginRequest = /name="request" value="([^"]+)"/.exec(page.text)[1];

const login = await request(server()).post('/mcp/oauth/login').type('form').send({ request: loginRequest, email, password });
const login = await loginStep(loginRequest);
if (login.status !== 302) return { login };
const location = new URL(login.headers.location);
expect(location.searchParams.get('state')).toBe('xyz');

const token = await request(server()).post('/token').type('form').send({
grant_type: 'authorization_code',
client_id: clientId,
code: location.searchParams.get('code'),
code_verifier: verifier,
redirect_uri: redirectUri,
});
const token = await request(server())
.post('/token')
.type('form')
.send({
grant_type: 'authorization_code',
client_id: clientId,
code: location.searchParams.get('code'),
code_verifier: verifier,
redirect_uri: redirectUri,
});
return { login, token, clientId };
}

it('advertises OAuth metadata and points unauthenticated calls at it', async () => {
const res = await request(server()).post('/mcp').set('Accept', ACCEPT).send({ jsonrpc: '2.0', id: 1, method: 'ping' });
const res = await request(server())
.post('/mcp')
.set('Accept', ACCEPT)
.send({ jsonrpc: '2.0', id: 1, method: 'ping' });
expect(res.status).toBe(401);
expect(res.headers['www-authenticate']).toMatch(/resource_metadata="http:\/\/127\.0\.0\.1:\d+\/\.well-known\/oauth-protected-resource\/mcp"/);
expect(res.headers['www-authenticate']).toMatch(
/resource_metadata="http:\/\/127\.0\.0\.1:\d+\/\.well-known\/oauth-protected-resource\/mcp"/,
);

const metadata = await request(server()).get('/.well-known/oauth-authorization-server');
expect(metadata.body).toMatchObject({ registration_endpoint: expect.stringMatching(/\/register$/), code_challenge_methods_supported: ['S256'] });
expect(metadata.body).toMatchObject({
registration_endpoint: expect.stringMatching(/\/register$/),
code_challenge_methods_supported: ['S256'],
});
});

it('logs in, issues tokens and runs tools as that user', async () => {
Expand All @@ -110,7 +148,10 @@ describe('MCP endpoint with OAuth login', () => {
.set('Accept', ACCEPT)
.send({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'whoami', arguments: {} } });
expect(call.status).toBe(200);
expect(JSON.parse(call.body.result.content[0].text)).toEqual({ userId: 42, baseUrl: expect.stringMatching(/^http:\/\/127\.0\.0\.1:\d+$/) });
expect(JSON.parse(call.body.result.content[0].text)).toEqual({
userId: 42,
baseUrl: expect.stringMatching(/^http:\/\/127\.0\.0\.1:\d+$/),
});

const refreshed = await request(server())
.post('/token')
Expand All @@ -127,7 +168,10 @@ describe('MCP endpoint with OAuth login', () => {

it('revoking a token disconnects the user', async () => {
const { token, clientId } = await connect('user@test', 'secret');
const revoke = await request(server()).post('/revoke').type('form').send({ client_id: clientId, token: token.body.access_token });
const revoke = await request(server())
.post('/revoke')
.type('form')
.send({ client_id: clientId, token: token.body.access_token });
expect(revoke.status).toBe(200);

const call = await request(server())
Expand All @@ -149,6 +193,54 @@ describe('MCP endpoint with OAuth login', () => {
expect(call.status).toBe(401);
});

it('approves in one click as the user signed in to the site', async () => {
const { login, token } = await connectWith(sessionApprove(siteCookie({ id: 42, username: 'user@test' })));
expect(login.status).toBe(302);
expect(token.status).toBe(200);
const call = await request(server())
.post('/mcp')
.set('Authorization', `Bearer ${token.body.access_token}`)
.set('Accept', ACCEPT)
.send({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'whoami', arguments: {} } });
expect(JSON.parse(call.body.result.content[0].text).userId).toBe(42);
});

it('refuses one-click approval without a valid session or from another site', async () => {
const user = siteCookie({ id: 42 });
expect((await connectWith(sessionApprove())).login.status).toBe(401);
expect((await connectWith(sessionApprove(user, 'https://evil.example'))).login.status).toBe(401);
expect((await connectWith(sessionApprove(user, ''))).login.status).toBe(401);
expect((await connectWith(sessionApprove(siteCookie({ id: 42, impersonated: true })))).login.status).toBe(401);
expect((await connectWith(sessionApprove(siteCookie({ id: 9 })))).login.status).toBe(401);
expect((await connectWith(sessionApprove(siteCookie({ id: -1, permissions: { admin: true } })))).login.status).toBe(
401,
);
const forged = `Authentication=${new JwtService({ secret: 'other' }).sign({ id: 42 })}`;
expect((await connectWith(sessionApprove(forged))).login.status).toBe(401);
});

it('tells the login page who is signed in, only to itself', async () => {
const ok = await request(server())
.post('/mcp/oauth/session')
.set('Host', 'localhost')
.set('Cookie', siteCookie({ id: 42 }))
.set('Origin', origin());
expect(ok.status).toBe(200);
expect(ok.body).toEqual({ name: 'Test User' });
const foreign = await request(server())
.post('/mcp/oauth/session')
.set('Host', 'localhost')
.set('Cookie', siteCookie({ id: 42 }))
.set('Origin', 'https://evil.example');
expect(foreign.status).toBe(401);
});

it('serves the login page unframeable', async () => {
const { login } = await connect('user@test', 'wrong');
expect(login.headers['content-security-policy']).toBe("frame-ancestors 'none'");
expect(login.headers['x-frame-options']).toBe('DENY');
});

it('refuses GET', async () => {
expect((await request(server()).get('/mcp')).status).toBe(405);
});
Expand Down
79 changes: 64 additions & 15 deletions mcp/oauth/mcp-login-page.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
import { Response } from 'express';

const escapeHtml = (value: string) =>
value.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
value.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));

/** Sign-in page shown when an MCP client (Claude, Codex, Gemini…) asks to connect. Posts to `/mcp/oauth/login`. */
export function renderLoginPage(request: string, description: string, clientName?: string, error?: string): string {
const client = escapeHtml(clientName || 'אפליקציית AI');
/**
* Sign-in page shown when an MCP client (Claude, Codex, Gemini…) asks to connect.
* The password form posts to `/mcp/oauth/login`. When the browser already has a site login, the page
* also offers one-click approval (`/mcp/oauth/approve`); it asks `/mcp/oauth/session` from script,
* because the site's SameSite=Strict cookie isn't sent on the redirect from the AI app but is on same-site requests.
*/
export function renderLoginPage(
request: string,
description: string,
client: { clientName?: string; redirectUri: string },
error?: string,
): string {
const name = escapeHtml(client.clientName || 'אפליקציית AI');
// The name is whatever the client registered; where it sends the user back is what identifies it.
const returnHost = escapeHtml(new URL(client.redirectUri).host);
const requestInput = `<input type="hidden" name="request" value="${escapeHtml(request)}">`;
return `<!doctype html>
<html lang="he" dir="rtl">
<head>
Expand All @@ -12,27 +27,61 @@ export function renderLoginPage(request: string, description: string, clientName
<title>התחברות</title>
<style>
body { font-family: system-ui, -apple-system, 'Segoe UI', Arial, sans-serif; background: #f4f5f7; margin: 0; display: flex; min-height: 100vh; align-items: center; justify-content: center; }
form { background: #fff; padding: 32px; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,.08); width: 100%; max-width: 360px; box-sizing: border-box; margin: 16px; }
main { background: #fff; padding: 32px; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,.08); width: 100%; max-width: 360px; box-sizing: border-box; margin: 16px; }
h1 { font-size: 20px; margin: 0 0 8px; }
p { color: #555; margin: 0 0 24px; line-height: 1.5; }
label { display: block; font-size: 14px; margin-bottom: 4px; }
input[type=email], input[type=password] { width: 100%; padding: 10px; margin-bottom: 16px; border: 1px solid #ccc; border-radius: 8px; font-size: 16px; box-sizing: border-box; }
button { width: 100%; padding: 12px; border: 0; border-radius: 8px; background: #1976d2; color: #fff; font-size: 16px; cursor: pointer; }
.error { color: #c62828; margin-bottom: 16px; }
#session { margin-bottom: 24px; }
#session p { margin: 16px 0 0; text-align: center; }
</style>
</head>
<body>
<form method="post" action="/mcp/oauth/login">
<h1>חיבור ${client}</h1>
<p>${client} ${escapeHtml(description)} התחברו עם המייל והסיסמה של המערכת כדי לאשר.</p>
<main>
<h1>חיבור ${name}</h1>
<p>${name} ${escapeHtml(
description,
)} אחרי האישור תחזרו אל <b dir="ltr">${returnHost}</b>. אשרו רק אם זו האפליקציה שאתם מחברים.</p>
${error ? `<div class="error">${escapeHtml(error)}</div>` : ''}
<input type="hidden" name="request" value="${escapeHtml(request)}">
<label for="email">מייל</label>
<input id="email" name="email" type="email" autocomplete="username" required autofocus>
<label for="password">סיסמה</label>
<input id="password" name="password" type="password" autocomplete="current-password" required>
<button type="submit">התחברות ואישור</button>
</form>
<div id="session" hidden>
<form method="post" action="/mcp/oauth/approve">
${requestInput}
<button type="submit">אישור בתור <span id="session-name"></span></button>
</form>
<p>או התחברו עם משתמש אחר:</p>
</div>
<form method="post" action="/mcp/oauth/login">
${requestInput}
<label for="email">מייל</label>
<input id="email" name="email" type="email" autocomplete="username" required autofocus>
<label for="password">סיסמה</label>
<input id="password" name="password" type="password" autocomplete="current-password" required>
<button type="submit">התחברות ואישור</button>
</form>
</main>
<script>
fetch('/mcp/oauth/session', { method: 'POST', credentials: 'same-origin' })
.then(function (res) { return res.ok ? res.json() : null; })
.then(function (session) {
if (!session) return;
document.getElementById('session-name').textContent = session.name;
document.getElementById('session').hidden = false;
})
.catch(function () {});
</script>
</body>
</html>`;
}

/** Sends the sign-in page; it must never be framed, since it can approve with one click. */
export function sendLoginPage(res: Response, status: number, html: string) {
res
.status(status)
.setHeader('Content-Security-Policy', "frame-ancestors 'none'")
.setHeader('X-Frame-Options', 'DENY')
.setHeader('Cache-Control', 'no-store')
.type('html')
.send(html);
}
49 changes: 44 additions & 5 deletions mcp/oauth/mcp-oauth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { Body, Controller, Post, Request, Res, UseGuards } from '@nestjs/common';
import { Response } from 'express';
import { Request as ExpressRequest, Response } from 'express';
import { JwtAuthGuard } from '@shared/auth/jwt-auth.guard';
import { AuthenticatedRequest } from '@shared/auth/auth.types';
import { getUserIdFromUser } from '@shared/auth/auth.util';
import { McpOAuthProvider } from './mcp-oauth.provider';
import { renderLoginPage } from './mcp-login-page';
import { sendLoginPage } from './mcp-login-page';
import { mcpBaseUrl } from './mcp-auth.middleware';

const EXPIRED_PAGE = '<p dir="rtl">פג תוקף הבקשה. חזרו לאפליקציה ונסו להתחבר שוב.</p>';

@Controller('mcp/oauth')
export class McpOAuthController {
Expand All @@ -15,13 +18,43 @@ export class McpOAuthController {
async login(@Body() body: { request?: string; email?: string; password?: string }, @Res() res: Response) {
const request = this.provider.verifyLoginRequest(body?.request ?? '');
if (!request) {
res.status(400).type('html').send('<p dir="rtl">פג תוקף הבקשה. חזרו לאפליקציה ונסו להתחבר שוב.</p>');
res.status(400).type('html').send(EXPIRED_PAGE);
return;
}
const user = await this.provider.login(body.email, body.password);
if (!user) {
const retry = this.provider.signLoginRequest(request);
res.status(401).type('html').send(renderLoginPage(retry, this.provider.consent.description, request.clientName, 'מייל או סיסמה שגויים'));
sendLoginPage(res, 401, this.provider.loginPage(request, 'מייל או סיסמה שגויים'));
return;
}
res.redirect(302, this.provider.issueCodeRedirect(request, user.id));
}

/** Who is signed in to the site in this browser, so the login page can offer one-click approval. */
@Post('session')
async session(@Request() req: ExpressRequest, @Res() res: Response) {
const user = sameOrigin(req) ? await this.provider.sessionUser(req.headers.cookie) : null;
res.setHeader('Cache-Control', 'no-store');
if (!user) {
res.status(401).json({ error: 'not signed in' });
return;
}
res.status(200).json({ name: user.name || user.email });
}

/**
* One-click approval as the user signed in to the site. Only from the login page itself: the site cookie
* is SameSite=Strict and the Origin must be this server, so another site can't approve on the user's behalf.
*/
@Post('approve')
async approve(@Request() req: ExpressRequest, @Body() body: { request?: string }, @Res() res: Response) {
const request = this.provider.verifyLoginRequest(body?.request ?? '');
if (!request) {
res.status(400).type('html').send(EXPIRED_PAGE);
return;
}
const user = sameOrigin(req) ? await this.provider.sessionUser(req.headers.cookie) : null;
if (!user) {
sendLoginPage(res, 401, this.provider.loginPage(request, 'לא נמצאה התחברות פעילה. התחברו עם מייל וסיסמה.'));
return;
}
res.redirect(302, this.provider.issueCodeRedirect(request, user.id));
Expand All @@ -36,3 +69,9 @@ export class McpOAuthController {
return { success: true };
}
}

/** The request came from a page on this server (browsers send Origin on POST). */
function sameOrigin(req: ExpressRequest): boolean {
const baseUrl = mcpBaseUrl(req);
return !!baseUrl && req.headers.origin === baseUrl;
}
Loading
Loading