# Verify Delivery Report Webhooks
URL: /docs/recipes/verify-webhooks

> Extract raw request bodies, parse X-SmsPro-Signature headers, enforce 300s replay protection, and validate HMAC-SHA256 in constant time.

Difficulty: Intermediate | Duration: 8 min | Language: TypeScript

## Step 1: Read the Raw Unparsed HTTP Body (`src/app/api/webhooks/smspro/route.ts`)

Always capture the raw HTTP payload string with `await request.text()` before parsing JSON. Any whitespace normalization or key re-ordering from `JSON.stringify(await request.json())` invalidates the cryptographic signature.

```typescript
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  // CRITICAL: Read raw text bytes before JSON.parse().
  // Re-serializing parsed JSON changes whitespace/key ordering and breaks HMAC.
  const rawBody = await request.text();
  const signatureHeader = request.headers.get('x-smspro-signature');

  if (!rawBody || !signatureHeader) {
    return NextResponse.json(
      { error: 'Missing webhook payload or X-SmsPro-Signature header' },
      { status: 400 },
    );
  }

  // Verification proceeds in Steps 2-4...
  return NextResponse.json({ received: true });
}
```

## Step 2: Parse X-SmsPro-Signature & Replay Window (`src/lib/verify-smspro-webhook.ts`)

= {};

  for (const segment of header.split(',')) {
    const idx = segment.indexOf('=');
    if (idx === -1) continue;
    const key = segment.slice(0, idx).trim().toLowerCase();
    const val = segment.slice(idx + 1).trim();
    if (key && val) parts[key] = val;
  }

  if (!parts.t || !parts.v1) return null;

  const rawTs = Number(parts.t);
  if (!Number.isFinite(rawTs)) return null;

  // Normalize milliseconds to seconds if necessary
  const tsSeconds = rawTs > 1_000_000_000_000 ? Math.floor(rawTs / 1000) : rawTs;
  const nowSeconds = Math.floor(Date.now() / 1000);

  if (Math.abs(nowSeconds - tsSeconds) > REPLAY_TOLERANCE_SECONDS) {
    return null;
  }

  return { timestamp: parts.t, v1: parts.v1.toLowerCase() };
}`}
  >
    Extract `t` (Unix timestamp) and `v1` (64-character lowercase hex digest) from `X-SmsPro-Signature: t=...,v1=...`. Reject payloads older or newer than `300` seconds to block replay attacks.

## Step 3: Compute HMAC-SHA256 & Constant-Time Check (`src/lib/verify-smspro-webhook.ts`)

.<rawBody>"
  const signedPayload = \`\${parsed.timestamp}.\${rawBody}\`;
  const computedHex = createHmac('sha256', webhookSecret.trim())
    .update(signedPayload, 'utf8')
    .digest('hex');

  const computedBuf = Buffer.from(computedHex, 'utf8');
  const expectedBuf = Buffer.from(parsed.v1, 'utf8');

  if (computedBuf.length !== expectedBuf.length) {
    return false;
  }

  return timingSafeEqual(computedBuf, expectedBuf);
}`}
  >
    Compute `HMAC-SHA256` over `` `${timestamp}.${rawBody}` `` using your `whsec_...` signing secret, check equal buffer lengths, and compare with `crypto.timingSafeEqual()` to prevent timing side-channel leaks.

## Step 4: Process Event & Acknowledge 200 OK (`src/app/api/webhooks/smspro/route.ts`)

Return `401 Unauthorized` on invalid or expired signatures. Once verified, parse the JSON event, enqueue downstream database or alert updates, and respond immediately with `200 OK`.

```typescript
import { NextRequest, NextResponse } from 'next/server';
import { verifySmsProSignature } from '@/lib/verify-smspro-webhook';

interface DeliveryEvent {
  messageId: string;
  providerMessageId: string;
  to: string;
  status: string;
  deliveredAt: string;
  gateway: string;
  raw: string;
}

export async function POST(request: NextRequest) {
  const rawBody = await request.text();
  const signature = request.headers.get('x-smspro-signature') ?? '';
  const secret = process.env.SMSPRO_WEBHOOK_SECRET ?? '';

  if (!verifySmsProSignature(rawBody, signature, secret)) {
    return NextResponse.json(
      { error: 'Invalid or expired webhook signature' },
      { status: 401 },
    );
  }

  const payload = JSON.parse(rawBody) as DeliveryEvent;

  // Dispatch to background queue so HTTP 200 returns well under 5 seconds
  console.info('Verified SMS Pro delivery:', payload.messageId, payload.status);

  return NextResponse.json({ status: 'received' }, { status: 200 });
}
```