GladysDevelopers

Verifying signatures

Check that a webhook came from Gladys and wasn't changed on the way.

Anyone can send a POST to your webhook URL. Every request from Gladys carries a signature that only Gladys, and you, can produce:

Gladys-Signature: t=1791201600,v1=5f2b8c9a…
  • t is when the request was sent, in Unix seconds.
  • v1 is an HMAC-SHA256, in hex, of the timestamp, a dot, and the raw request body, keyed with your endpoint's secret: HMAC-SHA256(secret, t + "." + body).

How to check it

  1. Read the raw body: the exact bytes received, before any JSON parsing. A body that is parsed and re-serialized won't match.
  2. Split the header on , and each part on the first =, to get t and v1.
  3. Refuse it if t is more than 5 minutes away from your clock. This stops an old, captured request being replayed.
  4. Compute the HMAC with your secret, the whole whsec_… string, and compare it to v1 in constant time.
import crypto from 'node:crypto';

// rawBody: a Buffer of the exact bytes received.
export function verifyGladysSignature(rawBody, header, secret, toleranceSeconds = 300) {
  const parts = Object.fromEntries(
    header.split(',').map((part) => {
      const i = part.indexOf('=');
      return [part.slice(0, i).trim(), part.slice(i + 1).trim()];
    }),
  );
  const timestamp = Number(parts.t);
  if (!Number.isInteger(timestamp) || !parts.v1) return false;
  if (Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return false;

  const expected = crypto
    .createHmac('sha256', secret)
    .update(`${timestamp}.`)
    .update(rawBody)
    .digest();
  const received = Buffer.from(parts.v1, 'hex');
  return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}

With Express, keep the raw body for this route:

app.post('/webhooks/gladys', express.raw({ type: 'application/json' }), (req, res) => {
  const ok = verifyGladysSignature(req.body, req.get('Gladys-Signature') ?? '', process.env.GLADYS_WEBHOOK_SECRET);
  if (!ok) return res.sendStatus(400);

  const event = JSON.parse(req.body);
  res.sendStatus(200);
  handleEvent(event); // after answering
});

Each sample is tested against the signatures Gladys sends: a genuine request passes; a changed body, the wrong secret or a timestamp more than 5 minutes old fails.

Good to know

  • The signature is made when each attempt is sent, so a retry or a replay has a new t, signed with the endpoint's current secret.
  • Keep your server's clock in sync (NTP). A clock that drifts more than 5 minutes rejects real webhooks.
  • After rotating the secret, only the new secret verifies.

On this page