|
1 | | -import express, { Request, Response, Application } from "express"; |
| 1 | +import express, { Request, Response, NextFunction, Application } from "express"; |
| 2 | + |
| 3 | +declare module 'express-serve-static-core' { |
| 4 | + interface Request { |
| 5 | + rawBody: string; |
| 6 | + } |
| 7 | +} |
| 8 | + |
2 | 9 | import dotenv from "dotenv"; |
| 10 | +import { verifyWebhookSignature } from "@hookdeck/sdk/webhooks"; |
3 | 11 |
|
4 | 12 | dotenv.config(); |
5 | 13 |
|
| 14 | +const HOOKDECK_WEBHOOK_SECRET = process.env.HOOKDECK_WEBHOOK_SECRET; |
| 15 | + |
6 | 16 | const app: Application = express(); |
7 | | -app.use(express.json()); |
| 17 | + |
| 18 | +const verify = async (req: Request, res: Response, next: NextFunction) => { |
| 19 | + if(!HOOKDECK_WEBHOOK_SECRET) { |
| 20 | + console.warn("No HOOKDECK_WEBHOOK_SECRET found in environment variables. Skipping verification.") |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + const verified = await verifyWebhookSignature({ |
| 25 | + headers: req.headers as { [key: string]: string; }, |
| 26 | + rawBody: req.rawBody, |
| 27 | + signingSecret: HOOKDECK_WEBHOOK_SECRET |
| 28 | + }); |
| 29 | + |
| 30 | + if(verified) { |
| 31 | + next(); |
| 32 | + } |
| 33 | + else { |
| 34 | + res.status(401).send("Unauthorized"); |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +app.use(express.json({ |
| 39 | + verify: (req: Request, res: Response, buf: Buffer, encoding: string) => { |
| 40 | + req.rawBody = buf.toString(); |
| 41 | + } |
| 42 | +})); |
8 | 43 |
|
9 | 44 | const port = process.env.PORT || 3030; |
10 | 45 |
|
11 | | -app.post("*", (req: Request, res: Response) => { |
12 | | - console.log({ webhook_received: new Date().toISOString(), body: req.body }); |
| 46 | +app.post("*", verify, (req: Request, res: Response) => { |
| 47 | + console.log({ |
| 48 | + webhook_received: new Date().toISOString(), |
| 49 | + path: req.path, |
| 50 | + body: req.body |
| 51 | + }); |
13 | 52 |
|
14 | 53 | res.json({ status: "ACCEPTED" }); |
15 | 54 | }); |
|
0 commit comments