Verify Signatures
Anyone who knows your URL can send a request to it. Verify the signature of each request before you trust it.
Volt signs events as the Standard Webhooks specification describes, so you can use one of its libraries or a few lines of your own code.
With a library
import { Webhook } from 'standardwebhooks'
const webhook = new Webhook(process.env.VOLT_WEBHOOK_SECRET) // whsec_...
app.post('/volt', express.raw({ type: 'application/json' }), (req, res) => {
let event
try {
event = webhook.verify(req.body, req.headers)
} catch {
return res.sendStatus(401)
}
res.sendStatus(200)
// Use the event here.
})Pass the raw body, exactly as it arrived. A body that was parsed and serialized again does not match the signature.
By hand
- Take the part of your secret after
whsec_and decode it from base64. This is the key. - Build the signed content:
{webhook-id}.{webhook-timestamp}.{raw body}. - Calculate the HMAC-SHA256 of the signed content with the key, and encode it in base64.
- Compare it with the value after
v1,in thewebhook-signatureheader. Use a constant-time comparison. - Reject the request if
webhook-timestampis more than five minutes away from the current time.
import base64, hashlib, hmac, time
def verify(secret: str, headers: dict, body: bytes) -> bool:
key = base64.b64decode(secret.removeprefix("whsec_"))
event_id = headers["webhook-id"]
timestamp = headers["webhook-timestamp"]
if abs(time.time() - int(timestamp)) > 300:
return False
signed = f"{event_id}.{timestamp}.".encode() + body
expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
# The header can hold more than one signature, separated by spaces.
for part in headers["webhook-signature"].split(" "):
scheme, _, signature = part.partition(",")
if scheme == "v1" and hmac.compare_digest(signature, expected):
return True
return FalseKeep the secret safe
- Each endpoint has its own secret. Volt shows it once, when you add the endpoint.
- Store it as a secret on your server. Do not put it in client code or in a repository.
- If a secret leaks, delete the endpoint and add it again to get a new one.