import express from "express";
import crypto from "node:crypto";
const app = express();
app.post(
"/webhooks/iex",
express.raw({ type: "application/json" }),
async (req, res) => {
const secret = process.env.IEX_WEBHOOK_SECRET!;
const eventId = String(req.header("X-Webhook-Event-Id") ?? "");
const eventType = String(req.header("X-Webhook-Event-Type") ?? "");
const timestamp = String(req.header("X-Webhook-Timestamp") ?? "");
const nonce = String(req.header("X-Webhook-Nonce") ?? "");
const signature = String(req.header("X-Webhook-Signature") ?? "");
const bodyHash = crypto
.createHash("sha256")
.update(req.body)
.digest("hex");
const canonical = [
"v1",
eventId,
eventType,
timestamp,
nonce,
bodyHash,
].join("\n");
const expected =
"sha256=" + crypto.createHmac("sha256", secret).update(canonical).digest("hex");
if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature))) {
return res.status(401).json({ ok: false });
}
const payload = JSON.parse(req.body.toString("utf8"));
// Сохраните eventId в базе, чтобы не обработать одно событие дважды.
// После сохранения можно запускать бизнес-логику.
return res.json({ received: true });
},
);