Repository navigation
Expand file tree
/
Copy pathapi-proxy.js
More file actions
253 lines (215 loc) · 9.2 KB
/
Copy pathapi-proxy.js
File metadata and controls
253 lines (215 loc) · 9.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#!/usr/bin/env node
const http = require('http')
const fs = require('fs')
const path = require('path')
const PORT = 8001
// Read API keys for both providers
let apiKeys = {}
let primaryProvider = null
try {
const keysPath = path.join(__dirname, 'dist', 'keys')
const keysContent = fs.readFileSync(keysPath, 'utf8')
const lines = keysContent.split('\n')
const keyOrder = []
for (const line of lines) {
const trimmed = line.trim()
if (trimmed && !trimmed.startsWith('#')) {
if (trimmed.includes('=')) {
const [key, value] = trimmed.split('=', 2)
if (key && value) {
const provider = key.trim().toLowerCase()
const apiKey = value.trim()
if ((provider === 'openai' && apiKey.startsWith('sk-')) ||
(provider === 'anthropic' && apiKey.startsWith('sk-ant-'))) {
apiKeys[provider] = apiKey
if (!keyOrder.includes(provider)) keyOrder.push(provider)
}
}
}
}
}
primaryProvider = keyOrder[0]
}
catch (error) {
console.error('❌ Could not read API keys:', error.message)
process.exit(1)
}
if (!primaryProvider || !apiKeys[primaryProvider]) {
console.error('❌ No valid API keys found in dist/keys file')
console.error('💡 Expected format: openai=sk-proj-... or anthropic=sk-ant-api03-...')
process.exit(1)
}
// Provider authentication header configurations
const PROVIDER_AUTH = {
openai: (apiKey) => ({
'Authorization': `Bearer ${apiKey}`
}),
anthropic: (apiKey) => ({
'x-api-key': apiKey,
'anthropic-version': '2023-06-01'
})
}
// Pure proxy handler - only adds auth headers and forwards the path
async function handleProxyRequest(url, requestData, res, method = 'POST') {
// Parse the URL to extract provider and path
// Expected format: /api/<provider>/<path>
const urlParts = url.split('/')
if (urlParts.length < 4 || urlParts[1] !== 'api') {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Invalid API URL format. Expected: /api/<provider>/<path>' }))
return
}
const provider = urlParts[2]
const apiPath = urlParts.slice(3).join('/') // Everything after /api/<provider>/
// Check if provider is supported
if (!PROVIDER_AUTH[provider]) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({
error: `Unsupported provider: ${provider}. Supported providers: ${Object.keys(PROVIDER_AUTH).join(', ')}`
}))
return
}
// Check if we have the API key for this provider
if (!apiKeys[provider]) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({
error: `${provider.toUpperCase()} API key not configured. Available providers: ${Object.keys(apiKeys).join(', ')}`
}))
return
}
// Build target URL: https://api.<provider>.com/<path>
const targetUrl = `https://api.${provider}.com/${apiPath}`
console.log(`🔄 Proxying ${method} request:`)
console.log(` Original URL: ${url}`)
console.log(` Provider: ${provider}`)
console.log(` API Path: ${apiPath}`)
console.log(` Target URL: ${targetUrl}`)
if (requestData && requestData.messages) {
console.log('📝 Prompt length:', requestData.messages[0]?.content?.length || 0)
}
// Build headers: base headers + provider-specific auth headers
const headers = {
'Content-Type': 'application/json',
'User-Agent': 'Catalyst-VM/1.0',
...PROVIDER_AUTH[provider](apiKeys[provider])
}
try {
// Forward request to the target API
console.log(`📤 Making ${method} request to: ${targetUrl}`)
console.log(`📤 Request headers:`, headers)
const fetchOptions = {
method: method,
headers: headers
}
// Only add body for POST requests
if (method === 'POST' && requestData) {
fetchOptions.body = JSON.stringify(requestData)
}
const response = await fetch(targetUrl, fetchOptions)
console.log(`📥 Response status: ${response.status} ${response.statusText}`)
console.log(`📥 Response headers:`, Object.fromEntries(response.headers.entries()))
const data = await response.json()
if (!response.ok) {
console.error(`❌ ${provider.toUpperCase()} API error:`)
console.error(` Status: ${response.status} ${response.statusText}`)
console.error(` Target URL: ${targetUrl}`)
console.error(` Response data:`, data)
res.writeHead(response.status, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(data))
return
}
console.log(`✅ ${provider.toUpperCase()} API response received`)
if (data.usage) {
console.log('📊 Usage:', data.usage)
}
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(data))
} catch (error) {
console.error(`❌ ${provider.toUpperCase()} API request failed:`)
console.error(` Target URL: ${targetUrl}`)
console.error(` Error: ${error.message}`)
console.error(` Stack:`, error.stack)
res.writeHead(500, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: error.message }))
}
}
const server = http.createServer(async (req, res) => {
// Log ALL incoming requests to debug routing issues
console.log(`🌐 Incoming request: ${req.method} ${req.url}`)
console.log(`🌐 Request headers:`, req.headers)
// Enable CORS for all requests
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, x-api-key, anthropic-version')
if (req.method === 'OPTIONS') {
console.log(`✅ Handling OPTIONS request for ${req.url}`)
res.writeHead(200)
res.end()
return
}
// Health check endpoint
if (req.method === 'GET' && req.url === '/health') {
console.log(`✅ Health check requested`)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ status: 'ok', timestamp: new Date().toISOString() }))
return
}
// Handle all API endpoints for both GET and POST
if ((req.method === 'GET' || req.method === 'POST') && req.url.startsWith('/api/')) {
if (req.method === 'GET') {
// Handle GET requests (no body)
try {
await handleProxyRequest(req.url, null, res, req.method)
} catch (error) {
console.error('❌ Proxy error:', error.message)
res.writeHead(500, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: error.message }))
}
} else {
// Handle POST requests (with body)
let body = ''
req.on('data', chunk => {
body += chunk.toString()
})
req.on('end', async () => {
try {
const requestData = body ? JSON.parse(body) : null
await handleProxyRequest(req.url, requestData, res, req.method)
} catch (error) {
console.error('❌ Proxy error:', error.message)
res.writeHead(500, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: error.message }))
}
})
}
}
else {
console.log(`❌ Request not handled: ${req.method} ${req.url}`)
console.log(`❌ Reason: Not a GET/POST request to /api/ endpoint`)
res.writeHead(404)
res.end('Not Found')
}
})
server.listen(PORT, () => {
console.log('🔗 Pure API Proxy Server running!')
console.log(`📍 URL: http://localhost:${PORT}`)
console.log(`🔑 Primary provider: ${primaryProvider.toUpperCase()}`)
console.log(`🔑 Available providers: ${Object.keys(apiKeys).map(p => p.toUpperCase()).join(', ')}`)
console.log(`📡 Pure proxy mapping (GET & POST):`)
console.log(` /api/<provider>/<path> -> https://api.<provider>.com/<path>`)
console.log(`� Examples:`)
console.log(` /api/openai/v1/chat/completions -> https://api.openai.com/v1/chat/completions`)
console.log(` /api/openai/v1/models -> https://api.openai.com/v1/models`)
console.log(` /api/anthropic/v1/messages -> https://api.anthropic.com/v1/messages`)
console.log(` /api/anthropic/v1/models -> https://api.anthropic.com/v1/models`)
console.log('🌐 CORS enabled for all origins')
console.log('🔧 Authentication headers added automatically')
console.log('💡 To switch providers, reorder keys in the "keys" file')
console.log('🛑 Press Ctrl+C to stop')
})
// Graceful shutdown
process.on('SIGINT', () => {
console.log('\n🛑 Shutting down API proxy server...')
server.close()
process.exit(0)
})