Verify SMS webhook signatures in Node.js: Twilio, Telnyx, Plivo, and Vonage
Verify Twilio, Telnyx, Plivo, Vonage, Bandwidth, and Sinch SMS webhooks in Node.js: each provider's signature scheme, a dependency-free X-Twilio-Signature check, and the fix for proxy URL mismatches.
Your SMS webhook URL is public, so anyone can post a fake “delivered” or “STOP” to it. parseSmsWebhook() checks the provider’s signature or credentials before it reads any field, and throws WebhookSignatureError if the request is not authentic. The most common failure is a URL mismatch behind a proxy, covered below.
Respond to failures
import { parseSmsWebhook, WebhookPayloadError, WebhookSignatureError } from "@opencoredev/sms-sdk/webhooks";
export async function POST(request: Request): Promise<Response> {
try {
const event = await parseSmsWebhook({
provider: "vonage",
request,
credentials: { signatureSecret: process.env.VONAGE_SIGNATURE_SECRET ?? "" },
});
console.log(event.type);
return new Response(null, { status: 200 });
} catch (error) {
if (error instanceof WebhookSignatureError) {
console.warn("Rejected webhook", error.providerName, error.reason);
return new Response("Invalid signature", { status: 401 });
}
if (error instanceof WebhookPayloadError) {
if (error.reason === "body_too_large") {
return new Response("Payload too large", { status: 413 });
}
return new Response("Unexpected payload", { status: 400 });
}
throw error;
}
}
WebhookSignatureError.reason says what failed:
reason |
Meaning |
|---|---|
missing_signature |
The signature or Authorization header, or the Plivo nonce, is absent. |
invalid_signature |
The signature or Basic credentials do not match. Usually a wrong credential or a URL mismatch. |
stale_timestamp |
The Telnyx, Vonage, or Sinch HMAC signed time is more than toleranceSec (default 300) from now. |
body_hash_mismatch |
Twilio bodySHA256 or Vonage payload_hash does not match the body. |
malformed_signature |
The signature, token, or timestamp cannot be decoded. |
invalid_credentials |
The credential you passed is malformed, such as a Telnyx public key that is not 32 bytes of base64. |
WebhookPayloadError means the request body exceeded the 1 MiB limit (error.reason === "body_too_large", checked before signature verification so oversized bodies are never buffered; respond with 413), the request body stream failed or aborted while reading (error.reason === "body_unreadable"; respond with 400), or the request was authentic but lacks required fields (respond with 400).
How each provider signs
| Provider | Credential | Scheme | Replay window |
|---|---|---|---|
| Twilio | { authToken } |
X-Twilio-Signature: Base64 HMAC-SHA1 of the URL plus sorted form parameters. For JSON bodies, the URL carries bodySHA256 and only the URL is signed. |
None |
| Telnyx | { publicKey } |
telnyx-signature-ed25519: Ed25519 over `` `${telnyx-timestamp} |
${rawBody}` ``. |
| Plivo | { authToken } |
X-Plivo-Signature-V2 (or X-Plivo-Signature-Ma-V2): Base64 HMAC-SHA256 of the URL without its query string plus X-Plivo-Signature-V2-Nonce. The form parameters are not signed. |
None |
| Vonage | { signatureSecret } |
Authorization: Bearer <JWT>, HS256 with the signature secret. payload_hash, when present, is the SHA-256 of the body. |
toleranceSec on the JWT iat, default 300 |
| Bandwidth | { username, password } |
No signature. Authorization: Basic must match the callback credentials set on your Bandwidth application. |
None |
| Sinch | { kind: "basic", username, password } or { kind: "hmac", webhookSecret } |
Basic: Authorization: Basic must match the credentials on your callback URL. HMAC: Base64 HMAC-SHA256 of body.nonce.timestamp in x-sinch-webhook-signature. Sinch does not publish this format for SMS; see Sinch. |
HMAC: toleranceSec, default 300. Basic: none. |
Where to find each credential:
- Twilio: the Auth Token of the account that owns the number. API keys cannot verify webhooks.
- Telnyx: the base64 public key in Mission Control, under Keys & Credentials.
- Plivo: the Auth Token of the account or subaccount.
X-Plivo-Signature-Ma-V2is signed with the main account’s token. - Vonage: the signature secret in the dashboard settings for the API key that signs your webhooks.
- Bandwidth: the callback username and password you set on the messaging application.
- Sinch: the Basic credentials on your callback URL, or the HMAC secret your Sinch account manager set up.
Twilio, Plivo, Bandwidth, and Sinch with Basic auth sign no timestamp, so someone who captures a real request can send it again. Deduplicating on dedupeKey makes a replay harmless. See Receive webhooks.
Verify Twilio and Telnyx signatures by hand
To check a Twilio webhook in Node.js, compute a Base64 HMAC-SHA1 of the full URL Twilio called followed by every POST parameter’s name and value, sorted by name, keyed with your Auth Token, and compare it to X-Twilio-Signature in constant time. To check a Telnyx webhook, verify the Ed25519 signature in telnyx-signature-ed25519 over `${telnyx-timestamp}|${rawBody}` with your Telnyx public key, and reject timestamps older than a few minutes.
If you already use the twilio npm package, its validateRequest(authToken, signature, url, params) runs the same check for a form POST, and twilio.webhook() wraps it as Express middleware. parseSmsWebhook() does the check for every supported provider. If you only need the check, for example in middleware for an app that doesn’t use SMS SDK, this is the whole thing with no dependencies, in Node.js 20 or later and Bun:
import { createHmac, timingSafeEqual } from "node:crypto";
// Twilio: Base64 HMAC-SHA1 keyed with your Auth Token, over the full URL
// Twilio called plus each POST parameter's name and value, sorted by name,
// then by value. Every value is signed, so a repeated field added in transit
// fails the check.
export function isValidTwilioSignature(
authToken: string,
url: string,
params: URLSearchParams,
signature: string,
): boolean {
const pairs = [...params].sort(([nameA, valueA], [nameB, valueB]) =>
nameA === nameB ? (valueA < valueB ? -1 : valueA > valueB ? 1 : 0) : nameA < nameB ? -1 : 1,
);
const data = pairs.reduce((signed, [name, value]) => signed + name + value, url);
const expected = Buffer.from(createHmac("sha1", authToken).update(data).digest("base64"));
const received = Buffer.from(signature);
return expected.length === received.length && timingSafeEqual(expected, received);
}
// Telnyx: Ed25519 over `${timestamp}|${rawBody}`, checked with the base64
// public key from Mission Control. Old timestamps are refused, so a captured
// request can't be replayed later. Malformed input returns false, never throws.
export async function isValidTelnyxSignature(
publicKey: string,
rawBody: string,
signature: string,
timestamp: string,
): Promise<boolean> {
const ageSec = Math.abs(Date.now() / 1000 - Number(timestamp));
if (!/^\d+$/.test(timestamp) || ageSec > 300) return false;
try {
const bytes = (base64: string) => Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
const keyBytes = bytes(publicKey);
const signatureBytes = bytes(signature);
if (keyBytes.length !== 32 || signatureBytes.length !== 64) return false;
const key = await crypto.subtle.importKey("raw", keyBytes, "Ed25519", false, ["verify"]);
const signed = new TextEncoder().encode(`${timestamp}|${rawBody}`);
return await crypto.subtle.verify("Ed25519", key, signatureBytes, signed);
} catch {
return false;
}
}
Pass the URL exactly as configured in Twilio, including any query string (see below), and the raw body for Telnyx before anything parses it. This handles Twilio’s form-encoded webhooks. A JSON body from Twilio carries bodySHA256 in the URL instead, and parseSmsWebhook() checks both. SMS SDK’s own Twilio check also tries the URL with and without the default port, which the snippet does not. For the same checks wired into a Next.js route with offline tests, see the Twilio, Telnyx, and Vonage guides.
Fix URL mismatches behind a proxy
Twilio and Plivo sign the exact URL they called, such as https://example.com/webhooks/sms/twilio. Behind a load balancer, tunnel, or platform proxy, your app often sees another URL, such as http://10.0.0.5:3000/webhooks/sms/twilio, and verification fails with invalid_signature.
Pass the public URL exactly as configured with the provider:
import { parseSmsWebhook } from "@opencoredev/sms-sdk/webhooks";
export async function POST(request: Request): Promise<Response> {
const event = await parseSmsWebhook({
provider: "twilio",
request,
publicUrl: "https://example.com/webhooks/sms/twilio",
credentials: { authToken: process.env.TWILIO_AUTH_TOKEN ?? "" },
});
console.log(event.type);
return new Response(null, { status: 200 });
}
If publicUrl has no query string, SMS SDK appends the request’s, so Twilio’s bodySHA256 and any parameters you added still verify. For Twilio it also tries the URL with and without the default port, :443 or :80.
The alternative is trustProxy: true, which builds the URL from X-Forwarded-Proto and X-Forwarded-Host. Use it only when a proxy you control sets those headers and strips any a client sent; otherwise anyone can forge them. With neither option, SMS SDK uses request.url and ignores forwarded headers.
The other providers do not sign the URL, so these options exist only for Twilio and Plivo.
The raw body
Signatures cover the raw bytes, so parseSmsWebhook() reads the body stream once up to 1 MiB. Do not read or parse the body before calling it, and do not let a framework body parser consume it first. In Express and similar frameworks, convert the incoming request to a web Request with the raw body.
Skipping verification in tests
unsafeSkipVerification: true parses without checking anything. Use it only in unit tests. It throws ConfigurationError when process.env.NODE_ENV is "production", so a test setting that leaks into a deployment fails loudly instead of accepting forged events. The signed request builders in @opencoredev/sms-sdk/testing are better, because they exercise the real verification path. See Test without a provider.
Lower-level helpers
To verify without parsing, for example in middleware, /webhooks exports verifyTwilioSignature, verifyTelnyxSignature, verifyPlivoSignatureV2, verifyVonageSignature, and verifySinchSignature, plus computeTwilioSignature and computePlivoSignatureV2. See Webhook events.