Fastify
Ham gövde eklentisi, imza doğrulayan preHandler ve tam bir Fastify sunucusu.
Fastify gövdeyi varsayılan olarak parse eder ve ham hâlini atar. İmza doğrulaması için önce ham baytları saklamamız gerekiyor.
Kurulum
npm install fastifyHam gövde eklentisi
En temiz yol kendi content-type parser'ınızı tanımlamak: gövdeyi hem parse
edin hem ham hâlini request.rawBody olarak saklayın.
import fp from 'fastify-plugin';
/**
* application/json gövdelerini parse ederken ham metni de saklar.
*
* `request.rawBody` yalnızca imza doğrulaması için var; iş mantığı normal
* `request.body` nesnesini kullanmaya devam eder.
*/
async function hikieRawBody(fastify) {
fastify.addContentTypeParser(
'application/json',
{ parseAs: 'buffer' },
(request, body, done) => {
request.rawBody = body.toString('utf8');
try {
done(null, JSON.parse(request.rawBody));
} catch (error) {
error.statusCode = 400;
done(error, undefined);
}
},
);
}
export default fp(hikieRawBody, { name: 'hikie-raw-body' });fastify-plugin ile sarmak eklentinin kapsamını kök seviyeye taşır. Sarmazsanız
parser yalnızca eklentinin kendi kapsamında geçerli olur.
fastify-plugin yüklemek istemiyorsanız aynı şeyi doğrudan da yapabilirsiniz:
fastify.addContentTypeParser('application/json', { parseAs: 'buffer' }, (req, body, done) => {
req.rawBody = body.toString('utf8');
try { done(null, JSON.parse(req.rawBody)); }
catch (error) { error.statusCode = 400; done(error, undefined); }
});Tam örnek
import crypto from 'node:crypto';
import Fastify from 'fastify';
import hikieRawBody from './plugins/hikie-raw-body.js';
const SECRET = process.env.HIKIE_WEBHOOK_SECRET;
const TOLERANCE_SECONDS = 300;
if (!SECRET) {
throw new Error('HIKIE_WEBHOOK_SECRET tanımlı değil.');
}
const fastify = Fastify({
logger: true,
bodyLimit: 1_048_576, // 1 MB
});
await fastify.register(hikieRawBody);
fastify.post(
'/hikie/webhook',
{
// Doğrulama handler'dan önce çalışır; handler yalnızca doğrulanmış
// istekleri görür.
preHandler: verifyHikieSignature,
},
async (request, reply) => {
const webhookId = request.headers['hikie-webhook-id'];
const attempt = Number(request.headers['hikie-delivery-attempt'] ?? 1);
// Tekrar koruması
if (await alreadyProcessed(webhookId)) {
request.log.info({ webhookId, attempt }, 'hikie: zaten işlendi');
return reply.code(200).send();
}
try {
await enqueue(request.body);
} catch (error) {
// Kuyruğa yazamadık — yeniden denensin.
request.log.error({ err: error }, 'hikie: kuyruğa yazılamadı');
return reply.code(503).send();
}
return reply.code(200).send();
},
);
await fastify.listen({ port: 3000, host: '0.0.0.0' });
// ---------------------------------------------------------------- doğrulama
async function verifyHikieSignature(request, reply) {
const timestamp = request.headers['hikie-timestamp'];
const signature = request.headers['hikie-signature'];
const webhookId = request.headers['hikie-webhook-id'];
if (!timestamp || !signature || !webhookId) {
return reply.code(400).send();
}
// 1) Zaman damgası penceresi
const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
if (!Number.isFinite(age) || age > TOLERANCE_SECONDS) {
request.log.warn({ age }, 'hikie: zaman damgası penceresi dışında');
return reply.code(400).send();
}
// 2) İmza — request.rawBody parser'ın sakladığı ham metin
const expected = crypto
.createHmac('sha256', SECRET)
.update(`${timestamp}.${request.rawBody}`, 'utf8')
.digest('hex');
const a = Buffer.from(expected, 'utf8');
const b = Buffer.from(signature, 'utf8');
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
request.log.warn('hikie: imza doğrulanamadı');
return reply.code(400).send();
}
}TypeScript ile
rawBody alanını istek tipine eklemeniz gerekir:
import 'fastify';
declare module 'fastify' {
interface FastifyRequest {
rawBody?: string;
}
}import crypto from 'node:crypto';
import Fastify, { type FastifyReply, type FastifyRequest } from 'fastify';
interface HikieOrder {
orderId: string;
status: string;
storeSlug: string | null;
currency: string;
totals: {
subtotal: string;
shipping: string;
discount: string;
total: string;
};
customerInfo: {
firstName: string | null;
lastName: string | null;
email: string | null;
phone: string | null;
} | null;
items: Array<{
itemId: string | null;
title: string | null;
type: 'PHYSICAL' | 'DIGITAL';
variant: { sku: string | null; name: string | null } | null;
quantity: number;
unitPrice: string;
total: string;
}>;
}
const fastify = Fastify({ logger: true });
fastify.post(
'/hikie/webhook',
{ preHandler: verifyHikieSignature },
async (request, reply) => {
// Olay tipi başlıkta, model gövdenin kökünde
const eventType = request.headers['hikie-event'] as string;
if (eventType === 'order.paid') {
await grantPurchase(request.body as HikieOrder);
}
return reply.code(200).send();
},
);
async function verifyHikieSignature(
request: FastifyRequest,
reply: FastifyReply,
): Promise<void> {
const timestamp = request.headers['hikie-timestamp'] as string | undefined;
const signature = request.headers['hikie-signature'] as string | undefined;
if (!timestamp || !signature || !request.rawBody) {
reply.code(400).send();
return;
}
const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
if (!Number.isFinite(age) || age > 300) {
reply.code(400).send();
return;
}
const expected = crypto
.createHmac('sha256', process.env.HIKIE_WEBHOOK_SECRET!)
.update(`${timestamp}.${request.rawBody}`, 'utf8')
.digest('hex');
const a = Buffer.from(expected, 'utf8');
const b = Buffer.from(signature, 'utf8');
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
reply.code(400).send();
}
}Yalnızca webhook yolunda ham gövde
Uygulamanızın geri kalanı ham gövdeye ihtiyaç duymuyorsa, parser'ı kapsamlı bir eklenti içine alarak sınırlayabilirsiniz:
// Webhook kapsamı — kendi parser'ı var
fastify.register(async (scope) => {
scope.addContentTypeParser('application/json', { parseAs: 'buffer' }, (req, body, done) => {
req.rawBody = body.toString('utf8');
try { done(null, JSON.parse(req.rawBody)); }
catch (error) { error.statusCode = 400; done(error, undefined); }
});
scope.post('/webhook', { preHandler: verifyHikieSignature }, handler);
}, { prefix: '/hikie' });
// Uygulamanın geri kalanı Fastify'ın varsayılan parser'ını kullanır.
fastify.post('/api/orders', async () => { /* … */ });Bu sürümde fastify-plugin kullanılmaz — kapsamın sınırlı kalması tam
olarak istediğimiz şey.