hikiehikieDeveloper Documentation
Entegrasyon

NestJS

rawBody kurulumu, imza doğrulayan bir Guard ve tam bir modül yapısı.

NestJS ham gövdeyi rawBody: true seçeneğiyle sunar. Doğrulamayı bir Guard içine koyarsak controller yalnızca doğrulanmış istekleri görür.

Kurulum

npm install @nestjs/common @nestjs/core @nestjs/platform-express

1. Ham gövdeyi açın

src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    // request.rawBody'yi doldurur — imza doğrulaması buna ihtiyaç duyar.
    rawBody: true,
    // Varsayılan 100 KB; webhook gövdeleri küçüktür ama sepet büyük olabilir.
    bodyParser: true,
  });

  await app.listen(3000);
}

void bootstrap();

rawBody: true, request.body'yi bozmaz — parse edilmiş nesne yerinde kalır, request.rawBody yanına bir Buffer olarak eklenir.

2. Doğrulama guard'ı

src/hikie/hikie-signature.guard.ts
import {
  BadRequestException,
  CanActivate,
  ExecutionContext,
  Injectable,
  Logger,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createHmac, timingSafeEqual } from 'node:crypto';
import type { RawBodyRequest } from '@nestjs/common';
import type { Request } from 'express';

const TOLERANCE_SECONDS = 300;

/**
 * Hikie imzasını doğrular. Geçmeyen istek controller'a hiç ulaşmaz.
 *
 * Bilinçli olarak 400 dönüyoruz, 401 değil: 401 Hikie tarafında KALICI hata
 * sayılır ve iki ardışık başarısızlıkta abonelik `failing` durumuna düşer.
 * 400 ise "isteği anlamadım" der ve aynı sonucu doğurur — ama asıl fark,
 * geçici sorunlarda 503 dönmemiz gerektiğidir (aşağıya bakın).
 */
@Injectable()
export class HikieSignatureGuard implements CanActivate {
  private readonly logger = new Logger(HikieSignatureGuard.name);
  private readonly secret: string;

  constructor(configService: ConfigService) {
    const secret = configService.get<string>('HIKIE_WEBHOOK_SECRET');
    if (!secret) {
      throw new Error('HIKIE_WEBHOOK_SECRET tanımlı değil.');
    }
    this.secret = secret;
  }

  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<RawBodyRequest<Request>>();

    const timestamp = request.headers['hikie-timestamp'];
    const signature = request.headers['hikie-signature'];
    const rawBody = request.rawBody;

    if (
      typeof timestamp !== 'string' ||
      typeof signature !== 'string' ||
      !rawBody
    ) {
      throw new BadRequestException('Eksik imza başlıkları.');
    }

    // 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) {
      this.logger.warn(`Zaman damgası penceresi dışında: ${age}s`);
      throw new BadRequestException('Zaman damgası geçersiz.');
    }

    // 2) İmza — sabit zamanlı karşılaştırma
    const expected = createHmac('sha256', this.secret)
      .update(`${timestamp}.${rawBody.toString('utf8')}`, 'utf8')
      .digest('hex');

    const a = Buffer.from(expected, 'utf8');
    const b = Buffer.from(signature, 'utf8');

    if (a.length !== b.length || !timingSafeEqual(a, b)) {
      this.logger.warn(
        `İmza doğrulanamadı: ${String(request.headers['hikie-event'])}`,
      );
      throw new BadRequestException('İmza geçersiz.');
    }

    return true;
  }
}

3. Tipler

src/hikie/hikie-event.types.ts
export const HIKIE_EVENT_TYPES = [
  'order.paid',
  'order.updated',
  'order.shipmentUpdated',
  'product.created',
  'product.updated',
  'product.deleted',
  'test.ping',
] as const;

export type HikieEventType = (typeof HIKIE_EVENT_TYPES)[number];

export interface HikieOrder {
  orderId: string;
  status: string;
  /** Yalnızca `order.updated`'da var. */
  previousStatus?: string | null;
  /** Yalnızca `order.shipmentUpdated`'da var. */
  shipmentStatus?: string;
  previousShipmentStatus?: string | null;
  storeSlug: string | null;
  dateCreated: string | null;
  currency: string;
  totals: { subtotal: string; shipping: string; discount: string; total: string };
  discounts: Array<{ discountId: string | null; code: string; amount: string | null }>;
  customerInfo: {
    firstName: string | null;
    lastName: string | null;
    email: string | null;
    phone: string | null;
    address: string | null;
    district: string | null;
    city: string | null;
    state: string | null;
    postcode: string | null;
    country: string | null;
  } | null;
  billingInfo: Record<string, 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;
    isUpsell: boolean;
    stockQuantity: number | null;
  }>;
  /** Yalnızca `order.paid`'de var. */
  isLink?: boolean;
  attribution: Record<string, string> | null;
  /** `order.updated`'da yok. */
  cargo?: {
    company: string | null;
    trackingNumber: string | null;
    trackingUrl: string | null;
    status: string;
    fulfilledAt: string | null;
    deliveredAt: string | null;
  } | null;
}

/** Kuyruğa yazdığımız iş: başlıklardan gelen metadata + gövdedeki model. */
export interface HikieJob {
  eventType: HikieEventType;
  webhookId: string;
  occurredAt: string;
  payload: Record<string, unknown>;
}

4. Controller

src/hikie/hikie.controller.ts
import {
  Body,
  Controller,
  Headers,
  HttpCode,
  Logger,
  Post,
  ServiceUnavailableException,
  UseGuards,
} from '@nestjs/common';
import { HikieSignatureGuard } from './hikie-signature.guard';
import { HikieService } from './hikie.service';
import type { HikieJob } from './hikie-event.types';

@Controller('hikie')
export class HikieController {
  private readonly logger = new Logger(HikieController.name);

  constructor(private readonly hikieService: HikieService) {}

  @Post('webhook')
  @HttpCode(200)
  @UseGuards(HikieSignatureGuard)
  async receive(
    // Gövde zarfsız: doğrudan event modeli
    @Body() payload: Record<string, unknown>,
    @Headers('hikie-event') eventType: string,
    @Headers('hikie-webhook-id') webhookId: string,
    @Headers('hikie-occurred-at') occurredAt: string,
    @Headers('hikie-delivery-attempt') attempt: string,
  ): Promise<void> {
    // Tekrar koruması
    if (await this.hikieService.alreadyProcessed(webhookId)) {
      this.logger.log(`${webhookId} zaten işlendi (deneme ${attempt})`);
      return;
    }

    try {
      // Kalıcı bir yere yaz ve hemen dön — ağır iş worker'da.
      await this.hikieService.enqueue({
        eventType: eventType as any,
        webhookId,
        occurredAt,
        payload,
      });
    } catch (error) {
      // 503 geçici hatadır; Hikie yeniden dener.
      this.logger.error(`Kuyruğa yazılamadı: ${String(error)}`);
      throw new ServiceUnavailableException();
    }
  }
}

@HttpCode(200) olmadan NestJS POST için varsayılan 201 döner. 201 de 2xx olduğu için başarı sayılır — ama açıkça belirtmek niyeti netleştirir.

5. Servis ve kuyruk

src/hikie/hikie.service.ts
import { InjectQueue } from '@nestjs/bullmq';
import { Injectable } from '@nestjs/common';
import { Queue } from 'bullmq';
import type { HikieJob } from './hikie-event.types';

@Injectable()
export class HikieService {
  constructor(
    @InjectQueue('hikie-events') private readonly queue: Queue,
  ) {}

  /**
   * BullMQ'nun jobId çakışma davranışını tekrar filtresi olarak kullanıyoruz:
   * aynı webhookId ile ikinci kez eklenen iş kuyruğa girmez.
   *
   * Bu tek başına yeterli değil — tamamlanmış işler kuyruktan temizlendikten
   * sonra aynı kimlik yeniden kabul edilir. Kalıcı bir kayıt için
   * `alreadyProcessed` uygulamasına bakın.
   */
  async enqueue(job: HikieJob): Promise<void> {
    await this.queue.add('handle', job, {
      jobId: job.webhookId,
      attempts: 5,
      backoff: { type: 'exponential', delay: 5_000 },
      removeOnComplete: 1_000,
      removeOnFail: 5_000,
    });
  }

  async alreadyProcessed(webhookId: string): Promise<boolean> {
    const existing = await this.queue.getJob(webhookId);
    return existing !== undefined;
  }
}

6. Worker

src/hikie/hikie.processor.ts
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import type { HikieJob, HikieOrder } from './hikie-event.types';

@Processor('hikie-events')
export class HikieProcessor extends WorkerHost {
  private readonly logger = new Logger(HikieProcessor.name);

  async process(job: Job<HikieJob>): Promise<void> {
    const { eventType, payload } = job.data;

    switch (eventType) {
      case 'order.paid':
        return this.grantPurchase(payload as unknown as HikieOrder);

      case 'order.updated':
        return this.applyOrderStatus(payload as unknown as HikieOrder);

      case 'order.shipmentUpdated':
        return this.updateShipmentStatus(payload as unknown as HikieOrder);

      case 'test.ping':
        this.logger.log('Hikie test bağlantısı başarılı');
        return;

      default:
        // Bilinmeyen tip hata değil — katalog genişleyebilir.
        this.logger.log(`İşlenmeyen event: ${eventType}`);
    }
  }

  private async grantPurchase(order: HikieOrder): Promise<void> {
    for (const item of order.items) {
      await this.rcon(
        `givepackage "${order.customerInfo?.email}" "${item.variant?.name ?? item.title}"`,
      );
    }
  }

  // … diğer işleyiciler
}

7. Modül

src/hikie/hikie.module.ts
import { BullModule } from '@nestjs/bullmq';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { HikieController } from './hikie.controller';
import { HikieProcessor } from './hikie.processor';
import { HikieService } from './hikie.service';

@Module({
  imports: [
    ConfigModule,
    BullModule.registerQueue({ name: 'hikie-events' }),
  ],
  controllers: [HikieController],
  providers: [HikieService, HikieProcessor],
})
export class HikieModule {}
main.ts
app.module.ts
hikie.module.ts
hikie.controller.ts
hikie.service.ts
hikie.processor.ts
hikie-signature.guard.ts
hikie-event.types.ts

Fastify adaptörü kullanıyorsanız

@nestjs/platform-fastify ile rawBody: true yine çalışır:

src/main.ts
import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
    { rawBody: true },
  );

  await app.listen(3000, '0.0.0.0');
}

void bootstrap();

Guard'daki RawBodyRequest<Request> tipini Fastify'a çevirmeniz yeterli:

import type { FastifyRequest } from 'fastify';

const request = context.switchToHttp().getRequest<RawBodyRequest<FastifyRequest>>();

Sonraki adımlar

Bu sayfada