|
| 1 | +import * as fs from 'fs'; |
| 2 | +import * as path from 'path'; |
| 3 | +import * as os from 'os'; |
| 4 | + |
| 5 | +/** |
| 6 | + * OAuth configuration |
| 7 | + */ |
| 8 | +const OAUTH_CONFIG = { |
| 9 | + // Remote MCP server OAuth endpoint |
| 10 | + authorizeUrl: process.env.VAPI_OAUTH_URL || 'https://mcp.vapi.ai/authorize', |
| 11 | + tokenInfoUrl: process.env.VAPI_TOKEN_INFO_URL || 'https://mcp.vapi.ai/oauth/token-info', |
| 12 | + pollInterval: 5000, // 5 seconds |
| 13 | + pollTimeout: 120000, // 2 minutes |
| 14 | +}; |
| 15 | + |
| 16 | +/** |
| 17 | + * OAuth token storage location |
| 18 | + */ |
| 19 | +const CONFIG_DIR = path.join(os.homedir(), '.vapi'); |
| 20 | +const CONFIG_FILE = path.join(CONFIG_DIR, 'mcp-config.json'); |
| 21 | + |
| 22 | +/** |
| 23 | + * Interface for stored OAuth credentials |
| 24 | + */ |
| 25 | +interface OAuthCredentials { |
| 26 | + apiKey: string; |
| 27 | + orgId: string; |
| 28 | + userId: string; |
| 29 | + email: string; |
| 30 | + timestamp: number; |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + * Check if OAuth credentials are stored |
| 35 | + */ |
| 36 | +export function hasStoredCredentials(): boolean { |
| 37 | + try { |
| 38 | + return fs.existsSync(CONFIG_FILE); |
| 39 | + } catch (error) { |
| 40 | + return false; |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * Load stored OAuth credentials |
| 46 | + */ |
| 47 | +export function loadStoredCredentials(): OAuthCredentials | null { |
| 48 | + try { |
| 49 | + if (!fs.existsSync(CONFIG_FILE)) { |
| 50 | + return null; |
| 51 | + } |
| 52 | + |
| 53 | + const data = fs.readFileSync(CONFIG_FILE, 'utf8'); |
| 54 | + return JSON.parse(data); |
| 55 | + } catch (error) { |
| 56 | + console.error('Failed to load OAuth credentials:', error); |
| 57 | + return null; |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +/** |
| 62 | + * Save OAuth credentials to disk |
| 63 | + */ |
| 64 | +export function saveCredentials(credentials: OAuthCredentials): void { |
| 65 | + try { |
| 66 | + // Create config directory if it doesn't exist |
| 67 | + if (!fs.existsSync(CONFIG_DIR)) { |
| 68 | + fs.mkdirSync(CONFIG_DIR, { recursive: true }); |
| 69 | + } |
| 70 | + |
| 71 | + fs.writeFileSync(CONFIG_FILE, JSON.stringify(credentials, null, 2), 'utf8'); |
| 72 | + } catch (error) { |
| 73 | + console.error('Failed to save OAuth credentials:', error); |
| 74 | + throw error; |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +/** |
| 79 | + * Generate OAuth authorization URL |
| 80 | + */ |
| 81 | +export function generateOAuthUrl(): string { |
| 82 | + const params = new URLSearchParams({ |
| 83 | + response_type: 'code', |
| 84 | + client_id: 'vapi-mcp-client', |
| 85 | + redirect_uri: 'http://localhost:3000/callback', // Will be handled by remote server |
| 86 | + scope: 'read_profile read_data write_data', |
| 87 | + }); |
| 88 | + |
| 89 | + return `${OAUTH_CONFIG.authorizeUrl}?${params.toString()}`; |
| 90 | +} |
| 91 | + |
| 92 | +/** |
| 93 | + * Poll for OAuth completion and retrieve API key |
| 94 | + * |
| 95 | + * This function is called after the user completes OAuth in their browser. |
| 96 | + * It polls the token-info endpoint to check if the OAuth flow is complete. |
| 97 | + * |
| 98 | + * @param accessToken - OAuth access token from the authorization flow |
| 99 | + * @returns OAuth credentials including API key |
| 100 | + */ |
| 101 | +export async function pollForOAuthCompletion(accessToken: string): Promise<OAuthCredentials> { |
| 102 | + const startTime = Date.now(); |
| 103 | + |
| 104 | + while (Date.now() - startTime < OAUTH_CONFIG.pollTimeout) { |
| 105 | + try { |
| 106 | + const response = await fetch(OAUTH_CONFIG.tokenInfoUrl, { |
| 107 | + headers: { |
| 108 | + Authorization: `Bearer ${accessToken}`, |
| 109 | + }, |
| 110 | + }); |
| 111 | + |
| 112 | + if (response.ok) { |
| 113 | + const data = await response.json(); |
| 114 | + |
| 115 | + if (data.apiKey) { |
| 116 | + const credentials: OAuthCredentials = { |
| 117 | + apiKey: data.apiKey, |
| 118 | + orgId: data.orgId, |
| 119 | + userId: data.userId, |
| 120 | + email: data.email, |
| 121 | + timestamp: Date.now(), |
| 122 | + }; |
| 123 | + |
| 124 | + // Save credentials |
| 125 | + saveCredentials(credentials); |
| 126 | + |
| 127 | + return credentials; |
| 128 | + } |
| 129 | + } |
| 130 | + } catch (error) { |
| 131 | + // Continue polling on error |
| 132 | + } |
| 133 | + |
| 134 | + // Wait before next poll |
| 135 | + await new Promise(resolve => setTimeout(resolve, OAUTH_CONFIG.pollInterval)); |
| 136 | + } |
| 137 | + |
| 138 | + throw new Error('OAuth flow timed out. Please try again.'); |
| 139 | +} |
| 140 | + |
| 141 | +/** |
| 142 | + * Trigger OAuth flow |
| 143 | + * |
| 144 | + * This function is called when a tool is invoked without authentication. |
| 145 | + * It throws an error with the OAuth URL, which Claude Desktop will display to the user. |
| 146 | + */ |
| 147 | +export function triggerOAuthFlow(): never { |
| 148 | + const oauthUrl = generateOAuthUrl(); |
| 149 | + |
| 150 | + throw new Error( |
| 151 | + `Authentication required. Please complete OAuth authorization:\n\n${oauthUrl}\n\n` + |
| 152 | + 'After completing authorization, retry your request.' |
| 153 | + ); |
| 154 | +} |
| 155 | + |
| 156 | +/** |
| 157 | + * Get API key from stored credentials or trigger OAuth |
| 158 | + */ |
| 159 | +export function getApiKeyOrTriggerOAuth(): string { |
| 160 | + const credentials = loadStoredCredentials(); |
| 161 | + |
| 162 | + if (credentials && credentials.apiKey) { |
| 163 | + return credentials.apiKey; |
| 164 | + } |
| 165 | + |
| 166 | + // No credentials found - trigger OAuth flow |
| 167 | + triggerOAuthFlow(); |
| 168 | +} |
0 commit comments