Verify signatures
Check that a webhook really comes from Chatwise, with samples in Node.js and Python.
Anyone can send a request to your URL. The signature proves that it comes from Chatwise, that nobody changed it and that it isn't an old one sent again.
Chatwise signs the way Standard Webhooks does, so the libraries of that project can verify it too. The samples below need no library.
How it is signed
- The key is your signing secret without
whsec_, decoded from base64. - The signed text is the
webhook-idheader, a dot, thewebhook-timestampheader, a dot, and the raw body. - The signature is
v1,and the base64 of the HMAC-SHA256 of that text. webhook-signatureholds one signature, or two with a space between them while a secret is rotated.
To verify a request:
- Use the raw body, byte for byte. Parsing the JSON and writing it again can change it, and then no signature matches.
- Refuse old timestamps. The timestamp is signed, and it is new on every attempt, so a request that is more than five minutes old isn't a retry.
- Accept any matching signature, and compare in constant time.
- Limit what you read. Until the signature is checked, the request can be from anyone. An event is at most 256 KiB.
- Answer 400 when nothing matches.
Verify
import { createHmac, timingSafeEqual } from "node:crypto";
const FIVE_MINUTES = 5 * 60;
// rawBody is the request body exactly as received (a Buffer or a string).
// headers has lowercase names, as Node's request.headers does.
export function verifyChatwiseWebhook(rawBody, headers, secret, now = Date.now() / 1000) {
const id = headers["webhook-id"];
const timestamp = headers["webhook-timestamp"];
const signatures = headers["webhook-signature"];
if (!id || !timestamp || !signatures) return false;
// Refuse old requests, so a captured one can't be sent again later.
if (!(Math.abs(now - Number(timestamp)) <= FIVE_MINUTES)) return false;
const key = Buffer.from(secret.slice("whsec_".length), "base64");
const expected = createHmac("sha256", key).update(`${id}.${timestamp}.`).update(rawBody).digest();
// While a secret is being rotated there are two signatures. One match is enough.
return signatures.split(" ").some((signature) => {
const [version, value = ""] = signature.split(",");
const received = Buffer.from(value, "base64");
return version === "v1" && received.length === expected.length && timingSafeEqual(received, expected);
});
}A complete server
It reads the raw body, at most the 256 KiB an event can have, verifies it, skips events it already handled, and answers before it does the work. It remembers events in memory, so it loses them when it stops: use it to try things out. Save it next to the file above.
import { createServer } from "node:http";
import { verifyChatwiseWebhook } from "./verify.mjs";
const secret = process.env.CHATWISE_WEBHOOK_SECRET;
const MAX_BODY_BYTES = 256 * 1024; // The largest event Chatwise sends.
// In production, keep the events in your database: save one, answer, then do the work.
const handled = new Set();
async function handle(event) {
if (event.type === "message.received") {
console.log(`New message in conversation ${event.data.message.conversationId}`);
}
}
async function receive(request, response) {
// Anyone can send a request, so don't read more than an event can be.
if (Number(request.headers["content-length"] ?? 0) > MAX_BODY_BYTES) {
response.writeHead(413, { Connection: "close" }).end();
return;
}
const chunks = [];
let size = 0;
for await (const chunk of request) {
size += chunk.length;
if (size > MAX_BODY_BYTES) throw new Error("The body is too large");
chunks.push(chunk);
}
const rawBody = Buffer.concat(chunks);
if (!verifyChatwiseWebhook(rawBody, request.headers, secret)) {
response.writeHead(400).end();
return;
}
// The same event can arrive more than once.
const id = request.headers["webhook-id"];
const isNew = !handled.has(id);
handled.add(id);
// Answer within 10 seconds, then do the work.
response.writeHead(204).end();
if (isNew) await handle(JSON.parse(rawBody));
}
const server = createServer((request, response) => {
receive(request, response).catch((error) => {
console.error(error.message);
response.destroy();
});
});
server.listen(Number(process.env.PORT ?? 3000));Start it with the secret you got when you created the endpoint:
CHATWISE_WEBHOOK_SECRET='whsec_…' node server.mjsIn a framework
Many frameworks parse JSON before your code runs, and some refuse a body as large as an event can be. Get both right: the raw body, and a limit of at least 256 KiB. A request your framework refuses with a 413 is a failed delivery that isn't retried.
| Framework | The raw body | Its limit for a body |
|---|---|---|
| Express | express.raw({ type: "application/json", limit: "300kb" }) on the route | Takes at most 100 KB by default, which is too little: always set limit |
| Next.js route handlers | await request.text() | Has no limit: answer 413 yourself when content-length is over 300 KB |
| Flask | request.get_data() | Has no limit by default: set app.config["MAX_CONTENT_LENGTH"] = 300 * 1024 |
| FastAPI | await request.body() | Has no limit: answer 413 yourself when content-length is over 300 KB |
A proxy or a host in front of your server can have a limit of its own.
With Express, next to verify.mjs:
import express from "express";
import { verifyChatwiseWebhook } from "./verify.mjs";
const secret = process.env.CHATWISE_WEBHOOK_SECRET;
const app = express();
// The raw body, and room for the largest event (256 KiB): Express allows 100 KB unless you say otherwise.
const rawBody = express.raw({ type: "application/json", limit: "300kb" });
app.post("/webhooks/chatwise", rawBody, (request, response) => {
// The body is only bytes if the request said it was JSON.
if (!Buffer.isBuffer(request.body) || !verifyChatwiseWebhook(request.body, request.headers, secret)) {
response.sendStatus(400);
return;
}
// Skip events you already handled, by webhook-id, as in the complete server above.
response.sendStatus(204);
const event = JSON.parse(request.body);
console.log(`Received ${event.type}`);
});
app.listen(Number(process.env.PORT ?? 3000));If it doesn't match
- The secret is another endpoint's, or it was rotated more than 24 hours ago.
- The body was parsed, decoded or reformatted before it was verified.
- A proxy in front of your server changes the body or removes the
webhook-headers. - Your server's clock is more than five minutes off.
Send a test event to try again: it is signed like every other event.