Verify SMS webhook HMAC-SHA256 signatures
How to confirm the request really came from DroidSender and not from someone else.
Last updated
| Header | What it holds |
|---|---|
| X-DroidSender-Event | the event name, the same one in the body |
| X-DroidSender-Delivery | identifies one delivery attempt; to deduplicate, use event plus data.id (plus data.status for sent, delivered and failed) |
| X-DroidSender-Signature | the signature, described below |
| User-Agent | DroidSender-Webhooks/2.0 |
Every request carries the X-DroidSender-Signature header in the form t=<unix seconds>,v1=<hex>, where v1 is the HMAC-SHA256 of "<t>.<raw body>" using your webhook's secret.
const crypto = require("crypto");
function signatureIsValid(rawBody, header, secret) {
const match = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(header ?? "");
if (!match) return false;
const [, t, received] = match;
// the timestamp is inside what is signed: an intercepted delivery
// cannot be replayed tomorrow, and t cannot be rewritten without the secret
const age = Math.abs(Math.floor(Date.now() / 1000) - Number(t));
if (age > 300) return false;
const expected = crypto
.createHmac("sha256", secret)
.update(`${t}.${rawBody}`)
.digest("hex");
// constant-time comparison: a plain === lets the secret be measured
return crypto.timingSafeEqual(
Buffer.from(expected, "hex"),
Buffer.from(received, "hex"),
);
}import hmac, hashlib, re, time
def signature_is_valid(raw_body: bytes, header: str, secret: str) -> bool:
m = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", header or "")
if not m:
return False
t, received = m.group(1), m.group(2)
if abs(int(time.time()) - int(t)) > 300:
return False
expected = hmac.new(
secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, received)<?php
function signature_is_valid(string $rawBody, ?string $header, string $secret): bool {
if (!preg_match('/^t=(\d+),v1=([0-9a-f]{64})$/', $header ?? '', $m)) {
return false;
}
[, $t, $received] = $m;
if (abs(time() - (int) $t) > 300) {
return false;
}
$expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
// hash_equals, never ==: a normal comparison leaks timing
return hash_equals($expected, $received);
}
// the raw body comes from php://input; $_POST is already parsed and useless here
$rawBody = file_get_contents('php://input');
$header = $_SERVER['HTTP_X_DROIDSENDER_SIGNATURE'] ?? null;