diff --git a/mcp/__tests__/mcp.controller.spec.ts b/mcp/__tests__/mcp.controller.spec.ts index f452850..cff1c0a 100644 --- a/mcp/__tests__/mcp.controller.spec.ts +++ b/mcp/__tests__/mcp.controller.spec.ts @@ -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'; @@ -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 = { @@ -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') @@ -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 () => { @@ -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') @@ -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()) @@ -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); }); diff --git a/mcp/oauth/mcp-login-page.ts b/mcp/oauth/mcp-login-page.ts index be3e3a0..b3c39eb 100644 --- a/mcp/oauth/mcp-login-page.ts +++ b/mcp/oauth/mcp-login-page.ts @@ -1,9 +1,24 @@ +import { Response } from 'express'; + const escapeHtml = (value: string) => - value.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); + value.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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 = ``; return `
@@ -12,27 +27,61 @@ export function renderLoginPage(request: string, description: string, clientNameאו התחברו עם משתמש אחר:
+פג תוקף הבקשה. חזרו לאפליקציה ונסו להתחבר שוב.
'; @Controller('mcp/oauth') export class McpOAuthController { @@ -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('פג תוקף הבקשה. חזרו לאפליקציה ונסו להתחבר שוב.
'); + 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)); @@ -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; +} diff --git a/mcp/oauth/mcp-oauth.provider.ts b/mcp/oauth/mcp-oauth.provider.ts index 9211806..3da6d24 100644 --- a/mcp/oauth/mcp-oauth.provider.ts +++ b/mcp/oauth/mcp-oauth.provider.ts @@ -4,6 +4,7 @@ import { JwtService } from '@nestjs/jwt'; import { Repository } from 'typeorm'; import { Response } from 'express'; import * as bcrypt from 'bcrypt'; +import * as cookie from 'cookie'; import { createHmac } from 'crypto'; import { AuthorizationParams, OAuthServerProvider } from '@modelcontextprotocol/sdk/server/auth/provider.js'; import { OAuthRegisteredClientsStore } from '@modelcontextprotocol/sdk/server/auth/clients.js'; @@ -16,7 +17,7 @@ import { } from '@modelcontextprotocol/sdk/shared/auth.js'; import { User } from '@shared/entities/User.entity'; import { isAdmin } from '@shared/utils/permissionsUtil'; -import { renderLoginPage } from './mcp-login-page'; +import { renderLoginPage, sendLoginPage } from './mcp-login-page'; import { DEFAULT_MCP_CONSENT, MCP_CONSENT, McpConsent } from '../mcp.types'; const ACCESS_TOKEN_SECONDS = 60 * 60; @@ -44,7 +45,9 @@ export interface LoginRequest { */ @Injectable() export class McpOAuthProvider implements OAuthServerProvider { - private readonly secret = createHmac('sha256', process.env.JWT_SECRET ?? '').update('mcp-oauth').digest('hex'); + private readonly secret = createHmac('sha256', process.env.JWT_SECRET ?? '') + .update('mcp-oauth') + .digest('hex'); private readonly jwt = new JwtService({ secret: this.secret }); // Codes are single use; enough for one server instance, and they expire in 5 minutes anyway. private readonly usedCodes = new Map