| 1 | import { NextResponse } from 'next/server'; |
| 2 | import crypto from 'crypto'; |
| 3 | |
| 4 | export async function POST(request: Request) { |
| 5 | try { |
| 6 | const payloadText = await request.text(); |
| 7 | const signature = request.headers.get('x-hub-signature-256'); |
| 8 | const secret = process.env.GITHUB_WEBHOOK_SECRET; |
| 9 | |
| 10 | if (secret) { |
| 11 | if (!signature) { |
| 12 | return NextResponse.json({ error: 'Unauthorized: Missing signature' }, { status: 401 }); |
| 13 | } |
| 14 | const hmac = crypto.createHmac('sha256', secret); |
| 15 | const digest = 'sha256=' + hmac.update(payloadText).digest('hex'); |
| 16 | |
| 17 | // Use timingSafeEqual to prevent timing attacks |
| 18 | try { |
| 19 | if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(digest))) { |
| 20 | return NextResponse.json({ error: 'Unauthorized: Invalid signature' }, { status: 401 }); |
| 21 | } |
| 22 | } catch { |
| 23 | return NextResponse.json({ error: 'Unauthorized: Invalid signature format' }, { status: 401 }); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | const payload = JSON.parse(payloadText); |
| 28 | |
| 29 | // Forward the payload to the local OSIRIS Discord Bot running on Port 3005 |
| 30 | // Using the Tailscale internal IP of the Discord bot server |
| 31 | const response = await fetch('http://100.68.100.15:3005/github/webhook', { |
| 32 | method: 'POST', |
| 33 | headers: { |
| 34 | 'Content-Type': 'application/json', |
| 35 | ...(signature ? { 'x-hub-signature-256': signature } : {}) |
| 36 | }, |
| 37 | body: payloadText, |
| 38 | }); |
| 39 | |
| 40 | if (!response.ok) { |
| 41 | console.error('Failed to forward webhook to Discord bot:', response.statusText); |
| 42 | return NextResponse.json({ error: 'Failed to forward to bot' }, { status: 500 }); |
| 43 | } |
| 44 | |
| 45 | return NextResponse.json({ success: true, message: 'Webhook forwarded successfully' }, { status: 200 }); |
| 46 | |
| 47 | } catch (error) { |
| 48 | console.error('Error handling GitHub webhook:', error); |
| 49 | return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 }); |
| 50 | } |
| 51 | } |