import express from 'express';
import crypto from 'crypto';
const app = express();
// Use raw body for signature verification
app.post('/webhooks/pocketsflow', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.header('x-pocketsflow-signature');
const secret = process.env.POCKETSFLOW_WEBHOOK_SECRET;
const rawBody = req.body; // Buffer
if (!verifySignature(rawBody, signature, secret)) {
return res.status(400).send('Invalid signature');
}
const event = JSON.parse(rawBody.toString('utf8'));
if (alreadyProcessed(event.id)) {
return res.status(200).send('Already processed');
}
handleEvent(event);
res.status(200).send('OK');
});
function verifySignature(rawBody, signature, secret) {
// Replace with the algorithm documented by Pocketsflow
const expected = crypto
.createHmac('sha256', secret)
.update(rawBody)
.digest('hex');
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}