Check a signature
Verify that an event came from CharpstAR and was not changed on the way, with a complete receiver in Node.
Every event carries a CharpstAR-Signature header. Check it before you trust the event.
Check the signature
Before you trust an event, check that it came from us and was not changed on the way:
- Read the raw request body as text, before you parse it.
- From
CharpstAR-Signature, taketandv1. - Compute HMAC SHA-256 over
t + "." + raw body, keyed with yourwhsec_secret, as hex. - Compare it with
v1in constant time. - Refuse the event if they differ, or if
tis more than 300 seconds from your clock.
import { createHmac, timingSafeEqual } from "node:crypto";
// CharpstAR-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, t + "." + raw body)>
export function verifyCharpstarSignature(header, rawBody, secret, toleranceSeconds = 300) {
if (!header || !secret) return false;
let t = null;
const signatures = [];
for (const part of header.split(",")) {
const [k, ...rest] = part.trim().split("=");
const v = rest.join("=");
if (k === "t" && /^\d+$/.test(v)) t = Number(v);
else if (k === "v1" && /^[0-9a-f]{64}$/i.test(v)) signatures.push(v.toLowerCase());
}
if (t === null || signatures.length === 0) return false;
if (Math.abs(Math.floor(Date.now() / 1000) - t) > toleranceSeconds) return false;
const expected = Buffer.from(createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex"));
return signatures.some((s) => {
const got = Buffer.from(s);
return got.length === expected.length && timingSafeEqual(got, expected);
});
}While a secret is being rotated, the header carries a signature for each secret, so compare v1 against every v1 value in it.
A complete receiver (Node)
The same checks as the reference client, in one file you can run with Node 18 or later.
// node receiver.mjs (Node 18 or later)
// Set CHARPSTAR_API_KEY and CHARPSTAR_WEBHOOK_SECRET first.
import { createServer } from "node:http";
import { verifyCharpstarSignature } from "./verify.mjs";
const secret = process.env.CHARPSTAR_WEBHOOK_SECRET;
const handled = new Set(); // use your database in production
async function handle(event) {
const delivered = event.type === "status.changed" && event.data.to === "delivered";
if (event.type === "asset.approved" || event.type === "asset.images.updated" || delivered) {
// Events are a signal: read the current asset, then write the links back into your system.
const res = await fetch(`https://platform.charpstar.co/api/v1/assets/${encodeURIComponent(event.article)}`, {
headers: { Authorization: `Bearer ${process.env.CHARPSTAR_API_KEY}` },
});
if (!res.ok) throw new Error(`asset read failed: ${res.status}`);
const asset = await res.json();
console.log(asset.articleId, asset.status, asset.arUrl);
}
}
createServer(async (req, res) => {
if (req.method !== "POST" || req.url !== "/charpstar/events") return res.writeHead(404).end();
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const raw = Buffer.concat(chunks).toString("utf8"); // the raw body: verify before parsing
if (!verifyCharpstarSignature(req.headers["charpstar-signature"], raw, secret)) {
return res.writeHead(401).end();
}
const delivery = req.headers["charpstar-delivery"];
if (handled.has(delivery)) return res.writeHead(200).end(); // a retry of one we already handled
try {
const event = JSON.parse(raw);
if (event.type !== "ping") await handle(event);
handled.add(delivery);
res.writeHead(200).end();
} catch (err) {
console.error(err);
res.writeHead(503).end(); // not handled: we will send it again later
}
}).listen(8080);