Verifying signatures
Verify the Nurishd-Signature header on every webhook delivery, with working Node, Python and PHP code, and roll a signing secret safely.
You will verify that a webhook delivery came from Nurish'd and was not changed or replayed, and you will roll a signing secret without missing events.
The header#
Every delivery carries one header.
Nurishd-Signature: t=1764515045,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bdtis the Unix time in seconds when Nurish'd signed the delivery.v1is the hex HMAC-SHA256 of the string<t>.<raw body>, using the endpoint's signing secret as the key. The body is the compact JSON of the event, exactly as sent.- After you roll a secret, the header carries two
v1=values for 24 hours, one per secret:
Nurishd-Signature: t=1764515045,v1=<new secret hex>,v1=<old secret hex>Steps#
- Read the raw request body as bytes or an exact string. Do not parse and re-serialize it. Any change to the bytes breaks the signature.
- Read the
Nurishd-Signatureheader. Split it on,, then each part on the first=. Taketand collect everyv1. - Reject the delivery if
tis more than five minutes old. The code below also rejects atmore than five minutes in the future. This stops replays. - Compute the HMAC-SHA256 of
t + "." + raw bodywith your signing secret, as hex. - Compare it to each
v1with a constant-time comparison. Accept if any one matches. - Only then parse the body as JSON.
Answer with a failure status (400) when verification fails, and do not process the body. A 2xx is success, anything else is retried, and redirects are not followed. See Webhooks.
The request carries User-Agent: Nurishd-Connect-Webhooks/1.0. Do not trust a request by its User-Agent: only the signature proves who sent it.
Node#
This uses only the standard library. With Express, read the raw body with express.raw({ type: "application/json" }).
import crypto from 'node:crypto';
const TOLERANCE_SECONDS = 300;
/**
* @param {Buffer | string} rawBody the exact bytes received
* @param {string | undefined} header the Nurishd-Signature header
* @param {string} secret the signing secret, starting with nk-whsec-
* @returns {boolean}
*/
export function verifySignature(rawBody, header, secret) {
if (!header) return false;
let timestamp = null;
const signatures = [];
for (const part of header.split(',')) {
const index = part.indexOf('=');
if (index === -1) continue;
const key = part.slice(0, index).trim();
const value = part.slice(index + 1).trim();
if (key === 't') timestamp = value;
if (key === 'v1') signatures.push(value);
}
if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0)
return false;
const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
if (age > TOLERANCE_SECONDS) return false;
const body = Buffer.isBuffer(rawBody)
? rawBody
: Buffer.from(rawBody, 'utf8');
const expected = crypto
.createHmac('sha256', secret)
.update(Buffer.concat([Buffer.from(`${timestamp}.`, 'utf8'), body]))
.digest();
return signatures.some((signature) => {
if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
const received = Buffer.from(signature, 'hex');
return (
received.length === expected.length &&
crypto.timingSafeEqual(received, expected)
);
});
}import express from 'express';
import { verifySignature } from './verify-signature.js';
const app = express();
app.post('/nurishd', express.raw({ type: 'application/json' }), (req, res) => {
const ok = verifySignature(
req.body,
req.get('Nurishd-Signature'),
process.env.NURISHD_WEBHOOK_SECRET,
);
if (!ok) return res.sendStatus(400);
const event = JSON.parse(req.body.toString('utf8'));
// Handle by event.id so a repeated delivery does no harm.
res.sendStatus(200);
});Python#
import hashlib
import hmac
import time
TOLERANCE_SECONDS = 300
def verify_signature(raw_body: bytes, header: str | None, secret: str) -> bool:
"""Return True if the delivery is genuine and fresh.
raw_body is the exact bytes received. header is the Nurishd-Signature value.
"""
if not header:
return False
timestamp = None
signatures = []
for part in header.split(","):
key, sep, value = part.partition("=")
if not sep:
continue
key, value = key.strip(), value.strip()
if key == "t":
timestamp = value
elif key == "v1":
signatures.append(value)
if timestamp is None or not timestamp.isdigit() or not signatures:
return False
if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
return False
expected = hmac.new(
secret.encode("utf-8"),
timestamp.encode("utf-8") + b"." + raw_body,
hashlib.sha256,
).hexdigest()
return any(hmac.compare_digest(expected, signature.lower()) for signature in signatures)With Flask, use request.get_data() for the raw body.
import os
from flask import Flask, request
app = Flask(__name__)
@app.post("/nurishd")
def nurishd():
ok = verify_signature(
request.get_data(),
request.headers.get("Nurishd-Signature"),
os.environ["NURISHD_WEBHOOK_SECRET"],
)
if not ok:
return "", 400
event = request.get_json()
# Handle by event["id"] so a repeated delivery does no harm.
return "", 200PHP#
<?php
const TOLERANCE_SECONDS = 300;
/**
* Return true if the delivery is genuine and fresh.
*
* @param string $rawBody the exact body received
* @param string|null $header the Nurishd-Signature header
* @param string $secret the signing secret, starting with nk-whsec-
*/
function verify_signature(string $rawBody, ?string $header, string $secret): bool
{
if ($header === null || $header === '') {
return false;
}
$timestamp = null;
$signatures = [];
foreach (explode(',', $header) as $part) {
$pair = explode('=', $part, 2);
if (count($pair) !== 2) {
continue;
}
$key = trim($pair[0]);
$value = trim($pair[1]);
if ($key === 't') {
$timestamp = $value;
} elseif ($key === 'v1') {
$signatures[] = $value;
}
}
if ($timestamp === null || !ctype_digit($timestamp) || count($signatures) === 0) {
return false;
}
if (abs(time() - (int) $timestamp) > TOLERANCE_SECONDS) {
return false;
}
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
foreach ($signatures as $signature) {
if (hash_equals($expected, strtolower($signature))) {
return true;
}
}
return false;
}
$rawBody = file_get_contents('php://input');
$header = $_SERVER['HTTP_NURISHD_SIGNATURE'] ?? null;
if (!verify_signature($rawBody, $header, getenv('NURISHD_WEBHOOK_SECRET'))) {
http_response_code(400);
exit;
}
$event = json_decode($rawBody, true);
// Handle by $event['id'] so a repeated delivery does no harm.
http_response_code(200);Test your check#
- In the console, select Send test event on your endpoint. Nurish'd sends a signed
ping. - Confirm your code accepts it.
- Change one byte of the body and confirm it fails.
- Change
tto a time six minutes old and confirm it fails.
Roll a secret#
Roll a secret when it may have leaked, or on a schedule. Rolling keeps the old secret valid for 24 hours, so you do not miss events.
- Roll the secret in the console, or call
PUT /developer/v1/webhook-endpoint/{endpoint_id}/secret/roll/document. The answer holds the new secret insecret, andendpoint.previous_secret_expires_atsays when the old one stops working. - For 24 hours, each delivery carries two
v1=values. The code above accepts a delivery if either matches. - Deploy the new secret. While you do, deliveries verify with either secret.
- After
previous_secret_expires_at, only the new secret is valid.
curl -X PUT https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/whe-01JD2ZQ4M8K7R5T3V9X1B6C0HN/secret/roll/document \
-H "X-Partner-API-Key: $NURISHD_API_KEY"const res = await fetch(
'https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/whe-01JD2ZQ4M8K7R5T3V9X1B6C0HN/secret/roll/document',
{
method: 'PUT',
headers: { 'X-Partner-API-Key': process.env.NURISHD_API_KEY },
},
);
const { endpoint, secret } = await res.json();import os
import requests
res = requests.put(
"https://api.dev.nurishd.ca/developer/v1/webhook-endpoint/whe-01JD2ZQ4M8K7R5T3V9X1B6C0HN/secret/roll/document",
headers={"X-Partner-API-Key": os.environ["NURISHD_API_KEY"]},
)
body = res.json()
secret = body["secret"]Your code needs one secret per endpoint. If you receive from several endpoints, look up the secret by endpoint.
Next#
Something wrong on this page? Email hello@nurishd.io with the page address.