forked from copilot-extensions/blackbeard-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
142 lines (118 loc) · 4.08 KB
/
index.js
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
import { Octokit } from "@octokit/core";
import express from 'express';
import bodyParser from 'body-parser';
import crypto from 'crypto';
import jwt from 'jsonwebtoken';
import axios from 'axios';
import fs from 'fs';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const port = 3000;
// Use raw body parser for signature verification
app.use(bodyParser.raw({ type: 'application/json' }));
// Middleware to verify GitHub webhook signature
function verifyGitHubSignature(req, res, next) {
const signature = req.headers['x-hub-signature-256'];
const secret = process.env.GITHUB_WEBHOOK_SECRET;
const hmac = crypto.createHmac('sha256', secret);
const digest = `sha256=${hmac.update(req.body).digest('hex')}`;
if (signature !== digest) {
return res.status(401).send('Invalid signature');
}
next();
}
// Handle GitHub webhooks
app.post('/github/webhook', verifyGitHubSignature, (req, res) => {
const event = req.headers['x-github-event'];
const payload = JSON.parse(req.body);
console.log('GitHub Event:', req.headers['x-github-event']);
console.log('Payload:', JSON.stringify(req.body, null, 2));
if (event === 'push') {
console.log('Push event received:', payload);
} else if (event === 'pull_request') {
console.log('Pull request event received:', payload);
}
res.status(200).send('Event received');
});
// Route to handle GitHub OAuth callback
app.get('/github/callback', async (req, res) => {
const code = req.query.code;
const installationId = req.query.installation_id;
console.log(`Received callback with code: ${code}, installation_id: ${installationId}`);
try {
// Exchange the code for an access token (if necessary)
const response = 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 accessToken = response.data.access_token;
console.log(`Access Token: ${accessToken}`);
// Store the access token or use it as needed
// Respond to the user or redirect them to the app page
res.send('GitHub App successfully installed! You can close this page.');
} catch (error) {
console.error('Error during OAuth callback:', error.message);
res.status(500).send('An error occurred during the GitHub OAuth callback.');
}
});
// Generate JWT for GitHub App authentication
function generateJWT() {
const privateKey = fs.readFileSync('./stackassist.2025-01-07.private-key.pem', 'utf8');
const appId = process.env.GITHUB_APP_ID;
const payload = {
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (10 * 60),
iss: appId,
};
return jwt.sign(payload, privateKey, { algorithm: 'RS256' });
}
// Get installation access token
async function getInstallationAccessToken(installationId) {
const jwtToken = generateJWT();
try {
const response = await axios.post(
`https://api.github.com/app/installations/${installationId}/access_tokens`,
{},
{
headers: {
Authorization: `Bearer ${jwtToken}`,
Accept: 'application/vnd.github.v3+json',
},
}
);
return response.data.token;
} catch (error) {
console.error('Error getting installation access token:', error.message);
throw error;
}
}
// Example of authenticated API request
async function makeAuthenticatedRequest() {
const installationId = '59260928';
try {
const accessToken = await getInstallationAccessToken(installationId);
const response = await axios.get('https://api.github.com/repos/YOUR_OWNER/YOUR_REPO/issues', {
headers: {
Authorization: `token ${accessToken}`,
Accept: 'application/vnd.github.v3+json',
},
});
console.log(response.data);
} catch (error) {
console.error('Error making authenticated request:', error.message);
}
}
// Start the server
app.listen(port, () => {
console.log(`Server is running at http://klaim.tplinkdns.com:${port}`);
});