Skip to main content
TRUSTORYX.
एंटरप्राइझ आर्किटेक्चर मार्गदर्शक

एंटरप्राइझ एपीआय आणि वेबहुक एकत्रीकरण नियोजन मार्गदर्शक

वितरित, त्रुटी-सहिष्णु एपीआय एकत्रीकरण तयार करणाऱ्या आर्किटेक्ट्ससाठी सर्वसमावेशक मार्गदर्शक. क्रिप्टोग्राफिक HMAC, रेडिस आयडेमपोटेन्सी आणि डेड-लेटर रांगा.

सुरक्षित क्रिप्टोग्राफी डिस्ट्रिब्युटेड आयडेमपोटेन्सी n8n आणि Node.js पॅटर्न

१. HMAC SHA-256 स्वाक्षरी

अनधिकृत वेबहुक्सवर विश्वास ठेवू नका. टाइमिंग हल्ले टाळण्यासाठी टाइमिंग-सेफ तुलनेचा वापर करून पेलोड सत्यापित करा.

२. डिस्ट्रिब्युटेड आयडेमपोटेन्सी

Redis SETNX लॉक्स डुप्लिकेट पेमेंट आणि डेटाबेस त्रुटी रोखतात.

३. असिंक्रोनस डीकपलिंग

नेहमी HTTP 202 Accepted सह त्वरित पावती द्या. गेटवे टाइमआउट टाळण्यासाठी बॅकग्राउंड रांगेत काम पाठवा.

// Next.js 16 App Router: Idempotent Webhook Consumer with Timing-Safe HMAC
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

const WEBHOOK_SECRET = process.env.STRIPE_OR_PARTNER_SECRET!;

export async function POST(req: NextRequest) {
  try {
    const rawBody = await req.text();
    const signature = req.headers.get('x-signature') || '';
    const idempotencyKey = req.headers.get('idempotency-key');

    if (!idempotencyKey) {
      return NextResponse.json({ error: 'Missing Idempotency-Key header' }, { status: 400 });
    }

    // 1. Timing-Safe HMAC Verification
    const expectedSig = crypto
      .createHmac('sha256', WEBHOOK_SECRET)
      .update(rawBody)
      .digest('hex');

    const isValid = crypto.timingSafeEqual(
      Buffer.from(signature, 'hex'),
      Buffer.from(expectedSig, 'hex')
    );

    if (!isValid) {
      return NextResponse.json({ error: 'Invalid HMAC Signature' }, { status: 401 });
    }

    // 2. Distributed Redis Idempotency Check (Atomic SETNX with 24h TTL)
    // const isNew = await redis.set(`idempotency:${idempotencyKey}`, 'processing', 'EX', 86400, 'NX');
    // if (!isNew) return NextResponse.json({ status: 'already_processed' }, { status: 200 });

    // 3. Immediately acknowledge HTTP 202 and push to background worker queue
    // await jobQueue.add('process_event', { payload: JSON.parse(rawBody) });

    return NextResponse.json({ received: true, status: 'queued' }, { status: 202 });
  } catch (error) {
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
  }
}
एंटरप्राइझ इंटिग्रेशन अभियांत्रिकी हवी आहे?

तुमची सीआरएम, ईआरपी आणि एआय सिस्टीम त्रुटींशिवाय जोडा

Trustoryx मजबूत API पाइपलाइन आणि सेल्फ-होस्टेड n8n वर्कफ्लो तयार करते.