Verify Delivery Report Webhooks
Extract raw request bodies, parse X-SmsPro-Signature headers, enforce 300s replay protection, and validate HMAC-SHA256 in constant time.
SMS Pro signs the raw delivery JSON with HMAC-SHA256 in X-SmsPro-Signature. Walk through a Next.js Route Handler that checks that header before you read status.
Webhook Signature Verification (Next.js App Router)
Click any step or scroll down the narrative to inspect the exact TypeScript verification handler.
Read the Raw Unparsed HTTP Body
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.
src/app/api/webhooks/smspro/route.ts
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 });}Parse X-SmsPro-Signature & Replay Window
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.
src/lib/verify-smspro-webhook.ts
const REPLAY_TOLERANCE_SECONDS = 300; // 5-minute windowexport interface ParsedSignature {timestamp: string;v1: string;}export function parseSignatureHeader(header: string): ParsedSignature | null {const parts: Record<string, string> = {};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 necessaryconst 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() };}Compute HMAC-SHA256 & Constant-Time Check
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.
src/lib/verify-smspro-webhook.ts
import { createHmac, timingSafeEqual } from 'node:crypto';import { parseSignatureHeader } from './parse-signature';export function verifySmsProSignature(rawBody: string,signatureHeader: string,webhookSecret: string,): boolean {const parsed = parseSignatureHeader(signatureHeader);if (!parsed || !webhookSecret.trim()) { return false;}// Canonical signed string: "<timestamp>.<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);}Process Event & Acknowledge 200 OK
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.
src/app/api/webhooks/smspro/route.ts
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 secondsconsole.info('Verified SMS Pro delivery:', payload.messageId, payload.status);return NextResponse.json({ status: 'received' }, { status: 200 });}Send Bulk SMS with CSV Streaming & Batch Progress
Ingest high-volume CSV contact lists without memory leaks, dispatch chunked batch jobs, and poll asynchronous campaign completion.
Zero-Knowledge OTP Verification (v2)
Issue 128-bit single-use challenge nonces, derive SHA-256 codeProof digests, verify OTPs without transmitting raw PINs, and handle failover.