Skip to main content

Verify signatures

In this page you will verify the signature and the timestamp of a delivery with your webhook secret, and drop duplicates.

Before you start​

  • The webhook_secret of the installation, sent once in the token response when the installation was first activated.
  • Access to the raw request body, as bytes, before your framework parses it.

How the signature is computed​

X-Positive-Signature-V2 = "v1=" + base64( HMAC-SHA256( key = webhook secret, message = timestamp + "." + raw body ) )

timestamp is the value of X-Positive-Timestamp, in Unix seconds, written as sent. The key is the secret string exactly as issued. The result is base64 with padding, not hex.

During the 48 hours after the secret is rotated, X-Positive-Signature-V2-Previous carries the same computation made with the previous secret.

Verify a request​

  1. Read the raw body as bytes. Do not parse it yet.
  2. Read X-Positive-Timestamp and X-Positive-Signature-V2. Reject the request if either is missing.
  3. Reject a timestamp more than 5 minutes away from your clock: that is a replay.
  4. Compute the signature with your current secret and compare it with the header in constant time. If it does not match and you hold a previous secret, try the -Previous header with it.
  5. Reject the request if nothing matches, without parsing the body.
  6. Parse the body. Check that the topic header equals the body's topic and that apiVersion is v1.
  7. Look the event id up. If you have handled it, answer 2xx and stop. Otherwise store it, answer, and process the event.

Code​

import { createHmac, timingSafeEqual } from 'node:crypto';

export function isValidSignature(rawBody, timestamp, header, secret, now = Date.now()) {
if (!secret || !timestamp || !header) return false;
if (Math.abs(now / 1000 - Number(timestamp)) > 300) return false;
const expected = 'v1=' + createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest('base64');
const a = Buffer.from(expected);
const b = Buffer.from(header);
return a.length === b.length && timingSafeEqual(a, b);
}

Use it with the raw body, for example express.raw({ type: 'application/json' }), never express.json.

Pitfalls​

  • Re-serialized JSON. Parsing the body and encoding it again changes its bytes. Verify the raw bytes.
  • A framework that parses first. Configure the route to keep the raw body.
  • The wrong key. The key is the installation's webhook secret, not your OAuth client secret.
  • Comparing with ==. Use a constant-time comparison.
  • No deduplication. A retry or a redelivery sends the same event id again: handle each id once.