|
| 1 | +import http from 'http'; |
| 2 | +import crypto from 'crypto'; |
| 3 | +import { execSync } from 'child_process'; |
| 4 | + |
| 5 | +const APOLLO_BASE = 'https://api.apollo.io'; |
| 6 | +const APOLLO_MCP_BASE = 'https://mcp.apollo.io'; |
| 7 | +const REDIRECT_PORT = 3421; |
| 8 | +const REDIRECT_URI = `http://localhost:${REDIRECT_PORT}/callback`; |
| 9 | +const SCOPES = 'people_bulk_match organizations_bulk_enrich organizations_enrich people_match mixed_people_search mixed_people_api_search mixed_companies_search contact_write contact_update contacts_search contact_read account_write account_update emailer_campaigns_search emailer_campaigns_add_contact_ids emailer_campaigns_remove_or_stop_contact_ids email_accounts_list read_user_profile'; |
| 10 | +const TIMEOUT_MS = 5 * 60 * 1000; |
| 11 | + |
| 12 | +function generatePKCE() { |
| 13 | + const verifier = crypto.randomBytes(32).toString('base64url'); |
| 14 | + const challenge = crypto.createHash('sha256').update(verifier).digest('base64url'); |
| 15 | + return { verifier, challenge }; |
| 16 | +} |
| 17 | + |
| 18 | +async function registerClient() { |
| 19 | + const res = await fetch(`${APOLLO_MCP_BASE}/api/v1/oauth/applications/register_oauth_client`, { |
| 20 | + method: 'POST', |
| 21 | + headers: { 'Content-Type': 'application/json', 'User-Agent': 'Apollo-MCP/1.0' }, |
| 22 | + body: JSON.stringify({ |
| 23 | + client_name: 'Apollo CLI', |
| 24 | + redirect_uris: [REDIRECT_URI], |
| 25 | + token_endpoint_auth_method: 'none', |
| 26 | + grant_types: ['authorization_code'], |
| 27 | + response_types: ['code'], |
| 28 | + scope: SCOPES, |
| 29 | + }), |
| 30 | + }); |
| 31 | + if (!res.ok) throw new Error(`Client registration failed: ${await res.text()}`); |
| 32 | + const data = await res.json(); |
| 33 | + return data.client_id; |
| 34 | +} |
| 35 | + |
| 36 | +async function exchangeCode(code, clientId, verifier) { |
| 37 | + const res = await fetch(`${APOLLO_MCP_BASE}/api/v1/oauth/token`, { |
| 38 | + method: 'POST', |
| 39 | + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, |
| 40 | + body: new URLSearchParams({ |
| 41 | + grant_type: 'authorization_code', |
| 42 | + code, |
| 43 | + client_id: clientId, |
| 44 | + redirect_uri: REDIRECT_URI, |
| 45 | + code_verifier: verifier, |
| 46 | + }), |
| 47 | + }); |
| 48 | + if (!res.ok) throw new Error(`Token exchange failed: ${await res.text()}`); |
| 49 | + return res.json(); |
| 50 | +} |
| 51 | + |
| 52 | +export async function revokeToken(accessToken, clientId) { |
| 53 | + await fetch(`${APOLLO_MCP_BASE}/api/v1/oauth/revoke`, { |
| 54 | + method: 'POST', |
| 55 | + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, |
| 56 | + body: new URLSearchParams({ token: accessToken, client_id: clientId }), |
| 57 | + }); |
| 58 | +} |
| 59 | + |
| 60 | +function openBrowser(url) { |
| 61 | + if (process.platform === 'darwin') execSync(`open "${url}"`); |
| 62 | + else if (process.platform === 'win32') execSync(`start "" "${url}"`); |
| 63 | + else execSync(`xdg-open "${url}"`); |
| 64 | +} |
| 65 | + |
| 66 | +export async function oauthLogin() { |
| 67 | + const clientId = await registerClient(); |
| 68 | + const { verifier, challenge } = generatePKCE(); |
| 69 | + const state = crypto.randomBytes(16).toString('hex'); |
| 70 | + |
| 71 | + const params = new URLSearchParams({ |
| 72 | + client_id: clientId, |
| 73 | + redirect_uri: REDIRECT_URI, |
| 74 | + response_type: 'code', |
| 75 | + scope: SCOPES, |
| 76 | + code_challenge: challenge, |
| 77 | + code_challenge_method: 'S256', |
| 78 | + state, |
| 79 | + }); |
| 80 | + |
| 81 | + const authUrl = `${APOLLO_MCP_BASE}/mcp/oauth_metadata/redirect_to_authorize?${params}`; |
| 82 | + |
| 83 | + return new Promise((resolve, reject) => { |
| 84 | + let settled = false; |
| 85 | + |
| 86 | + const done = (fn) => { |
| 87 | + if (settled) return; |
| 88 | + settled = true; |
| 89 | + server.close(); |
| 90 | + fn(); |
| 91 | + }; |
| 92 | + |
| 93 | + const server = http.createServer(async (req, res) => { |
| 94 | + const url = new URL(req.url, `http://localhost:${REDIRECT_PORT}`); |
| 95 | + if (url.pathname !== '/callback') return; |
| 96 | + |
| 97 | + const code = url.searchParams.get('code'); |
| 98 | + const returnedState = url.searchParams.get('state'); |
| 99 | + const error = url.searchParams.get('error'); |
| 100 | + |
| 101 | + res.writeHead(200, { 'Content-Type': 'text/html' }); |
| 102 | + res.end('<html><body><h2>Authorization complete. You can close this tab.</h2></body></html>'); |
| 103 | + |
| 104 | + if (error) return done(() => reject(new Error(`Authorization denied: ${error}`))); |
| 105 | + if (returnedState !== state) return done(() => reject(new Error('State mismatch — possible CSRF attack'))); |
| 106 | + if (!code) return done(() => reject(new Error('No authorization code received'))); |
| 107 | + |
| 108 | + try { |
| 109 | + const tokens = await exchangeCode(code, clientId, verifier); |
| 110 | + done(() => resolve({ clientId, ...tokens })); |
| 111 | + } catch (err) { |
| 112 | + done(() => reject(err)); |
| 113 | + } |
| 114 | + }); |
| 115 | + |
| 116 | + server.on('error', (err) => done(() => reject(err))); |
| 117 | + |
| 118 | + server.listen(REDIRECT_PORT, () => { |
| 119 | + console.log('Opening browser for Apollo login...'); |
| 120 | + try { |
| 121 | + openBrowser(authUrl); |
| 122 | + } catch { |
| 123 | + console.log(`\nCould not open browser automatically. Visit:\n${authUrl}\n`); |
| 124 | + } |
| 125 | + console.log('Waiting for authorization...'); |
| 126 | + }); |
| 127 | + |
| 128 | + setTimeout(() => done(() => reject(new Error('Authorization timed out'))), TIMEOUT_MS); |
| 129 | + }); |
| 130 | +} |
0 commit comments