Entegrasyon
Express
İmza doğrulayan, tekrarları yutan ve işi kuyruğa atan tam bir Express sunucusu.
Kurulum
npm install expressTam örnek
import crypto from 'node:crypto';
import express from 'express';
const app = express();
const SECRET = process.env.HIKIE_WEBHOOK_SECRET;
const TOLERANCE_SECONDS = 300;
if (!SECRET) {
throw new Error('HIKIE_WEBHOOK_SECRET tanımlı değil.');
}
/**
* Ham gövde ara yazılımı — YALNIZCA webhook yolunda.
*
* Uygulamanın geri kalanı normal `express.json()` kullanmaya devam edebilir;
* burada araya girmesi imzayı bozar.
*/
app.use('/hikie/webhook', express.raw({ type: 'application/json', limit: '1mb' }));
app.post('/hikie/webhook', async (req, res) => {
const timestamp = req.get('Hikie-Timestamp');
const signature = req.get('Hikie-Signature');
const webhookId = req.get('Hikie-Webhook-Id');
const eventType = req.get('Hikie-Event');
const attempt = Number(req.get('Hikie-Delivery-Attempt') ?? 1);
if (!timestamp || !signature || !webhookId) {
return res.sendStatus(400);
}
const rawBody = req.body.toString('utf8');
// 1) Zaman damgası penceresi — tekrar oynatma koruması
const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
if (!Number.isFinite(age) || age > TOLERANCE_SECONDS) {
console.warn(`[hikie] zaman damgası penceresi dışında: ${age}s`);
return res.sendStatus(400);
}
// 2) İmza — sabit zamanlı karşılaştırma
if (!signatureMatches(SECRET, timestamp, rawBody, signature)) {
console.warn(`[hikie] imza doğrulanamadı (${eventType})`);
return res.sendStatus(400);
}
// 3) Tekrar koruması — aynı webhookId ikinci kez gelirse iş yapma
if (await alreadyProcessed(webhookId)) {
console.log(`[hikie] ${webhookId} zaten işlendi (deneme ${attempt})`);
return res.sendStatus(200);
}
// Gövde zarfsız: payload doğrudan gövdenin kökü
let payload;
try {
payload = JSON.parse(rawBody);
} catch {
return res.sendStatus(400);
}
// 4) İşi kalıcı bir yere yaz ve HEMEN yanıt dön
try {
await enqueue({ eventType, webhookId, payload });
await markProcessed(webhookId);
} catch (error) {
// Kuyruğa yazamadık — 503 dönerek yeniden denenmesini istiyoruz.
console.error('[hikie] kuyruğa yazılamadı:', error);
return res.sendStatus(503);
}
res.sendStatus(200);
});
app.listen(3000, () => console.log('hikie webhook dinleniyor :3000'));
// ---------------------------------------------------------------- yardımcılar
function signatureMatches(secret, timestamp, rawBody, signature) {
const expected = crypto
.createHmac('sha256', secret)
.update(`${timestamp}.${rawBody}`, 'utf8')
.digest('hex');
const a = Buffer.from(expected, 'utf8');
const b = Buffer.from(signature, 'utf8');
// Uzunluk farkı timingSafeEqual'ı patlatır.
if (a.length !== b.length) return false;
return crypto.timingSafeEqual(a, b);
}Event'i işlemek
Yanıt döndükten sonra çalışan worker tarafı:
export async function handleEvent(eventType, payload) {
switch (eventType) {
case 'order.paid':
return grantPurchase(payload);
case 'order.updated':
return applyOrderStatus(payload);
case 'order.shipmentUpdated':
return updateShipmentStatus(payload);
case 'test.ping':
console.log('[hikie] test bağlantısı başarılı');
return;
default:
// Bilinmeyen tip — yeni event tipleri eklenebilir, hata sayma.
console.log(`[hikie] işlenmeyen event: ${eventType}`);
}
}
async function grantPurchase(order) {
for (const item of order.items) {
const email = order.customerInfo?.email;
await rcon(`givepackage "${email}" "${item.variant?.name ?? item.title}"`);
}
}Tekrar kaydını Redis'te tutmak
alreadyProcessed / markProcessed için en basit üretim uygulaması:
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const TTL_SECONDS = 7 * 24 * 60 * 60; // 7 gün — retry penceresinin çok üstünde
export async function alreadyProcessed(webhookId) {
// SET NX: yoksa yaz ve true dön, varsa null dön.
const written = await redis.set(`hikie:wh:${webhookId}`, '1', {
NX: true,
EX: TTL_SECONDS,
});
return written === null;
}
export async function markProcessed() {
// alreadyProcessed zaten atomik olarak işaretledi.
}SET NX ile kontrol ve işaretleme tek atomik adımda yapılıyor. Ayrı GET +
SET kullanmak, aynı webhook aynı anda iki kez gelirse (paralel worker'lar)
ikisinin de "yeni" görmesine yol açar.
Redis yoksa veritabanınızda tekil indeksli bir tablo aynı işi görür:
CREATE TABLE hikie_webhooks (
webhook_id VARCHAR(64) PRIMARY KEY,
processed_at TIMESTAMPTZ NOT NULL DEFAULT now()
);export async function alreadyProcessed(webhookId) {
const { rowCount } = await db.query(
'INSERT INTO hikie_webhooks (webhook_id) VALUES ($1) ON CONFLICT DO NOTHING',
[webhookId],
);
return rowCount === 0; // eklenmediyse zaten vardı
}Router olarak ayırmak
Büyüyen bir uygulamada webhook'u kendi router'ına almak daha temiz:
import crypto from 'node:crypto';
import express from 'express';
export const hikieRouter = express.Router();
hikieRouter.use(express.raw({ type: 'application/json', limit: '1mb' }));
// İmza doğrulaması bir ara yazılım olarak
hikieRouter.use((req, res, next) => {
const timestamp = req.get('Hikie-Timestamp');
const signature = req.get('Hikie-Signature');
if (!timestamp || !signature) return res.sendStatus(400);
const rawBody = req.body.toString('utf8');
const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
if (!Number.isFinite(age) || age > 300) return res.sendStatus(400);
if (!signatureMatches(process.env.HIKIE_WEBHOOK_SECRET, timestamp, rawBody, signature)) {
return res.sendStatus(400);
}
req.hikiePayload = JSON.parse(rawBody);
req.hikieWebhookId = req.get('Hikie-Webhook-Id');
req.hikieEventType = req.get('Hikie-Event');
next();
});
hikieRouter.post('/webhook', async (req, res) => {
if (await alreadyProcessed(req.hikieWebhookId)) return res.sendStatus(200);
await enqueue({
eventType: req.hikieEventType,
webhookId: req.hikieWebhookId,
payload: req.hikiePayload,
});
res.sendStatus(200);
});import express from 'express';
import { hikieRouter } from './routes/hikie.js';
const app = express();
// Webhook router'ı express.json()'dan ÖNCE bağlanmalı.
app.use('/hikie', hikieRouter);
app.use(express.json());
// … uygulamanın geri kalanıSıra önemli. app.use(express.json()) webhook router'ından önce gelirse gövde
parse edilir, req.body bir nesne olur ve ham baytlara erişemezsiniz.