-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_core_api.js
More file actions
651 lines (571 loc) · 20.3 KB
/
main_core_api.js
File metadata and controls
651 lines (571 loc) · 20.3 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
const express = require('express');
const fs = require('fs-extra');
const path = require('path');
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const axios = require('axios');
// Removed Octokit dependency: using axios and direct GitHub REST API calls instead
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Database helper functions
const DB_PATH = path.join(__dirname, 'db.json');
async function readDB() {
try {
const data = await fs.readFile(DB_PATH, 'utf8');
return JSON.parse(data);
} catch (error) {
// Return default structure if file doesn't exist
return {
github_app: {
installations: {},
repositories: {}
},
oauth_users: {}
};
}
}
async function writeDB(data) {
await fs.writeFile(DB_PATH, JSON.stringify(data, null, 2));
}
// GitHub App Setup
let githubApp;
try {
const privateKey = fs.readFileSync(process.env.GITHUB_PRIVATE_KEY_PATH || './private.pem', 'utf8');
githubApp = {
appId: process.env.GITHUB_APP_ID,
privateKey: privateKey,
getInstallationAccessToken: async (installationId) => {
// Create an app JWT and request an installation access token
const jwtToken = jwt.sign({
iat: Math.floor(Date.now() / 1000) - 60,
exp: Math.floor(Date.now() / 1000) + (10 * 60),
iss: process.env.GITHUB_APP_ID
}, privateKey, { algorithm: 'RS256' });
const url = `https://api.github.com/app/installations/${installationId}/access_tokens`;
const resp = await axios.post(url, {}, {
headers: {
Authorization: `Bearer ${jwtToken}`,
Accept: 'application/vnd.github+json'
}
});
return resp.data; // { token, expires_at }
},
getSignedJsonWebToken: () => {
const payload = {
iat: Math.floor(Date.now() / 1000) - 60,
exp: Math.floor(Date.now() / 1000) + (10 * 60),
iss: process.env.GITHUB_APP_ID
};
return jwt.sign(payload, privateKey, { algorithm: 'RS256' });
}
};
} catch (error) {
console.warn('GitHub App not configured properly:', error.message);
}
// Utility Functions
function generateState() {
return crypto.randomBytes(16).toString('hex');
}
function verifyGitHubSignature(payload, signature) {
const secret = process.env.GITHUB_WEBHOOK_SECRET;
if (!secret) return false;
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(`sha256=${expectedSignature}`),
Buffer.from(signature)
);
}
// Routes
// Home route
app.get('/', (req, res) => {
res.json({
message: 'GitHub App and OAuth Integration Server',
endpoints: {
github_app: {
auth: 'GET /app/auth',
callback: 'GET /app/callback',
installations: 'GET /app/installations',
repositories: 'GET /app/repositories',
refresh: 'POST /app/refresh'
},
oauth: {
authorize: 'GET /auth/github',
callback: 'GET /auth/github/callback',
user: 'GET /auth/user/:userId'
},
diff: {
app_diff: 'POST /diff/app',
oauth_diff: 'POST /diff/oauth'
}
}
});
});
// GitHub App authentication - redirect to installation URL
app.get('/app/auth', (req, res) => {
try {
if (!githubApp) {
return res.status(400).json({ error: 'GitHub App not configured' });
}
const state = generateState();
const installationURL = `https://github.com/apps/${process.env.GITHUB_APP_SLUG || 'your-app-name'}/installations/new?state=${state}`;
res.json({
message: 'Visit the installation URL to authenticate and install the GitHub App',
installation_url: installationURL,
state: state,
instructions: 'After installation, you will be redirected to the callback URL'
});
} catch (error) {
console.error('GitHub App auth error:', error);
res.status(500).json({ error: 'Failed to generate authentication URL' });
}
});
// GitHub App callback - handle installation
app.get('/app/callback', async (req, res) => {
try {
const { installation_id, setup_action, state } = req.query;
if (!installation_id) {
return res.status(400).json({ error: 'Installation ID missing' });
}
if (!githubApp) {
return res.status(400).json({ error: 'GitHub App not configured' });
}
// Get installation details using app JWT
const appJwt = githubApp.getSignedJsonWebToken();
const installationResp = await axios.get(`https://api.github.com/app/installations/${installation_id}`, {
headers: {
Authorization: `Bearer ${appJwt}`,
Accept: 'application/vnd.github+json'
}
});
const installation = installationResp.data;
// Create an installation access token and list repositories accessible to the installation
const tokenData = await githubApp.getInstallationAccessToken(installation_id);
const installationToken = tokenData.token;
const reposResp = await axios.get('https://api.github.com/installation/repositories', {
headers: {
Authorization: `token ${installationToken}`,
Accept: 'application/vnd.github+json'
}
});
const repositories = reposResp.data;
// Store installation data
const db = await readDB();
if (!db.github_app) {
db.github_app = { installations: {}, repositories: {} };
}
if (!db.github_app.installations) {
db.github_app.installations = {};
}
if (!db.github_app.repositories) {
db.github_app.repositories = {};
}
db.github_app.installations[installation_id] = {
id: parseInt(installation_id),
account: installation.account,
created_at: new Date().toISOString(),
setup_action,
repositories: repositories.repositories || []
};
// Store repository data
repositories.repositories?.forEach(repo => {
db.github_app.repositories[repo.full_name] = {
...repo,
installation_id: parseInt(installation_id)
};
});
await writeDB(db);
res.json({
message: 'GitHub App installation successful',
installation: {
id: installation_id,
account: installation.account.login,
repositories_count: repositories.repositories?.length || 0,
repositories: repositories.repositories?.map(repo => ({
name: repo.name,
full_name: repo.full_name,
private: repo.private
})) || []
}
});
} catch (error) {
console.error('GitHub App callback error:', error);
res.status(500).json({
error: 'Installation processing failed',
details: error.message
});
}
});
// Refresh GitHub App installations and repositories
app.post('/app/refresh', async (req, res) => {
try {
if (!githubApp) {
return res.status(400).json({ error: 'GitHub App not configured' });
}
const db = await readDB();
const refreshedInstallations = {};
const refreshedRepositories = {};
// Get all installations for this app using app JWT
const appJwt = githubApp.getSignedJsonWebToken();
const installsResp = await axios.get('https://api.github.com/app/installations', {
headers: {
Authorization: `Bearer ${appJwt}`,
Accept: 'application/vnd.github+json'
}
});
const installations = installsResp.data;
for (const installation of installations) {
const installationId = installation.id;
// Create installation access token
const tokenData = await githubApp.getInstallationAccessToken(installationId);
const installationToken = tokenData.token;
// Get repositories for this installation
const reposResp = await axios.get('https://api.github.com/installation/repositories', {
headers: {
Authorization: `token ${installationToken}`,
Accept: 'application/vnd.github+json'
}
});
refreshedInstallations[installationId] = {
id: installationId,
account: installation.account,
created_at: installation.created_at,
updated_at: installation.updated_at,
repositories: reposResp.data.repositories || []
};
// Store repository data
reposResp.data.repositories?.forEach(repo => {
refreshedRepositories[repo.full_name] = {
...repo,
installation_id: installationId
};
});
}
// Update database
db.github_app.installations = refreshedInstallations;
db.github_app.repositories = refreshedRepositories;
await writeDB(db);
res.json({
message: 'GitHub App data refreshed successfully',
installations_count: Object.keys(refreshedInstallations).length,
repositories_count: Object.keys(refreshedRepositories).length,
installations: Object.values(refreshedInstallations).map(inst => ({
id: inst.id,
account: inst.account.login,
repositories_count: inst.repositories.length
}))
});
} catch (error) {
console.error('Error refreshing GitHub App data:', error);
res.status(500).json({
error: 'Failed to refresh data',
details: error.message
});
}
});
// Get GitHub App installations
app.get('/app/installations', async (req, res) => {
try {
if (!githubApp) {
return res.status(400).json({ error: 'GitHub App not configured' });
}
const db = await readDB();
const installations = db.github_app?.installations || {};
res.json({
installations: Object.values(installations),
total_count: Object.keys(installations).length
});
} catch (error) {
console.error('Error fetching installations:', error);
res.status(500).json({ error: 'Failed to fetch installations' });
}
});
// Get repositories accessible by GitHub App
app.get('/app/repositories', async (req, res) => {
try {
if (!githubApp) {
return res.status(400).json({ error: 'GitHub App not configured' });
}
const db = await readDB();
const repositories = db.github_app?.repositories || {};
res.json({
repositories: Object.values(repositories),
total_count: Object.keys(repositories).length
});
} catch (error) {
console.error('Error fetching repositories:', error);
res.status(500).json({ error: 'Failed to fetch repositories' });
}
});
// GitHub OAuth Routes
// OAuth authorization
app.get('/auth/github', (req, res) => {
const state = generateState();
// Allow configuring OAuth scopes via environment variable.
// Default includes repo (full), plus a read-only content permission if supported by the GitHub account.
const scope = process.env.GITHUB_OAUTH_SCOPES || 'repo,user:email';
const authURL = `https://github.com/login/oauth/authorize?client_id=${process.env.GITHUB_CLIENT_ID}&redirect_uri=${process.env.CALLBACK_URL}&scope=${encodeURIComponent(scope)}&state=${state}`;
// Store state for verification (in production, use session or Redis)
res.cookie('oauth_state', state, { httpOnly: true, maxAge: 600000 }); // 10 minutes
res.send(authURL);
});
// OAuth callback
app.get('/auth/github/callback', async (req, res) => {
try {
const { code, state } = req.query;
const storedState = req.headers.cookie?.split('oauth_state=')[1]?.split(';')[0];
if (!code) {
return res.status(400).json({ error: 'Authorization code missing' });
}
// Exchange code for access token
const tokenResponse = await axios.post('https://github.com/login/oauth/access_token', {
client_id: process.env.GITHUB_CLIENT_ID,
client_secret: process.env.GITHUB_CLIENT_SECRET,
code: code
}, {
headers: {
'Accept': 'application/json'
}
});
const { access_token } = tokenResponse.data;
if (!access_token) {
return res.status(400).json({ error: 'Failed to get access token' });
}
// Get user information
const userResponse = await axios.get('https://api.github.com/user', {
headers: {
'Authorization': `Bearer ${access_token}`,
'Accept': 'application/vnd.github.v3+json'
}
});
const user = userResponse.data;
// Store user data
const db = await readDB();
if (!db.oauth_users) {
db.oauth_users = {};
}
db.oauth_users[user.id] = {
id: user.id,
login: user.login,
name: user.name,
email: user.email,
access_token: access_token,
created_at: new Date().toISOString()
};
await writeDB(db);
res.json({
message: 'OAuth integration successful',
user: {
id: user.id,
login: user.login,
name: user.name,
email: user.email
}
});
} catch (error) {
console.error('OAuth callback error:', error);
res.status(500).json({ error: 'OAuth integration failed' });
}
});
// Get OAuth user info
app.get('/auth/user/:userId', async (req, res) => {
try {
const { userId } = req.params;
const db = await readDB();
const user = db.oauth_users[userId];
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
// Remove sensitive data before sending
const { access_token, ...userInfo } = user;
res.json(userInfo);
} catch (error) {
console.error('Error fetching user:', error);
res.status(500).json({ error: 'Failed to fetch user' });
}
});
// Diff Calculation Routes
// Calculate diff using GitHub App
app.post('/diff/app', async (req, res) => {
try {
const { repo_owner, repo_name, base_branch, head_branch, installation_id } = req.body;
if (!repo_owner || !repo_name || !base_branch || !head_branch) {
return res.status(400).json({
error: 'Missing required parameters: repo_owner, repo_name, base_branch, head_branch'
});
}
if (!githubApp) {
return res.status(400).json({ error: 'GitHub App not configured' });
}
// Create installation access token and call GitHub compare commits API
const tokenData = await githubApp.getInstallationAccessToken(installation_id);
const installationToken = tokenData.token;
const comparisonResp = await axios.get(`https://api.github.com/repos/${repo_owner}/${repo_name}/compare/${encodeURIComponent(base_branch)}...${encodeURIComponent(head_branch)}`, {
headers: {
Authorization: `token ${installationToken}`,
Accept: 'application/vnd.github+json'
}
});
const comparison = comparisonResp.data;
const diffData = {
repository: `${repo_owner}/${repo_name}`,
base_branch,
head_branch,
total_commits: comparison.total_commits,
ahead_by: comparison.ahead_by,
behind_by: comparison.behind_by,
status: comparison.status,
files_changed: comparison.files?.length || 0,
additions: comparison.files?.reduce((sum, file) => sum + (file.additions || 0), 0) || 0,
deletions: comparison.files?.reduce((sum, file) => sum + (file.deletions || 0), 0) || 0,
files: comparison.files?.map(file => ({
filename: file.filename,
status: file.status,
additions: file.additions,
deletions: file.deletions,
changes: file.changes,
patch: file.patch
})) || [],
commits: comparison.commits?.map(commit => ({
sha: commit.sha,
message: commit.commit.message,
author: commit.commit.author,
date: commit.commit.author.date
})) || [],
generated_at: new Date().toISOString(),
method: 'github_app'
};
// Save diff to file
const filename = `diff_${repo_owner}-${repo_name}_${base_branch}-to-${head_branch}_${Date.now()}.json`;
await fs.writeFile(path.join(__dirname, filename), JSON.stringify(diffData, null, 2));
res.json({
message: 'Diff calculated successfully using GitHub App',
diff: diffData,
saved_to: filename
});
} catch (error) {
console.error('Error calculating diff with GitHub App:', error);
res.status(500).json({
error: 'Failed to calculate diff',
details: error.message
});
}
});
// Calculate diff using OAuth
app.post('/diff/oauth', async (req, res) => {
try {
const { repo_owner, repo_name, base_branch, head_branch, user_id } = req.body;
if (!repo_owner || !repo_name || !base_branch || !head_branch || !user_id) {
return res.status(400).json({
error: 'Missing required parameters: repo_owner, repo_name, base_branch, head_branch, user_id'
});
}
const db = await readDB();
const user = db.oauth_users[user_id];
if (!user || !user.access_token) {
return res.status(404).json({ error: 'User not found or access token missing' });
}
// Call GitHub compare commits API with the user's oauth token
const comparisonResp = await axios.get(`https://api.github.com/repos/${repo_owner}/${repo_name}/compare/${encodeURIComponent(base_branch)}...${encodeURIComponent(head_branch)}`, {
headers: {
Authorization: `token ${user.access_token}`,
Accept: 'application/vnd.github+json'
}
});
const comparison = comparisonResp.data;
const diffData = {
repository: `${repo_owner}/${repo_name}`,
base_branch,
head_branch,
total_commits: comparison.total_commits,
ahead_by: comparison.ahead_by,
behind_by: comparison.behind_by,
status: comparison.status,
files_changed: comparison.files?.length || 0,
additions: comparison.files?.reduce((sum, file) => sum + (file.additions || 0), 0) || 0,
deletions: comparison.files?.reduce((sum, file) => sum + (file.deletions || 0), 0) || 0,
files: comparison.files?.map(file => ({
filename: file.filename,
status: file.status,
additions: file.additions,
deletions: file.deletions,
changes: file.changes,
patch: file.patch
})) || [],
commits: comparison.commits?.map(commit => ({
sha: commit.sha,
message: commit.commit.message,
author: commit.commit.author,
date: commit.commit.author.date
})) || [],
generated_at: new Date().toISOString(),
method: 'oauth',
requested_by: user.login
};
// Save diff to file
const filename = `diff_${repo_owner}-${repo_name}_${base_branch}-to-${head_branch}_${Date.now()}.json`;
await fs.writeFile(path.join(__dirname, filename), JSON.stringify(diffData, null, 2));
res.json({
message: 'Diff calculated successfully using OAuth',
diff: diffData,
saved_to: filename
});
} catch (error) {
console.error('Error calculating diff with OAuth:', error);
res.status(500).json({
error: 'Failed to calculate diff',
details: error.message
});
}
});
// Health check
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
github_app_configured: !!githubApp,
oauth_configured: !!(process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET)
});
});
// Error handling middleware
app.use((error, req, res, next) => {
console.error('Server error:', error);
res.status(500).json({
error: 'Internal server error',
message: error.message
});
});
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({
error: 'Endpoint not found',
path: req.originalUrl
});
});
// Start server
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`GitHub App configured: ${!!githubApp}`);
console.log(`OAuth configured: ${!!(process.env.GITHUB_CLIENT_ID && process.env.GITHUB_CLIENT_SECRET)}`);
console.log('\nAvailable endpoints:');
console.log('GET / - API documentation');
console.log('GET /health - Health check');
console.log('GET /app/auth - GitHub App authentication');
console.log('GET /app/callback - GitHub App installation callback');
console.log('POST /app/refresh - Refresh GitHub App installations');
console.log('GET /app/installations - GitHub App installations');
console.log('GET /app/repositories - GitHub App repositories');
console.log('POST /webhook - GitHub App webhook (optional)');
console.log('GET /auth/github - OAuth authorization');
console.log('GET /auth/github/callback - OAuth callback');
console.log('GET /auth/user/:userId - Get OAuth user info');
console.log('POST /diff/app - Calculate diff using GitHub App');
console.log('POST /diff/oauth - Calculate diff using OAuth');
});
module.exports = app;