mcp-emre-kalem
Version:
Test amaçlı MCP server - liste arama işlemleri
163 lines (142 loc) • 5.14 kB
JavaScript
import { ConfidentialClientApplication } from '@azure/msal-node';
import express from 'express';
import https from 'https';
import fs from 'fs';
import open from 'open';
import { loadConfig } from './config.js';
// Config yükle
const appConfig = loadConfig();
// Microsoft OAuth yapılandırması
const msalConfig = {
auth: {
clientId: appConfig.microsoft.clientId,
clientSecret: appConfig.microsoft.clientSecret,
authority: 'https://login.microsoftonline.com/organizations' // Single tenant için
}
};
const cca = new ConfidentialClientApplication(msalConfig);
let authenticatedUser = null;
// Authentication başlatma
export async function initializeAuth() {
// Eğer zaten authenticate olduysa geç
if (authenticatedUser) {
console.error(`✅ Zaten giriş yapılmış: ${authenticatedUser.username}`);
return true;
}
console.error('🔐 Microsoft hesabıyla browser girişi başlatılıyor...');
return await startAuthFlow();
}
// Auth flow başlatma
async function startAuthFlow() {
return new Promise((resolve) => {
const app = express();
// SSL sertifikası var mı kontrol et
let useHTTPS = false;
let server;
try {
const httpsOptions = {
key: fs.readFileSync('./localhost-key.pem'),
cert: fs.readFileSync('./localhost-cert.pem')
};
useHTTPS = true;
server = https.createServer(httpsOptions, app).listen(3000, async () => {
const loginUrl = 'https://localhost:3000/login';
console.error('📱 HTTPS server başlatıldı...');
console.error('🔒 SSL sertifikası: Self-signed');
console.error(`🌐 Login URL: ${loginUrl}`);
console.error('⚠️ Azure\'da redirect URI: https://localhost:3000/callback');
// Otomatik browser açma
try {
await open(loginUrl);
console.error('✅ Tarayıcı açıldı!');
console.error('⚠️ Tarayıcıda "Gelişmiş" → "Devam et" tıklayın (self-signed cert)');
} catch (error) {
console.error('❌ Tarayıcı açılamadı, manuel açın:', loginUrl);
}
});
} catch (error) {
console.error('⚠️ SSL sertifikası bulunamadı, HTTP kullanılıyor...');
console.error('🚨 Azure\'da HTTP redirect URI gerekecek: http://localhost:3000/callback');
server = app.listen(3000, async () => {
const loginUrl = 'http://localhost:3000/login';
console.error('📱 HTTP server başlatıldı...');
console.error(`🌐 Login URL: ${loginUrl}`);
// Otomatik browser açma
try {
await open(loginUrl);
console.error('✅ Tarayıcı açıldı!');
} catch (error) {
console.error('❌ Tarayıcı açılamadı, manuel açın:', loginUrl);
}
});
}
// Login endpoint
app.get('/login', async (req, res) => {
const protocol = useHTTPS ? 'https' : 'http';
const authCodeUrlParameters = {
scopes: ['user.read'],
redirectUri: `${protocol}://localhost:3000/callback`,
};
try {
const response = await cca.getAuthCodeUrl(authCodeUrlParameters);
res.redirect(response);
} catch (error) {
res.status(500).send('Auth URL oluşturma hatası: ' + error.message);
}
});
// Callback endpoint
app.get('/callback', async (req, res) => {
const protocol = useHTTPS ? 'https' : 'http';
const tokenRequest = {
code: req.query.code,
scopes: ['user.read'],
redirectUri: `${protocol}://localhost:3000/callback`,
};
try {
const response = await cca.acquireTokenByCode(tokenRequest);
authenticatedUser = {
username: response.account.username,
name: response.account.name,
token: response.accessToken
};
res.send(`
<h2>✅ Giriş Başarılı!</h2>
<p>Hoş geldin, ${authenticatedUser.name}!</p>
<p>Bu pencereyi kapatabilirsin, MCP Server başlatılıyor...</p>
<script>setTimeout(() => window.close(), 2000);</script>
`);
console.error(`✅ Microsoft girişi başarılı: ${authenticatedUser.username}`);
server.close();
resolve(true);
} catch (error) {
res.status(500).send('Token alma hatası: ' + error.message);
console.error('❌ Auth hatası:', error.message);
server.close();
resolve(false);
}
});
// Timeout
setTimeout(() => {
console.error('❌ Auth timeout - 5 dakika içinde giriş yapılmadı');
server.close();
resolve(false);
}, 5 * 60 * 1000); // 5 dakika
});
}
// Kullanıcı kontrolü
export function requireAuth() {
if (!authenticatedUser) {
throw new Error('❌ Microsoft hesabıyla giriş yapmanız gerekiyor');
}
return authenticatedUser;
}
// Auth durumu
export function getAuthStatus() {
return authenticatedUser ? {
authenticated: true,
user: authenticatedUser.username,
name: authenticatedUser.name
} : {
authenticated: false
};
}