UNPKG

onerios-mcp-server

Version:

OneriosMCP server providing memory, backlog management, file operations, and utility functions for enhanced AI assistant capabilities

351 lines (350 loc) 12.8 kB
"use strict"; /** * GitHub Authentication MCP Tool Handlers * * Implements MCP tool functions for GitHub API authentication and token management. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.githubAuthHandlers = exports.githubAuthTools = void 0; exports.handleGitHubAuthenticate = handleGitHubAuthenticate; exports.handleGitHubCheckAuth = handleGitHubCheckAuth; exports.handleGitHubValidateToken = handleGitHubValidateToken; exports.clearGitHubAuth = clearGitHubAuth; exports.getCurrentAuthToken = getCurrentAuthToken; exports.handleListStoredTokens = handleListStoredTokens; exports.handleDeleteStoredToken = handleDeleteStoredToken; const github_integration_js_1 = require("./github-integration.js"); const github_token_manager_js_1 = require("./github-token-manager.js"); // Enhanced authentication state with secure token management let currentAuthToken = null; let currentTokenId = null; /** * Handle GitHub authentication */ async function handleGitHubAuthenticate(args) { try { const { token, validateOnly = false } = args; if (!token || typeof token !== 'string') { throw new Error('GitHub token is required and must be a string'); } // Validate token format first const formatValidation = github_integration_js_1.GitHubTokenValidator.validateTokenFormat(token); if (!formatValidation.valid) { return { success: false, error: 'Invalid token format', issues: formatValidation.issues, tokenType: formatValidation.type }; } // Create client and authenticate const client = new github_integration_js_1.GitHubAPIClient({ token }); try { const user = await client.authenticate(); const permissions = await client.validateProjectPermissions(); // Check if token has required permissions if (!permissions.canReadProjects) { return { success: false, error: 'Token does not have required project permissions', requiredScopes: ['project', 'read:project'], currentScopes: permissions.scopes, user: { login: user.login, name: user.name, type: user.type } }; } const result = { success: true, message: validateOnly ? 'Token validation successful' : 'GitHub authentication successful', user: { login: user.login, name: user.name, email: user.email, type: user.type, avatar_url: user.avatar_url }, permissions: { canReadProjects: permissions.canReadProjects, canWriteProjects: permissions.canWriteProjects, scopes: permissions.scopes }, tokenType: formatValidation.type }; // Store client and token if not validation-only if (!validateOnly) { (0, github_integration_js_1.setGitHubClient)(client); currentAuthToken = token; // Optionally store token securely for development environment if (process.env.MCP_DEV_MODE === 'true') { try { currentTokenId = await github_token_manager_js_1.GitHubTokenSecurityManager.storeToken(token, { type: formatValidation.type, scopes: permissions.scopes, description: `Authentication for ${user.login} (${user.type})` }); console.log(`🔐 Token stored securely in development mode`); } catch (storageError) { console.warn(`⚠️ Failed to store token securely: ${storageError}`); // Continue without secure storage - authentication still works } } // Log successful authentication (without token details) console.log(`GitHub authenticated for user: ${user.login} (${user.type})`); } return result; } catch (authError) { return { success: false, error: authError instanceof Error ? authError.message : 'Authentication failed', tokenType: formatValidation.type }; } } catch (error) { return { success: false, error: error instanceof Error ? error.message : 'Unknown error occurred' }; } } /** * Handle GitHub authentication status check */ async function handleGitHubCheckAuth(args) { try { const client = (0, github_integration_js_1.getGitHubClient)(); if (!client || !client.isAuthenticated()) { return { authenticated: false, message: 'No active GitHub authentication' }; } const user = client.getCurrentUser(); if (!user) { return { authenticated: false, message: 'Authentication session invalid' }; } // Test authentication is still valid with a quick API call try { const permissions = await client.validateProjectPermissions(); return { authenticated: true, user: { login: user.login, name: user.name, email: user.email, type: user.type, avatar_url: user.avatar_url }, permissions: { canReadProjects: permissions.canReadProjects, canWriteProjects: permissions.canWriteProjects, scopes: permissions.scopes }, message: 'GitHub authentication active and valid' }; } catch (testError) { // Authentication may have expired or been revoked (0, github_integration_js_1.setGitHubClient)(null); currentAuthToken = null; return { authenticated: false, error: 'Authentication session expired or revoked', message: 'Please re-authenticate with GitHub' }; } } catch (error) { return { authenticated: false, error: error instanceof Error ? error.message : 'Unknown error occurred' }; } } /** * Handle GitHub token validation */ async function handleGitHubValidateToken(args) { try { const { token } = args; if (!token || typeof token !== 'string') { return { valid: false, error: 'Token is required and must be a string' }; } // Format validation const formatValidation = github_integration_js_1.GitHubTokenValidator.validateTokenFormat(token); if (!formatValidation.valid) { return { valid: false, error: 'Invalid token format', issues: formatValidation.issues, tokenType: formatValidation.type }; } // API validation const apiValidation = await github_integration_js_1.GitHubTokenValidator.validateTokenWithAPI(token); if (!apiValidation.valid) { return { valid: false, error: apiValidation.error, tokenType: formatValidation.type }; } return { valid: true, message: 'Token is valid and authenticated', user: apiValidation.user, permissions: apiValidation.permissions, tokenType: formatValidation.type, recommendations: apiValidation.permissions?.canWriteProjects ? ['Token has full project access - ready for integration'] : ['Token has read-only access - write operations will fail', 'Consider using a token with "project" scope for full functionality'] }; } catch (error) { return { valid: false, error: error instanceof Error ? error.message : 'Validation failed' }; } } /** * Utility function to clear GitHub authentication */ function clearGitHubAuth() { (0, github_integration_js_1.setGitHubClient)(null); currentAuthToken = null; console.log('GitHub authentication cleared'); } /** * Get current authentication token (for internal use) */ function getCurrentAuthToken() { return currentAuthToken; } /** * Enhanced MCP Tool: List stored GitHub tokens (development mode) */ async function handleListStoredTokens() { if (process.env.MCP_DEV_MODE !== 'true') { return { success: false, error: 'Token listing only available in development mode' }; } try { const tokens = await github_token_manager_js_1.GitHubTokenSecurityManager.listTokens(); const audit = await github_token_manager_js_1.GitHubTokenSecurityManager.auditTokenSecurity(); return { success: true, tokens: tokens.map(token => ({ id: token.id, type: token.type, description: token.description, scopes: token.scopes, createdAt: token.createdAt, lastUsed: token.lastUsed, isActive: token.id === currentTokenId })), audit: { totalTokens: audit.totalTokens, expiredTokens: audit.expiredTokens, oldTokens: audit.oldTokens, recommendations: audit.recommendations } }; } catch (error) { return { success: false, error: error instanceof Error ? error.message : 'Failed to list tokens' }; } } /** * Enhanced MCP Tool: Delete stored GitHub token (development mode) */ async function handleDeleteStoredToken(args) { if (process.env.MCP_DEV_MODE !== 'true') { return { success: false, error: 'Token deletion only available in development mode' }; } try { const tokenId = args.tokenId; if (!tokenId || typeof tokenId !== 'string') { return { success: false, error: 'Token ID is required and must be a string' }; } await github_token_manager_js_1.GitHubTokenSecurityManager.deleteToken(tokenId); // Clear current auth if this was the active token if (currentTokenId === tokenId) { clearGitHubAuth(); currentTokenId = null; } return { success: true, message: `Token ${tokenId} deleted successfully` }; } catch (error) { return { success: false, error: error instanceof Error ? error.message : 'Failed to delete token' }; } } // Tool definitions for enhanced token management const listStoredTokensTool = { name: 'github_list_stored_tokens', description: 'List all securely stored GitHub tokens with metadata (development mode only)', inputSchema: { type: 'object', properties: {}, required: [] } }; const deleteStoredTokenTool = { name: 'github_delete_stored_token', description: 'Delete a securely stored GitHub token by ID (development mode only)', inputSchema: { type: 'object', properties: { tokenId: { type: 'string', description: 'The ID of the token to delete' } }, required: ['tokenId'] } }; // Export tool definitions exports.githubAuthTools = [ github_integration_js_1.authenticateGitHub, github_integration_js_1.checkGitHubAuth, github_integration_js_1.validateGitHubToken, ...(process.env.MCP_DEV_MODE === 'true' ? [listStoredTokensTool, deleteStoredTokenTool] : []) ]; // Export handlers map exports.githubAuthHandlers = { github_authenticate: handleGitHubAuthenticate, github_check_auth: handleGitHubCheckAuth, github_validate_token: handleGitHubValidateToken, ...(process.env.MCP_DEV_MODE === 'true' ? { github_list_stored_tokens: handleListStoredTokens, github_delete_stored_token: handleDeleteStoredToken } : {}) };