import crypto from 'node:crypto';
import express from 'express';
const app = express();
app.post('/webhooks/sly', express.raw({ type: '*/*' }), (req, res) => {
const header = req.get('x-sly-signature');
if (!header) return res.status(400).end();
const parts = Object.fromEntries(header.split(',').map(p => p.split('=')));
const timestamp = parseInt(parts.t, 10);
const signature = parts.v1;
if (Math.abs(Date.now() / 1000 - timestamp) > 300) return res.status(400).end();
const expected = crypto
.createHmac('sha256', process.env.SLY_WEBHOOK_SECRET!)
.update(`${timestamp}.${req.body}`)
.digest('hex');
const valid = crypto.timingSafeEqual(
Buffer.from(expected),
Buffer.from(signature)
);
if (!valid) return res.status(400).end();
// Safe to parse + process
const event = JSON.parse(req.body.toString());
handleEvent(event);
res.status(200).end();
});