diff --git a/.env.sample b/.env.sample index bb7e7e22..50138739 100644 --- a/.env.sample +++ b/.env.sample @@ -20,6 +20,12 @@ JWT_SECRET_REFRESH_TOKEN=abacaba # JWT secret for user's access token JWT_SECRET_ACCESS_TOKEN=belarus +# JWT secret for oauth client's access token +JWT_OAUTH_SECRET_ACCESS_TOKEN=fxfxfx + +# JWT secret for oauth client's refresh token +JWT_OAUTH_SECRET_REFRESH_TOKEN=xfxfxf + # max document could for one read request to the database MAX_DB_READ_BATCH_SIZE=100000 @@ -92,6 +98,9 @@ SSO_SP_ENTITY_ID=urn:hawk:tracker:saml ## SAML state store type (memory or redis, default: redis) SAML_STORE_TYPE=redis +## OAuthRequest data store type (memory or redis, default: redis) +OAUTH_REQUEST_STORE_TYPE=redis + # String generated when we create GitHub App, see task-managers-integration-implementation-plan.md -> 2.1.1 GITHUB_WEBHOOK_SECRET=623f6ed30b1f762803149893263a95cc2687fe3ce5a9f30648dcbf25712afc9e diff --git a/.env.test b/.env.test index 19787b59..25a7a3de 100644 --- a/.env.test +++ b/.env.test @@ -17,6 +17,12 @@ JWT_SECRET_REFRESH_TOKEN=abacaba # JWT secret for user's access token JWT_SECRET_ACCESS_TOKEN=belarus +# JWT secret for oauth client's access token +JWT_OAUTH_SECRET_ACCESS_TOKEN=fxfxfx + +# JWT secret for oauth client's refresh token +JWT_OAUTH_SECRET_REFRESH_TOKEN=xfxfxf + # JWT secret for project's tokens (used in catcher) JWT_SECRET_PROJECT_TOKEN=qwerty diff --git a/package.json b/package.json index 653c6c6b..1ce42bfc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hawk.api", - "version": "1.7.1", + "version": "1.7.2", "main": "index.ts", "license": "BUSL-1.1", "scripts": { @@ -43,6 +43,7 @@ "@graphql-tools/utils": "^8.9.0", "@hawk.so/nodejs": "^3.3.2", "@hawk.so/types": "^0.7.0", + "@modelcontextprotocol/express": "^2.0.2", "@modelcontextprotocol/node": "^2.1.2", "@modelcontextprotocol/server": "^2.4.0", "@n1ru4l/json-patch-plus": "^0.2.0", diff --git a/src/index.ts b/src/index.ts index 188411db..780ef80c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -29,11 +29,13 @@ import { graphqlUploadExpress } from 'graphql-upload'; import { metricsMiddleware, createMetricsServer, graphqlMetricsPlugin } from './metrics'; import { requestLogger } from './utils/logger'; import ReleasesFactory from './models/releasesFactory'; +import OAuthClientsFactory from './models/oauthClientsFactory'; import RedisHelper from './redisHelper'; import { appendSsoRoutes } from './sso'; import { appendGitHubRoutes } from './integrations/github'; import { appendAiAssistantRoutes } from './services/askAi'; import { appendMCPRoutes } from './integrations/mcp'; +import { appendOAuthRoutes } from './oauth'; /** * Option to enable playground @@ -174,6 +176,9 @@ class HawkAPI { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const releasesFactory = new ReleasesFactory(mongo.databases.events!); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const oauthFactory = new OAuthClientsFactory(mongo.databases.hawk!); + return { usersFactory, workspacesFactory, @@ -181,6 +186,7 @@ class HawkAPI { plansFactory, businessOperationsFactory, releasesFactory, + oauthFactory, }; } @@ -279,6 +285,12 @@ class HawkAPI { */ appendAiAssistantRoutes(this.app); + /** + * Append OAuth routes to Express app + * Note: This must be called after database connections are established + */ + appendOAuthRoutes(this.app, sharedFactories); + /** * Append MCP integration routes to Express app using shared factories * Note: This must be called after database connections are established diff --git a/src/integrations/mcp/index.ts b/src/integrations/mcp/index.ts index 4a6953bf..aef7d922 100644 --- a/src/integrations/mcp/index.ts +++ b/src/integrations/mcp/index.ts @@ -1,6 +1,15 @@ +/* eslint-disable @typescript-eslint/camelcase, camelcase */ import express from 'express'; -import { ContextFactories } from 'src/types/graphql'; +import { ContextFactories } from '../../types/graphql'; import { createMCPHandler } from './mcp'; +import { verifyJWT } from '../../utils/verifyJWT'; +import { requireBearerAuth } from '@modelcontextprotocol/express'; +import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server'; + +import type { Response } from 'express'; +import type { OAuthJWTData, ProtectedResourceMetadataResponse } from '../../oauth/types'; +import type { AuthInfo, OAuthTokenVerifier } from '@modelcontextprotocol/server'; +import type { Secret } from 'jsonwebtoken'; /** * Appends MCP route to Express App @@ -11,5 +20,82 @@ import { createMCPHandler } from './mcp'; export function appendMCPRoutes(app: express.Application, factories: ContextFactories): void { const handler = createMCPHandler(factories); - app.use('/integration/mcp', (req, res) => handler(req, res, req.body)); + /** + * Used by {@link authMiddleware}. Checks access token validity + * + * On SUCCESS returns the resulting {@link AuthInfo}, which the serving entry surfaces to MCP request handlers + * + * On ERROR throws OAuthError + */ + const tokenVerifier: OAuthTokenVerifier = { + verifyAccessToken: async (token: string) => { + const data = verifyJWT(token, process.env.JWT_OAUTH_SECRET_ACCESS_TOKEN as Secret); + + if (!data) { + throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid or expired access token'); + } + + if ( + typeof data.userId !== 'string' || + typeof data.clientId !== 'string' || + !Array.isArray(data.scopes) || + !data.scopes.every(scope => scope === 'mcp:tools' || scope === 'mcp:resources') + ) { + throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid or expired access token'); + } + + const userId = await factories.oauthFactory.trackUse(data.userId, data.clientId); + + if (!userId) { + throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid or expired access token'); + } + + return { + token, + clientId: data.clientId, + scopes: data.scopes, + expiresAt: data.exp, + extra: { userId }, + }; + }, + }; + + /** + * Express middleware that requires a valid Bearer token in the Authorization header + * + * On failure the middleware sends a JSON OAuth error body and a WWW-Authenticate: Bearer … + * challenge that includes the configured resource_metadata URL + * so clients can discover the Authorization Server + */ + const authMiddleware = requireBearerAuth({ + verifier: tokenVerifier, + resourceMetadataUrl: + `${process.env.API_URL}/.well-known/oauth-protected-resource/integration/mcp`, + }); + + /** + * Protected Resource Metadata (PRM) discovery + * + * Client retrieves metadata the authorization server, + * supported scopes, and other resource information + */ + app.get( + '/.well-known/oauth-protected-resource/integration/mcp', + (_req, res: Response) => { + res.setHeader('Access-Control-Allow-Origin', '*'); + res.json({ + resource: `${process.env.API_URL}/integration/mcp`, + authorization_servers: [ + `${process.env.API_URL}`, + ], + scopes_supported: [ + 'mcp:tools', + 'mcp:resources', + ], + }); + } + ); + + app.options('/integration/mcp', (_req, res) => res.sendStatus(204)); + app.use('/integration/mcp', authMiddleware, (req, res) => handler(req, res, req.body)); } diff --git a/src/integrations/mcp/mcp.ts b/src/integrations/mcp/mcp.ts index 1e68a115..13604d7c 100644 --- a/src/integrations/mcp/mcp.ts +++ b/src/integrations/mcp/mcp.ts @@ -1,5 +1,5 @@ -import { createMcpHandler, McpServer } from '@modelcontextprotocol/server'; import { toNodeHandler } from '@modelcontextprotocol/node'; +import { createMcpHandler, McpServer } from '@modelcontextprotocol/server'; import { ContextFactories } from 'src/types/graphql'; import type { NodeMcpRequestHandler } from '@modelcontextprotocol/node'; @@ -10,30 +10,13 @@ import type { NodeMcpRequestHandler } from '@modelcontextprotocol/node'; * @param factories - context factories for database access * @returns configured MCP server */ -function createMCPServer(factories: ContextFactories) { +const createMCPServer = (factories: ContextFactories) => { const server = new McpServer({ name: 'server', version: '0.0.0', description: 'A test server', }); - server.registerTool( - 'hello_world', - { - description: 'A test tool to greet the user', - }, - async () => { - return { - content: [ - { - type: 'text' as const, - text: 'Hi', - }, - ], - }; - } - ); - return server; }; diff --git a/src/models/oauthClient.ts b/src/models/oauthClient.ts new file mode 100644 index 00000000..ac37891a --- /dev/null +++ b/src/models/oauthClient.ts @@ -0,0 +1,113 @@ +import { Collection, ObjectId, OptionalId } from 'mongodb'; +import jwt from 'jsonwebtoken'; +import AbstractModel from './abstractModel'; + +import type { Secret } from 'jsonwebtoken'; +import type { OAuthClientDBScheme, TokenPermissions, TokensPair } from '@hawk.so/types'; + +export default class OAuthClientModel extends AbstractModel> implements OAuthClientDBScheme { + /** + * External client identifier + */ + public _id!: ObjectId; + + /** + * Token owner id + */ + public userId!: string; + + /** + * OAuth client identifier, supplied as a Client ID Metadata Document URL. + */ + public clientId!: string; + + /** + * Hostname from the redirect URI used when this grant was authorized. + */ + public redirectHost!: string; + + /** + * OAuth scopes granted to this client. + */ + public scopes!: string[]; + + /** + * What client is allowed to do + */ + public permissions!: TokenPermissions[]; + + /** + * Label set by user + */ + public label!: string; + + /** + * Last time the client interacted with hawk api + */ + public lastUsedAt!: Date | null; + + /** + * Usage count + */ + public requestCount!: number; + + /** + * Creation date + */ + public createdAt!: Date; + + /** + * Current refresh-token identifier used to detect token reuse. + */ + public jti!: string; + + /** + * Time when this grant was revoked, or null while active. + */ + public revokedAt!: Date | null; + + public collection!: Collection>; + + constructor(oauthClient: OptionalId) { + super(oauthClient); + this.collection = this.dbConnection.collection>('oauthClients'); + } + + /** + * Signs an access and refresh token pair for this stored grant. + * + * @param refreshJti - Refresh-token identifier; defaults to the grant's current JTI. + * @returns The newly signed MCP access and refresh tokens. + */ + public async generateTokensPair(refreshJti: string = this.jti): Promise { + const accessToken = jwt.sign( + { + userId: this.userId, + clientId: this.clientId, + scopes: this.scopes, + }, + process.env.JWT_OAUTH_SECRET_ACCESS_TOKEN as Secret, + { + expiresIn: '15m', + } + ); + + const refreshToken = jwt.sign( + { + userId: this.userId, + clientId: this.clientId, + scopes: this.scopes, + }, + process.env.JWT_OAUTH_SECRET_REFRESH_TOKEN as Secret, + { + expiresIn: '30d', + jwtid: refreshJti, + } + ); + + return { + accessToken, + refreshToken, + }; + } +} diff --git a/src/models/oauthClientsFactory.ts b/src/models/oauthClientsFactory.ts new file mode 100644 index 00000000..51c00690 --- /dev/null +++ b/src/models/oauthClientsFactory.ts @@ -0,0 +1,134 @@ +import { Collection, Db, OptionalId } from 'mongodb'; +import AbstractModelFactory from './abstactModelFactory'; +import OAuthClientModel from './oauthClient'; +import type { OAuthClientDBScheme } from '@hawk.so/types'; +import { randomUUID } from 'crypto'; + +export default class OAuthClientsFactory extends AbstractModelFactory, OAuthClientModel> { + protected collection: Collection>; + + constructor(dbConnection: Db) { + super(dbConnection, OAuthClientModel); + this.collection = dbConnection.collection('oauthClients'); + } + + /** + * Creates a new grant for an authorized OAuth client. + * @param userId - ID of the user authorizing the client. + * @param clientId - Public client identifier. + * @param redirectHost - Host from the redirect URI used for authorization. + * @returns Nothing. + */ + public async create( + userId: string, + clientId: string, + redirectHost: string + ): Promise { + const refreshJti = randomUUID(); + await this.collection.updateOne( + { userId, clientId }, + { + $set: { + redirectHost, + revokedAt: null, + jti: refreshJti, + scopes: ['mcp:tools', 'mcp:resources'], + }, + $setOnInsert: { + userId, + clientId, + createdAt: new Date(), + label: 'MCP token', + lastUsedAt: null, + permissions: ['read', 'write'], + requestCount: 0, + }, + }, + { upsert: true } + ); + } + + /** + * Finds the grant for a user and client. + * + * @param userId - User identifier bound to the grant. + * @param clientId - Public client identifier bound to the grant. + * @returns The OAuth grant, or null when it does not exist. + */ + public async findGrant(userId: string, clientId: string): Promise { + const grant = await this.findOne({ userId, clientId }); + + return grant; + } + + /** + * Atomically replaces the active refresh-token identifier to prevent token reuse. + * + * @param userId - User identifier bound to the grant. + * @param clientId - Public client identifier bound to the grant. + * @param oldJti - Refresh-token identifier currently stored on the grant. + * @param newJti - Refresh-token identifier to store. + * @returns Whether the current identifier was successfully replaced. + */ + public async rotateRefreshJti( + userId: string, + clientId: string, + oldJti: string, + newJti: string + ): Promise { + const result = await this.collection.updateOne( + { userId, clientId, jti: oldJti, revokedAt: null }, + { $set: { jti: newJti } } + ); + + return result.modifiedCount === 1; + } + + /** + * Revokes an active grant bound to the specified client. + * + * @param userId - User identifier bound to the grant. + * @param clientId - Public client identifier bound to the grant. + * @returns Whether an active grant was revoked. + */ + public async revoke(userId: string, clientId: string): Promise { + const result = await this.collection.updateOne( + { userId, clientId, revokedAt: null }, + { $set: { revokedAt: new Date() } } + ); + + return result.modifiedCount === 1; + } + + /** + * Tracks token usage. + * Updates `lastUsedAt` and increases `requestCount` + * @param userId - User identifier bound to the grant. + * @param clientId - Client identifier encoded in the access token. + * @returns Grant owner ID when the grant is active, otherwise null. + */ + public async trackUse(userId: string, clientId: string): Promise { + const filter = { + userId, + clientId, + revokedAt: null, + }; + const grant = await this.collection.findOne(filter); + + if (!grant) { + return null; + } + + const update: { $inc: { requestCount: number }; $set?: { lastUsedAt: Date } } = { + $inc: { requestCount: 1 }, + }; + + if (!grant.lastUsedAt || grant.lastUsedAt.getTime() <= Date.now() - 60 * 60 * 1000) { + update.$set = { lastUsedAt: new Date() }; + } + + const result = await this.collection.updateOne(filter, update); + + return result.matchedCount === 1 ? grant.userId ?? null : null; + } +} diff --git a/src/oauth/helpers/generateOAuthClientId.ts b/src/oauth/helpers/generateOAuthClientId.ts new file mode 100644 index 00000000..6ef265b8 --- /dev/null +++ b/src/oauth/helpers/generateOAuthClientId.ts @@ -0,0 +1,9 @@ +import crypto from 'node:crypto'; + +/** + * Generates random clientId + * @returns string + */ +export function generateOAuthClientId() { + return `hawk-client:${crypto.randomUUID()}`; +}; diff --git a/src/oauth/helpers/isLoopback.ts b/src/oauth/helpers/isLoopback.ts new file mode 100644 index 00000000..2c7b267b --- /dev/null +++ b/src/oauth/helpers/isLoopback.ts @@ -0,0 +1,24 @@ +/** + * Checks if provided uri is a loopback interface + * @param uri uri to check + * @returns 'true' if uri is valid, 'false' if uri is invalid + */ +export function isLoopback(uri: string): boolean { + try { + const url = new URL(uri); + const hostname = url.hostname + .toLowerCase() + // removes brackets around ipv6 loopback uri ([::1]) + .replace(/^\[|\]$/g, ''); + const protocol = url.protocol; + + return ( + (protocol === 'https:' || protocol === 'http:') && + (hostname === 'localhost' || + hostname === '127.0.0.1' || + hostname === '::1') + ); + } catch { + return false; + } +}; diff --git a/src/oauth/index.ts b/src/oauth/index.ts new file mode 100644 index 00000000..25270bff --- /dev/null +++ b/src/oauth/index.ts @@ -0,0 +1,372 @@ +/* eslint-disable @typescript-eslint/camelcase, camelcase */ +import express from 'express'; +import crypto from 'node:crypto'; +import { verifyJWT } from '../utils/verifyJWT'; +import { createOAuthStore } from './store/storeFactory'; +import { OAuthErrorCode, OAuthGrantType } from '@hawk.so/types'; +import { generateOAuthClientId } from './helpers/generateOAuthClientId'; +import { isLoopback } from './helpers/isLoopback'; + +import type { Request, Response } from 'express'; +import type { OAuthRequest, OAuthTokenRequest, TokenResponse } from '@hawk.so/types'; +import type { ContextFactories } from '../types/graphql'; +import type { Secret } from 'jsonwebtoken'; +import type { + AuthorizationServerMetadataResponse, + ClientInformationResponse, + OAuthJWTData +} from './types'; + +/** + * Redirect uris that are allowed to be used in OAuth Flow. + * Restricts redirects to loopback interfaces and explicitly allowed URIs. + */ +const ALLOWED_REDIRECT_URIS = new Set(); + +function isAllowedRedirectUri(uri: string): boolean { + return isLoopback(uri) || ALLOWED_REDIRECT_URIS.has(uri); +} + +/** + * Implements OAuth Authorization Flow following + * {@link https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-16 | OAuth 2.1} + * and + * {@link https://modelcontextprotocol.io/docs/2026-07-28/tutorials/security/authorization | Authorization in MCP} + * + * Flow: + * 1. The client discovers the OAuth metadata and authorization endpoints. + * 2. The user signs in and supplies an authorization header. + * 3. The server generates an authorization code and stores the pending request data. + * 4. The client exchanges the code together with the PKCE verifier for a token pair. + * 5. Refresh tokens can be exchanged for a new access and refresh token pair. + * + * @param app - Express application instance + * @param factories - context factories for database access + */ +export function appendOAuthRoutes(app: express.Application, factories: ContextFactories) { + const store = createOAuthStore(); + + /** + * Issues a short-lived access token and a refresh token tied to a stored grant. + * + * @param userId - user identifier bound to the grant + * @param clientId - client identifier bound to the grant + * @param previousRefreshJti - present for refresh requests and atomically consumed + * @returns TokenResponse or null if the grant disappeared or rotation lost a race + */ + async function createTokenResponse( + userId: string, + clientId: string, + previousRefreshJti?: string + ): Promise { + const grant = await factories.oauthFactory.findGrant(userId, clientId); + + if (!grant || grant.revokedAt) { + return null; + } + + const nextRefreshJti = previousRefreshJti ? crypto.randomUUID() : grant.jti; + const tokensPair = await grant.generateTokensPair(nextRefreshJti); + + if (previousRefreshJti) { + const rotated = await factories.oauthFactory.rotateRefreshJti( + userId, + clientId, + previousRefreshJti, + nextRefreshJti + ); + + if (!rotated) { + return null; + } + } + + return { + access_token: tokensPair.accessToken, + refresh_token: tokensPair.refreshToken, + token_type: 'Bearer', + expires_in: 15 * 60, + scope: grant.scopes.join(' '), + }; + }; + + /** + * Authorization Server Discovery + * + * Client retrieves another set of metadata properties + * that will allow it to know the endpoints it needs to complete the authorization flow + */ + app.get( + '/.well-known/oauth-authorization-server', + (_req, res: Response) => { + res.setHeader('Access-Control-Allow-Origin', '*'); + res.json({ + issuer: `${process.env.API_URL}`, + + authorization_endpoint: + `${process.env.GARAGE_URL}/authorize`, + + token_endpoint: + `${process.env.API_URL}/token/oauth`, + + registration_endpoint: + `${process.env.API_URL}/register/oauth`, + + response_types_supported: [ 'code' ], + + grant_types_supported: [ + OAuthGrantType.authorizationCode, + OAuthGrantType.refreshToken, + ], + + token_endpoint_auth_methods_supported: [ + 'none', + ], + + code_challenge_methods_supported: [ + 'S256', + ], + }); + } + ); + + /** + * Dynamic Client Registration (DCR) + * + * Generates random clientId + * + * Currently we do not have any real authorization server, but this endpoint is still + * implemented in order not to bug the user with manual clientId creation in some IDEs (VSCode) + */ + app.post('/register/oauth', (req, res: Response) => { + res.status(201).json({ + client_id: generateOAuthClientId(), + client_name: req.body.client_name, + redirect_uris: req.body.redirect_uris, + grant_types: [OAuthGrantType.authorizationCode, OAuthGrantType.refreshToken], + response_types: [ 'code' ], + }); + }); + + /** + * Authorization Endpoint callback + * https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-16#name-authorization-endpoint + * + * Authenticates the resource owner and establishes + * whether the resource owner grants or denies the client's access request + * + * Assuming the resource owner grants access, the authorization server redirects + * the user agent back to the client using a redirect URI that passes server policy. + * The redirect URI includes an authorization code and any local state + * provided by the client earlier + */ + app.post('/authorize/oauth', async (req: Request<{}, {}, OAuthRequest>, res, next) => { + try { + const { + client_id, + redirect_uri, + state, + code_challenge, + code_challenge_method, + } = req.body || {}; + + if ( + req.context.user.accessTokenExpired || + !req.context.user.id + ) { + return res.status(401).json({ + error: OAuthErrorCode.invalidGrant, + }); + } + + if ( + typeof client_id !== 'string' || !client_id || + typeof redirect_uri !== 'string' || !redirect_uri || + typeof code_challenge !== 'string' || !code_challenge || code_challenge.length > 128 || + (state !== undefined && typeof state !== 'string') || + code_challenge_method !== 'S256' + ) { + return res.status(400).json({ + error: OAuthErrorCode.invalidRequest, + }); + } + + if (!isAllowedRedirectUri(redirect_uri)) { + return res.status(400).json({ + error: OAuthErrorCode.invalidRequest, + }); + } + + /** + * Authorization code generation + */ + const code = crypto + .randomBytes(32) + .toString('base64url'); + + /** + * Save OAuthRequest data to retrieve data on the next step + */ + await store.saveOAuthRequest(code, { + userId: req.context.user.id, + clientId: client_id, + redirectUri: redirect_uri, + codeChallenge: code_challenge, + }); + + const callback = new URL(redirect_uri); + + /** + * Add parameters to redirect_uri + */ + callback.searchParams.set('code', code); + + if (state) { + callback.searchParams.set('state', state); + } + + return res.json({ + redirect_uri: callback.toString(), + }); + } catch (error) { + next(error); + } + }); + + /** + * Token Endpoint + * https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-16#name-token-endpoint + * + * Token endpoint is used by the client to exchange the authorization code to access token or + * generate new {@link TokensPair} by refresh token + * + * ON 'authorization_code' GRANT TYPE: + * - Validates the authorization code, validates the code verifier, and ensures that + * the redirect URI received matches the URI used to redirect the user agent to the client in previous step. + * If valid, the authorization server responds back with an access token + * + */ + app.post('/token/oauth', async (req: Request<{}, {}, OAuthTokenRequest>, res, next) => { + try { + const { body } = req; + + if (!body || typeof body !== 'object') { + return res.status(400).json({ error: OAuthErrorCode.invalidRequest }); + } + + res.set('Cache-Control', 'no-store'); + res.set('Pragma', 'no-cache'); + + if (body.grant_type === OAuthGrantType.refreshToken) { + const { + refresh_token, + client_id, + } = body; + + if (typeof refresh_token !== 'string' || !refresh_token || + typeof client_id !== 'string' || !client_id) { + return res.status(400).json({ error: OAuthErrorCode.invalidRequest }); + } + + const data = verifyJWT(refresh_token, process.env.JWT_OAUTH_SECRET_REFRESH_TOKEN as Secret); + + if (!data) { + return res.status(400).json({ error: OAuthErrorCode.invalidGrant }); + } + + if ( + typeof data.userId !== 'string' || + typeof data.clientId !== 'string' || + typeof data.jti !== 'string' || + data.clientId !== client_id + ) { + return res.status(400).json({ error: OAuthErrorCode.invalidGrant }); + } + + const grant = await factories.oauthFactory.findGrant(data.userId, client_id); + + if (!grant || grant.revokedAt) { + return res.status(400).json({ error: OAuthErrorCode.invalidGrant }); + } + + if (grant.jti !== data.jti) { + await factories.oauthFactory.revoke(data.userId, client_id); + return res.status(400).json({ error: OAuthErrorCode.invalidGrant }); + } + + const response = await createTokenResponse(data.userId, client_id, data.jti); + + if (!response) { + await factories.oauthFactory.revoke(data.userId, client_id); + console.warn(`[OAuth] couldn't rotate refresh token for client: ${client_id}`); + + return res.status(400).json({ error: OAuthErrorCode.invalidGrant }); + } + + return res.json(response); + } + + if (body.grant_type !== OAuthGrantType.authorizationCode) { + return res.status(400).json({ + error: OAuthErrorCode.unsupportedGrantType, + }); + } + + const { + code, + code_verifier, + client_id, + redirect_uri, + } = body; + + if ( + typeof code !== 'string' || !code || + typeof code_verifier !== 'string' || !code_verifier || + typeof client_id !== 'string' || !client_id || + typeof redirect_uri !== 'string' || !redirect_uri + ) { + return res.status(400).json({ error: OAuthErrorCode.invalidRequest }); + } + + /** + * Retrieve OAuthRequest data from the store + */ + const data = await store.getOAuthRequest(code); + + /** + * Validate codeChallenge + */ + const calculatedChallenge = crypto + .createHash('sha256') + .update(code_verifier) + .digest('base64url'); + + if ( + !data || + data.clientId !== client_id || + data.redirectUri !== redirect_uri || + calculatedChallenge !== data.codeChallenge + ) { + return res.status(400).json({ error: OAuthErrorCode.invalidGrant }); + } + + await factories.oauthFactory.create( + data.userId, + data.clientId, + new URL(data.redirectUri).host + ); + + const response = await createTokenResponse(data.userId, data.clientId); + + if (!response) { + console.warn(`[OAuth] couldn't create token response for client: ${data.clientId}`); + + return res.status(400).json({ error: OAuthErrorCode.invalidGrant }); + } + + return res.json(response); + } catch (error) { + next(error); + } + }); +}; diff --git a/src/oauth/store/OAuthRequestStoreInterface.ts b/src/oauth/store/OAuthRequestStoreInterface.ts new file mode 100644 index 00000000..272a76d0 --- /dev/null +++ b/src/oauth/store/OAuthRequestStoreInterface.ts @@ -0,0 +1,33 @@ +import type { OAuthRequestData } from './types'; + +/** + * Interface for OAuthRequset data store implementations + * + * Defines contract for storing temporary data needed for OAuth authentication flow: + * - AuthRequest: maps authorization code to AuthRequest data + */ +export interface OAuthRequestStoreInterface { + /** + * Store type identifier + * Used for logging and debugging purposes + * + * @example "redis" or "memory" + */ + readonly type: string; + + /** + * Save AuthRequest data + * + * @param code - Authorization code () + * @param data - AuthRequest data (userId, clientId, redirectUrl, codeChallenge) + */ + saveOAuthRequest(code: string, data: OAuthRequestData): Promise; + + /** + * Get and consume AuthRequest data + * + * @param code - authorization code + * @returns AuthRequset data or null if not found/expired + */ + getOAuthRequest(code: string): Promise; +} diff --git a/src/oauth/store/memory.store.ts b/src/oauth/store/memory.store.ts new file mode 100644 index 00000000..7852aa15 --- /dev/null +++ b/src/oauth/store/memory.store.ts @@ -0,0 +1,107 @@ +import type { OAuthRequestData, MemoryAuthRequestData } from './types'; +import type { OAuthRequestStoreInterface } from './OAuthRequestStoreInterface'; + +/** + * In-memory store for OAuthRequest data + * + * Stores temporary data needed for OAuth authentication flow: + * - AuthRequest maps authorization code to AuthRequest data + * + * Note: This implementation is not suitable for multi-instance deployments. + * Use Redis store for production environments with multiple API instances. + */ +export class MemoryOAuthRequestStore implements OAuthRequestStoreInterface { + /** + * Store type identifier + */ + public readonly type = 'memory'; + + private AuthState: Map = new Map(); + + /** + * Time-to-live for stored data (5 minutes) + */ + private readonly TTL = 5 * 60 * 1000; + + /** + * Interval for cleanup of expired entries (1 minute) + */ + private readonly CLEANUP_INTERVAL = 60 * 1000; + + /** + * Cleanup timer reference + */ + private cleanupTimer: NodeJS.Timeout | null = null; + + /** + * Store constructor + */ + constructor() { + this.startCleanupTimer(); + } + + /** + * Save AuthRequest data + * + * @param code - Authorization code () + * @param data - AuthRequest data (userId, clientId, redirectUrl, codeChallenge) + */ + public async saveOAuthRequest(code: string, data: MemoryAuthRequestData): Promise { + this.AuthState.set(code, + { + ...data, + expiresAt: Date.now() + this.TTL, + } + ); + } + + /** + * Get AuthRequest data + * + * @param code - authorizaton code + * @returns authRequest data or null if not found/expired + */ + public async getOAuthRequest(code: string): Promise { + const data = this.AuthState.get(code); + + if (!data) { + return null; + } + + if (Date.now() > data.expiresAt) { + this.AuthState.delete(code); + + return null; + } + + this.AuthState.delete(code); + + const { expiresAt, ...authRequestData } = data; + + return authRequestData; + } + + /** + * Start periodic cleanup of expired entries + */ + private startCleanupTimer(): void { + this.cleanupTimer = setInterval(() => { + this.cleanup(); + }, this.CLEANUP_INTERVAL); + + this.cleanupTimer.unref(); + } + + /** + * Clean up expired entries + */ + private cleanup(): void { + const now = Date.now(); + + for (const [key, value] of this.AuthState) { + if (now > value.expiresAt) { + this.AuthState.delete(key); + } + } + } +} diff --git a/src/oauth/store/redis.store.ts b/src/oauth/store/redis.store.ts new file mode 100644 index 00000000..02d2e4b9 --- /dev/null +++ b/src/oauth/store/redis.store.ts @@ -0,0 +1,114 @@ +import RedisHelper from '../../redisHelper'; + +import type { OAuthRequestStoreInterface } from './OAuthRequestStoreInterface'; +import type { OAuthRequestData } from './types'; +import type { RedisClientType } from 'redis'; + +/** + * Redis-based store for OAuthRequest data + * + * Stores temporary data needed for OAuth flow: + * - AuthRequest maps authorization code to AuthRequest data + * + * This implementation is suitable for multi-instance deployments as it uses + * Redis as the shared state store. TTLs are handled by Redis automatically. + */ +export class RedisOAuthRequestStore implements OAuthRequestStoreInterface { + /** + * Store type identifier + */ + public readonly type = 'redis'; + + /** + * Redis helper instance + */ + private redisHelper: RedisHelper; + + /** + * Time-to-live for stored data in seconds (5 minutes) + */ + private readonly TTL_SECONDS = 5 * 60; + + /** + * Prefix for AuthRequest keys in Redis + */ + private readonly OAUTH_REQUEST_PREFIX = 'oauth'; + + constructor(redisHelper?: RedisHelper) { + this.redisHelper = redisHelper || RedisHelper.getInstance(); + } + + /** + * Save AuthRequest data + * + * @param code - authorization code + * @param data - AuthRequest data (userId, clientId, redirectUrl, codeChallenge) + */ + public async saveOAuthRequest(code: string, data: OAuthRequestData): Promise { + const client = this.getClient(); + const key = `${this.OAUTH_REQUEST_PREFIX}:${code}`; + const value = JSON.stringify(data); + + await client.setEx(key, this.TTL_SECONDS, value); + } + + /** + * Get and consume AuthRequest data + * + * @param code - authorization code + * @returns AuthRequset data or null if not found/expired + */ + public async getOAuthRequest(code: string): Promise { + const client = this.getClient(); + const key = `${this.OAUTH_REQUEST_PREFIX}:${code}`; + + /** + * Get and delete atomically to prevent race conditions + * This ensures the state can only be consumed once + * Using MULTI/EXEC for atomic operation (compatible with Redis 5.0+) + */ + const result = await client + .multi() + .get(key) + .del(key) + .exec(); + + if (!result || result.length < 2) { + return null; + } + + const value = result[0] as string | null; + + if (!value) { + return null; + } + + try { + return JSON.parse(value) as OAuthRequestData; + } catch (error) { + console.error('[OAuth Store] Failed to parse AuthCode', error); + + return null; + } + } + + /** + * Get Redis client + * + * @returns Redis client instance + * @throws Error if Redis client is not available + */ + private getClient(): RedisClientType { + const client = this.redisHelper.getClient(); + + if (!client) { + throw new Error('Redis client is not available. Make sure Redis is initialized.'); + } + + if (!client.isOpen) { + throw new Error('Redis client is not connected. Make sure Redis connection is established.'); + } + + return client; + } +} diff --git a/src/oauth/store/storeFactory.ts b/src/oauth/store/storeFactory.ts new file mode 100644 index 00000000..8070d6fc --- /dev/null +++ b/src/oauth/store/storeFactory.ts @@ -0,0 +1,50 @@ +import RedisHelper from '../../redisHelper'; +import { MemoryOAuthRequestStore } from './memory.store'; +import { RedisOAuthRequestStore } from './redis.store'; + +import type { OAuthRequestStoreInterface } from './OAuthRequestStoreInterface'; + +/** + * Create OAuthRequest data store instance based on configuration + * + * Store type is determined by OAUTH_REQUEST_STORE_TYPE environment variable: + * - 'redis' (default): Uses Redis store for multi-instance support + * - 'memory': Uses in-memory store (single instance only) + * + * @returns OAuthRequest data store instance + */ +export function createOAuthStore(): OAuthRequestStoreInterface { + const storeType = (process.env.OAUTH_REQUEST_STORE_TYPE || 'redis').toLowerCase(); + + if (storeType === 'memory') { + return new MemoryOAuthRequestStore(); + } + + if (storeType === 'redis') { + const redisHelper = RedisHelper.getInstance(); + + if (!redisHelper.isConnected()) { + console.warn( + '[OAuth Store] Redis store requested but Redis is not connected. Falling back to memory store.' + ); + + return new MemoryOAuthRequestStore(); + } + + return new RedisOAuthRequestStore(redisHelper); + } + + /** + * Unknown store type, default to Redis + */ + console.warn( + `[OAuth Store] Unknown store type "${storeType}". Defaulting to Redis.` + ); + const redisHelper = RedisHelper.getInstance(); + + if (redisHelper.isConnected()) { + return new RedisOAuthRequestStore(); + } + + return new MemoryOAuthRequestStore(); +} diff --git a/src/oauth/store/types.ts b/src/oauth/store/types.ts new file mode 100644 index 00000000..b8ccd1a1 --- /dev/null +++ b/src/oauth/store/types.ts @@ -0,0 +1,20 @@ +import type { MemoryOAuthRequestStore } from './memory.store'; + +/** + * Authorization data needed to verify that the original authorization request + * was made by the same client making token request + */ +export type OAuthRequestData = { + userId: string; + clientId: string; + redirectUri: string; + codeChallenge: string; +}; + +/** + * Used by {@link MemoryOAuthRequestStore} + * to track AuthRequest expiration + */ +export type MemoryAuthRequestData = OAuthRequestData & { + expiresAt: number; +} diff --git a/src/oauth/types.ts b/src/oauth/types.ts new file mode 100644 index 00000000..167f4b83 --- /dev/null +++ b/src/oauth/types.ts @@ -0,0 +1,62 @@ + +/* eslint-disable @typescript-eslint/camelcase, camelcase */ + +import { UserJWTData } from "src/types/graphql"; + +/** + * Parameters for {@link https://datatracker.ietf.org/doc/html/rfc9728#name-protected-resource-metadata-r | Protected Resource Metadata Response} + */ +export type ProtectedResourceMetadataResponse = { + resource: string; + authorization_servers: string[]; + scopes_supported: string[]; + resource_documentation?: string; +}; + +/** + * Parameters for {@link https://datatracker.ietf.org/doc/html/rfc8414 | Server Metadata Response} + */ +export type AuthorizationServerMetadataResponse = { + issuer: string; + authorization_endpoint: string; + token_endpoint: string; + registration_endpoint: string; + response_types_supported: string[]; + grant_types_supported: string[]; + token_endpoint_auth_methods_supported: string[]; + code_challenge_methods_supported: string[]; +}; + +/** + * Parameters for {@link https://www.rfc-editor.org/info/rfc7591/#section-3.2.1 | Client Information Response} + */ +export type ClientInformationResponse = { + client_id: string; + client_name: string; + redirect_uris: string[]; + grant_types: string[]; + response_types: string[]; +}; + +/** + * Additional data encoded into tokens issued for OAuth + */ +export type OAuthJWTData = UserJWTData & { + /** + * Client identifier + */ + clientId: string; + + /** Granted MCP scopes */ + scopes?: string[]; + + /** + * Expiration time (Unix timestamp in seconds) + */ + exp: number; + + /** + * Unique JSON Web Token Identifier + */ + jti?: string; +}; diff --git a/src/types/env.d.ts b/src/types/env.d.ts index 0308f58e..b027762b 100644 --- a/src/types/env.d.ts +++ b/src/types/env.d.ts @@ -61,6 +61,15 @@ declare namespace NodeJS { */ SAML_STORE_TYPE?: string; + /** + * OAuthRequest data store + * + * Determines which store implementation to use for OAuthRequest data: + * - 'redis' (default): Uses Redis store for multi-instance support + * - 'memory': Uses in-memory store (single instance only) + */ + OAUTH_REQUEST_STORE_TYPE?: string; + /** * Redis connection URL * Used for caching and TimeSeries data diff --git a/src/types/graphql.ts b/src/types/graphql.ts index d5f7a615..911f39bc 100644 --- a/src/types/graphql.ts +++ b/src/types/graphql.ts @@ -6,6 +6,7 @@ import ProjectsFactory from '../models/projectsFactory'; import PlansFactory from '../models/plansFactory'; import BusinessOperationsFactory from '../models/businessOperationsFactory'; import ReleasesFactory from '../models/releasesFactory'; +import OAuthFactory from '../models/oauthClientsFactory'; /** * Resolver's Context argument @@ -99,6 +100,11 @@ export interface ContextFactories { * Releases factory for working with releases */ releasesFactory: ReleasesFactory; + + /** + * OAuth factory for working with oauth clients + */ + oauthFactory: OAuthFactory; } /** diff --git a/src/utils/verifyJWT.ts b/src/utils/verifyJWT.ts new file mode 100644 index 00000000..d0ac3dce --- /dev/null +++ b/src/utils/verifyJWT.ts @@ -0,0 +1,23 @@ +import jwt from 'jsonwebtoken'; + +import type { Secret } from 'jsonwebtoken'; +import type { UserJWTData } from '../types/graphql'; + +/** + * Verifes given JWT token. + * Decodes JWT and extracts UserJWTData + * + * @param token JWT + * @param tokenType type of token to verify + * @returns UserJWTData or null if JWT can not be verified + */ +export function verifyJWT(token: string, tokenSecret: Secret): T | null { + try { + return jwt.verify( + token, + tokenSecret + ) as T; + } catch { + return null; + } +}; diff --git a/test/oauth/oauth.test.ts b/test/oauth/oauth.test.ts new file mode 100644 index 00000000..2a0ec5cc --- /dev/null +++ b/test/oauth/oauth.test.ts @@ -0,0 +1,212 @@ +import '../../src/env-test'; +import express from 'express'; +import jwt from 'jsonwebtoken'; +import type { JwtPayload } from 'jsonwebtoken'; +import { createHash } from 'node:crypto'; +import { OAuthErrorCode, OAuthGrantType } from '@hawk.so/types'; +import { appendOAuthRoutes } from '../../src/oauth'; +import { makeExpressRequest } from '../helpers/expressRequest'; + +describe('OAuth routes', () => { + const userId = '507f1f77bcf86cd799439011'; + const clientId = 'test-client'; + const redirectUri = 'http://localhost:4567/callback?existing=value'; + const codeVerifier = 'a sufficiently long test verifier'; + const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url'); + const accessSecret = 'oauth-test-access-secret'; + const refreshSecret = 'oauth-test-refresh-secret'; + + let app: express.Application; + let requestBody: Record; + let createOAuthClient: jest.Mock; + let findGrant: jest.Mock; + let rotateRefreshJti: jest.Mock; + let revoke: jest.Mock; + let grant: any; + + function createSignedTokens(refreshJti = 'oauth-refresh-jti') { + return { + accessToken: jwt.sign({ + user_id: userId, + client_id: clientId, + scopes: ['mcp:tools', 'mcp:resources'], + }, accessSecret, { + expiresIn: '15m', + }), + refreshToken: jwt.sign({ + user_id: userId, + client_id: clientId, + scopes: ['mcp:tools', 'mcp:resources'], + }, refreshSecret, { + expiresIn: '30d', + jwtid: refreshJti, + }), + }; + } + + beforeEach(() => { + process.env.JWT_OAUTH_SECRET_ACCESS_TOKEN = accessSecret; + process.env.JWT_OAUTH_SECRET_REFRESH_TOKEN = refreshSecret; + process.env.OAUTH_REQUEST_STORE_TYPE = 'memory'; + requestBody = {}; + + grant = { + userId, + clientId, + revokedAt: null, + jti: 'oauth-refresh-jti', + scopes: ['mcp:tools', 'mcp:resources'], + generateTokensPair: jest.fn((refreshJti?: string) => + Promise.resolve(createSignedTokens(refreshJti || grant.jti))), + }; + createOAuthClient = jest.fn().mockResolvedValue(undefined); + findGrant = jest.fn().mockResolvedValue(grant); + rotateRefreshJti = jest.fn().mockResolvedValue(true); + revoke = jest.fn().mockResolvedValue(true); + const factories = { + oauthFactory: { + create: createOAuthClient, + findGrant, + rotateRefreshJti, + revoke, + }, + } as any; + + app = express(); + app.use((req, _res, next) => { + req.body = requestBody; + req.context = { + user: { id: userId, accessTokenExpired: false }, + factories, + } as any; + next(); + }); + appendOAuthRoutes(app, factories); + }); + + async function post(path: string, body: Record) { + requestBody = body; + + return makeExpressRequest(app, 'POST', path); + } + + it.each([ + 'javascript://localhost', + 'ftp://127.0.0.1/callback', + 'ftp://[::1]/callback', + ])('rejects a non-HTTP loopback redirect URI: %s', async (invalidRedirectUri) => { + const response = await post('/authorize/oauth', { + client_id: clientId, + redirect_uri: invalidRedirectUri, + code_challenge: codeChallenge, + code_challenge_method: 'S256', + }); + + expect(response.status).toBe(400); + expect(response.body).toEqual({ error: OAuthErrorCode.invalidRequest }); + }); + + it('authorizes a loopback redirect and exchanges its code using PKCE', async () => { + const authorization = await post('/authorize/oauth', { + client_id: clientId, + redirect_uri: redirectUri, + state: 'state value', + code_challenge: codeChallenge, + code_challenge_method: 'S256', + }); + + expect(authorization.status).toBe(200); + const callback = new URL(authorization.body.redirect_uri); + expect(callback.origin + callback.pathname).toBe('http://localhost:4567/callback'); + expect(callback.searchParams.get('existing')).toBe('value'); + expect(callback.searchParams.get('state')).toBe('state value'); + + const tokenResponse = await post('/token/oauth', { + grant_type: OAuthGrantType.authorizationCode, + code: callback.searchParams.get('code'), + code_verifier: codeVerifier, + client_id: clientId, + redirect_uri: redirectUri, + }); + + expect(tokenResponse.status).toBe(200); + expect(tokenResponse.body).toMatchObject({ token_type: 'Bearer', scope: 'mcp:tools mcp:resources' }); + expect(tokenResponse.body.access_token).toEqual(expect.any(String)); + expect(tokenResponse.body.refresh_token).toEqual(expect.any(String)); + expect(createOAuthClient).toHaveBeenCalledWith(userId, clientId, 'localhost:4567'); + expect(findGrant).toHaveBeenCalledWith(userId, clientId); + }); + + it('rotates the refresh token for the user and client grant', async () => { + const authorization = await post('/authorize/oauth', { + client_id: clientId, + redirect_uri: redirectUri, + code_challenge: codeChallenge, + code_challenge_method: 'S256', + }); + const callback = new URL(authorization.body.redirect_uri); + const tokenResponse = await post('/token/oauth', { + grant_type: OAuthGrantType.authorizationCode, + code: callback.searchParams.get('code'), + code_verifier: codeVerifier, + client_id: clientId, + redirect_uri: redirectUri, + }); + const currentRefreshToken = tokenResponse.body.refresh_token; + const currentRefreshData = jwt.verify(currentRefreshToken, refreshSecret) as JwtPayload; + + const refreshed = await post('/token/oauth', { + grant_type: OAuthGrantType.refreshToken, + refresh_token: currentRefreshToken, + client_id: clientId, + }); + + expect(refreshed.status).toBe(200); + expect(refreshed.body.access_token).toEqual(expect.any(String)); + expect(refreshed.body.refresh_token).toEqual(expect.any(String)); + const rotatedRefreshData = jwt.verify(refreshed.body.refresh_token, refreshSecret) as JwtPayload; + + expect(rotatedRefreshData.jti).not.toBe(currentRefreshData.jti); + expect(rotateRefreshJti).toHaveBeenCalledWith( + userId, + clientId, + currentRefreshData.jti, + rotatedRefreshData.jti + ); + }); + + it('rejects a refresh token used with a different client ID', async () => { + const refreshToken = createSignedTokens().refreshToken; + const response = await post('/token/oauth', { + grant_type: OAuthGrantType.refreshToken, + refresh_token: refreshToken, + client_id: 'another-client', + }); + + expect(response.status).toBe(400); + expect(response.body).toEqual({ error: OAuthErrorCode.invalidGrant }); + expect(findGrant).not.toHaveBeenCalled(); + }); + + it('rejects an authorization code exchange with a mismatched redirect URI', async () => { + const authorization = await post('/authorize/oauth', { + client_id: clientId, + redirect_uri: redirectUri, + code_challenge: codeChallenge, + code_challenge_method: 'S256', + }); + const code = new URL(authorization.body.redirect_uri).searchParams.get('code'); + + const response = await post('/token/oauth', { + grant_type: OAuthGrantType.authorizationCode, + code, + code_verifier: codeVerifier, + client_id: clientId, + redirect_uri: 'http://localhost:4567/other-callback', + }); + + expect(response.status).toBe(400); + expect(response.body).toEqual({ error: OAuthErrorCode.invalidGrant }); + expect(createOAuthClient).not.toHaveBeenCalled(); + }); +}); diff --git a/yarn.lock b/yarn.lock index 1caa5422..a8accdaf 100644 --- a/yarn.lock +++ b/yarn.lock @@ -531,10 +531,10 @@ dependencies: bson "^7.0.0" -"@hono/node-server@^1.19.9": - version "1.19.17" - resolved "https://registry.yarnpkg.com/@hono/node-server/-/node-server-1.19.17.tgz#99bd8625cdbae82652a135c71363cd6322fae483" - integrity sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ== +"@hono/node-server@^1.19.9 || ^2.1.3": + version "2.1.5" + resolved "https://registry.yarnpkg.com/@hono/node-server/-/node-server-2.1.5.tgz#273db93e8bfb44ef361e55f3d00048013668aa09" + integrity sha512-MgP/I06GdvsilDspMk/qmRzpk8LOUStP6jFAbSRi40W09DhoyUn+Mj7eyKICPqeYKybOjVFLVIAQzvu1bfIa7Q== "@isaacs/cliui@^8.0.2": version "8.0.2" @@ -874,26 +874,34 @@ "@jridgewell/resolve-uri" "^3.1.0" "@jridgewell/sourcemap-codec" "^1.4.14" -"@modelcontextprotocol/core@2.0.0": - version "2.0.0" - resolved "https://registry.yarnpkg.com/@modelcontextprotocol/core/-/core-2.0.0.tgz#c918a4c6aef22a7c59dfb0aabc2a82c187cce157" - integrity sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA== +"@modelcontextprotocol/core@2.4.0": + version "2.4.0" + resolved "https://registry.yarnpkg.com/@modelcontextprotocol/core/-/core-2.4.0.tgz#c7f1a505452c3a0ad666d9a6e78a5804d8d8d0d9" + integrity sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q== dependencies: zod "^4.2.0" -"@modelcontextprotocol/node@^2.0.0": - version "2.0.0" - resolved "https://registry.yarnpkg.com/@modelcontextprotocol/node/-/node-2.0.0.tgz#3851275cb1c08aeb113d5b7cbe6dbe7adab37c65" - integrity sha512-Y4hAC2XdGDUdDOCbLDOCA4+aL3NUldjsOWlDL/YwpAxrPhRm1xHd7lZ+mLacvZ9t3PaH28wgNoaLQGrIk1P2pg== +"@modelcontextprotocol/express@^2.0.2": + version "2.0.2" + resolved "https://registry.yarnpkg.com/@modelcontextprotocol/express/-/express-2.0.2.tgz#4d2464f8bd588c98071d5ba477ab49425dc4a2ed" + integrity sha512-lUvfV7gT/tgP8nLRs0ajUtgL+MlMNWWHAls5c9cf4PyBexq3EgmhWWrS4irQOC9OoKuUsHHcNjUw9urhHz542g== dependencies: - "@hono/node-server" "^1.19.9" + cors "^2.8.5" -"@modelcontextprotocol/server@^2.0.0": - version "2.0.0" - resolved "https://registry.yarnpkg.com/@modelcontextprotocol/server/-/server-2.0.0.tgz#4fae5ccb8f7925ed9a6bf6595bb3b58617063ffd" - integrity sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw== +"@modelcontextprotocol/node@^2.1.2": + version "2.1.2" + resolved "https://registry.yarnpkg.com/@modelcontextprotocol/node/-/node-2.1.2.tgz#fc90e849adbc14d15bb3a50c1b01732012bf1a68" + integrity sha512-IIcIqBpr6NCQQs5DgJTgvbSOAw+3iaR/uquqg+e0nXCdudfjPg/80x0TseUnQx14AUAtE4fsJCEpJKPyb6WPVA== dependencies: - "@modelcontextprotocol/core" "2.0.0" + "@hono/node-server" "^1.19.9 || ^2.1.3" + hono "^4.11.4" + +"@modelcontextprotocol/server@^2.4.0": + version "2.4.0" + resolved "https://registry.yarnpkg.com/@modelcontextprotocol/server/-/server-2.4.0.tgz#282a61ccbdc531361f03525a33e33283534d6fc7" + integrity sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q== + dependencies: + "@modelcontextprotocol/core" "2.4.0" zod "^4.2.0" "@mongodb-js/saslprep@^1.3.0": @@ -3990,6 +3998,11 @@ hasown@^2.0.2: dependencies: function-bind "^1.1.2" +hono@^4.11.4: + version "4.13.13" + resolved "https://registry.yarnpkg.com/hono/-/hono-4.13.13.tgz#8dd5459ce4aa44b3e297f0b350f86b0f6d4a79f0" + integrity sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA== + hosted-git-info@^2.1.4: version "2.8.9" resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9"