-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver-proxy.js
More file actions
215 lines (189 loc) · 6.79 KB
/
server-proxy.js
File metadata and controls
215 lines (189 loc) · 6.79 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
const express = require('express');
const cors = require('cors');
const { createProxyMiddleware } = require('http-proxy-middleware');
const fs = require('fs');
const https = require('https');
class TokenManager {
constructor(configPath = './config.json') {
this.configPath = configPath;
this.config = this.loadConfig();
this.copilotToken = null;
this.tokenExpiry = null;
}
loadConfig() {
try {
const configData = fs.readFileSync(this.configPath, 'utf8');
return JSON.parse(configData);
} catch (error) {
console.error('Error loading config:', error.message);
process.exit(1);
}
}
async refreshCopilotToken() {
console.log('🔄 Refreshing Copilot token...');
return new Promise((resolve, reject) => {
const options = {
hostname: 'api.github.com',
port: 443,
path: '/copilot_internal/v2/token',
method: 'GET',
headers: {
'authorization': `token ${this.config.access_token}`,
'user-agent': 'GithubCopilot/1.155.0'
}
};
const req = https.request(options, (res) => {
let body = '';
res.on('data', chunk => body += chunk);
res.on('end', () => {
try {
if (res.statusCode === 200) {
const response = JSON.parse(body);
this.copilotToken = response.token;
this.tokenExpiry = (response.expires_at * 1000) - (60 * 1000);
console.log('✅ Copilot token refreshed successfully');
console.log(`🕐 Token expires at: ${new Date(this.tokenExpiry).toISOString()}`);
resolve(true);
} else {
console.error('❌ Error refreshing token:', body);
resolve(false);
}
} catch (error) {
console.error('❌ Parse error:', error.message);
resolve(false);
}
});
});
req.on('error', (error) => {
console.error('❌ Network error refreshing token:', error.message);
resolve(false);
});
req.end();
});
}
async getValidToken() {
if (!this.copilotToken || !this.tokenExpiry || Date.now() > this.tokenExpiry) {
const success = await this.refreshCopilotToken();
if (!success) {
throw new Error('Failed to obtain valid Copilot token');
}
}
return this.copilotToken;
}
}
// Create Express app
const app = express();
const port = process.env.PORT || 3000;
// Create token manager
const tokenManager = new TokenManager();
// Enable CORS
app.use(cors());
// Logging middleware
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
next();
});
// Health endpoint
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
service: 'copilot-api-proxy'
});
});
// Root endpoint with API information
app.get('/', (req, res) => {
res.json({
service: 'GitHub Copilot to OpenAI API Proxy (Ultra-Fast)',
version: '2.0.0',
endpoints: {
health: 'GET /health',
models: 'GET /v1/models',
chat_completions: 'POST /v1/chat/completions'
},
documentation: 'https://platform.openai.com/docs/api-reference',
note: 'This service provides transparent proxy to GitHub Copilot with automatic token injection'
});
});
// Ultra-fast proxy for all /v1/* endpoints
app.use('/v1', async (req, res, next) => {
try {
// Get token before creating proxy
const token = await tokenManager.getValidToken();
// Create proxy middleware with token
const proxy = createProxyMiddleware({
target: 'https://api.githubcopilot.com',
changeOrigin: true,
// Remove /v1 prefix when forwarding to GitHub Copilot
pathRewrite: {
'^/v1': '' // Remove /v1 prefix
},
// Inject auth headers (now synchronous)
onProxyReq: (proxyReq, req, res) => {
proxyReq.setHeader('authorization', `Bearer ${token}`);
proxyReq.setHeader('Copilot-Integration-Id', 'vscode-chat');
},
// Handle proxy errors
onError: (err, req, res) => {
console.error('Proxy error:', err);
if (!res.headersSent) {
res.status(500).json({
error: {
message: 'Proxy request failed',
type: 'proxy_error',
code: 500
}
});
}
},
// Log proxy responses
onProxyRes: (proxyRes, req, res) => {
console.log(`📡 Proxy: ${req.method} ${req.path} → ${proxyRes.statusCode}`);
}
});
// Execute proxy
proxy(req, res, next);
} catch (error) {
console.error('Error getting token for proxy:', error);
if (!res.headersSent) {
res.status(500).json({
error: {
message: 'Failed to obtain authentication token',
type: 'auth_error',
code: 500
}
});
}
}
});
// Handle 404 routes
app.use('*', (req, res) => {
res.status(404).json({
error: {
message: `Route ${req.method} ${req.originalUrl} not found`,
type: 'not_found_error',
code: 404
}
});
});
// Error handling middleware
app.use((error, req, res, next) => {
console.error('Unhandled error:', error);
res.status(500).json({
error: {
message: 'Internal server error',
type: 'internal_error',
code: 500
}
});
});
// Start server
app.listen(port, () => {
console.log(`🚀 Copilot API Proxy (Ultra-Fast) running on port ${port}`);
console.log(`📖 OpenAI-compatible endpoints:`);
console.log(` GET http://localhost:${port}/v1/models`);
console.log(` POST http://localhost:${port}/v1/chat/completions`);
console.log(`💡 Health check: http://localhost:${port}/health`);
console.log(`⚡ Ultra-fast transparent proxy mode enabled!`);
});
module.exports = { app, TokenManager };