|
| 1 | +import type { NextApiRequest, NextApiResponse } from "next"; |
| 2 | +import { verifyGitHubWebhookSignature } from "../../../../utils/github"; |
| 3 | + |
| 4 | +export const config = { |
| 5 | + api: { |
| 6 | + bodyParser: false, |
| 7 | + }, |
| 8 | +}; |
| 9 | + |
| 10 | +async function getRawBody(req: NextApiRequest): Promise<string> { |
| 11 | + const chunks: Buffer[] = []; |
| 12 | + for await (const chunk of req) { |
| 13 | + chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk); |
| 14 | + } |
| 15 | + return Buffer.concat(chunks).toString("utf8"); |
| 16 | +} |
| 17 | + |
| 18 | +export default async function handler( |
| 19 | + req: NextApiRequest, |
| 20 | + res: NextApiResponse |
| 21 | +) { |
| 22 | + if (req.method !== "POST") { |
| 23 | + return res.status(405).json({ error: "Method not allowed" }); |
| 24 | + } |
| 25 | + |
| 26 | + const rawBody = await getRawBody(req); |
| 27 | + const signature = req.headers["x-hub-signature-256"] as string | undefined; |
| 28 | + const webhookSecret = |
| 29 | + process.env.GITHUB_MARKETPLACE_WEBHOOK_SECRET || |
| 30 | + process.env.GITHUB_WEBHOOK_SECRET; |
| 31 | + |
| 32 | + if (!webhookSecret) { |
| 33 | + console.error("GitHub Marketplace webhook secret not configured"); |
| 34 | + return res.status(500).json({ error: "Webhook secret not configured" }); |
| 35 | + } |
| 36 | + |
| 37 | + if (!verifyGitHubWebhookSignature(rawBody, signature, webhookSecret)) { |
| 38 | + console.error("Invalid marketplace webhook signature"); |
| 39 | + return res.status(401).json({ error: "Invalid signature" }); |
| 40 | + } |
| 41 | + |
| 42 | + const event = req.headers["x-github-event"] as string; |
| 43 | + const payload = JSON.parse(rawBody); |
| 44 | + |
| 45 | + console.log("GitHub Marketplace webhook received:", { |
| 46 | + event, |
| 47 | + action: payload.action, |
| 48 | + account: payload.marketplace_purchase?.account?.login, |
| 49 | + plan: payload.marketplace_purchase?.plan?.name, |
| 50 | + }); |
| 51 | + |
| 52 | + return res.status(200).json({ message: "Event received" }); |
| 53 | +} |
0 commit comments