Dev.to Security 🔐 Cybersecurity 👁 0 📖 3 min read

Verify GitHub, Stripe, Shopify, and Svix Webhook Signatures in 40 Lines of Zero-Dependency Web Crypto JS

Every webhook integration fails in the same three places: You verify the signature against JSON.stringify(req.body) instead of the raw request bytes. You mix up hex vs base64 digests across providers. You forget that S

Every webhook integration fails in the same three places:

  1. You verify the signature against JSON.stringify(req.body) instead of the raw request bytes.
  2. You mix up hex vs base64 digests across providers.
  3. You forget that Standard Webhooks / Svix expects the whsec_ prefix stripped and the remainder base64-decoded before using it as an HMAC key.

Most teams debug this by pasting webhook secrets into random online HMAC tools—which sends production signing secrets to a third-party server. You don't need a server or an npm package to sign and verify all four major webhook formats: the Web Crypto API (crypto.subtle) works identically in every modern browser and in Node 20+.

Below is the exact ~40-line core we ship in Webhook & JSON Workbench (MIT, zero dependencies, runs 100% locally in your browser).

1. One HMAC-SHA256 helper for browser and Node

const subtle =
  (globalThis.crypto && globalThis.crypto.subtle) ||
  require('crypto').webcrypto.subtle;

const enc = (s) => new TextEncoder().encode(s);

const hex = (buf) =>
  [...new Uint8Array(buf)]
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('');

const b64 = (buf) => {
  let s = '';
  for (const b of new Uint8Array(buf)) s += String.fromCharCode(b);
  return typeof btoa === 'function'
    ? btoa(s)
    : Buffer.from(s, 'binary').toString('base64');
};

const b64decode = (s) => {
  const bin =
    typeof atob === 'function'
      ? atob(s)
      : Buffer.from(s, 'base64').toString('binary');
  return Uint8Array.from(bin, (c) => c.charCodeAt(0));
};

async function hmac(secret, message) {
  const key = await subtle.importKey(
    'raw',
    typeof secret === 'string' ? enc(secret) : secret,
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign']
  );
  return subtle.sign('HMAC', key, enc(message));
}

function safeEq(a, b) {
  if (a.length !== b.length) return false;
  let r = 0;
  for (let i = 0; i < a.length; i++) r |= a.charCodeAt(i) ^ b.charCodeAt(i);
  return r === 0;
}

Why safeEq? Standard === short-circuits on the first mismatched byte. Constant-time XOR comparison eliminates timing side-channels without pulling in a dependency.

2. The 4 provider formats side by side

Provider Header Signed Message Key Format Digest
GitHub X-Hub-Signature-256 rawBody UTF-8 string sha256= + hex
Stripe Stripe-Signature ${t}.${rawBody} UTF-8 string t=...,v1= + hex
Shopify X-Shopify-Hmac-Sha256 rawBody UTF-8 string base64
Svix / Standard Webhooks webhook-signature ${id}.${ts}.${rawBody} base64decode(secret.replace(/^whsec_/, '')) v1, + base64

Here is the complete provider map:

const PROVIDERS = {
  github: {
    async sign({ secret, body }) {
      return 'sha256=' + hex(await hmac(secret, body));
    },
    async verify({ secret, body, header }) {
      return safeEq(await this.sign({ secret, body }), String(header).trim());
    },
  },

  stripe: {
    async sign({ secret, body, timestamp }) {
      return `t=${timestamp},v1=${hex(await hmac(secret, `${timestamp}.${body}`))}`;
    },
    async verify({ secret, body, header, now, tolerance = 300 }) {
      const parts = Object.fromEntries(
        String(header).split(',').map((p) => p.split('='))
      );
      const ts = parts.t;
      if (!ts) return false;
      if (now != null && Math.abs(now - Number(ts)) > tolerance) return false;
      const exp = hex(await hmac(secret, `${ts}.${body}`));
      return String(header)
        .split(',')
        .some((p) => p.startsWith('v1=') && safeEq(p.slice(3), exp));
    },
  },

  shopify: {
    async sign({ secret, body }) {
      return b64(await hmac(secret, body));
    },
    async verify({ secret, body, header }) {
      return safeEq(await this.sign({ secret, body }), String(header).trim());
    },
  },

  svix: {
    async sign({ secret, body, timestamp, id }) {
      const key = b64decode(String(secret).replace(/^whsec_/, ''));
      return 'v1,' + b64(await hmac(key, `${id}.${timestamp}.${body}`));
    },
    async verify({ secret, body, header, timestamp, id }) {
      const exp = (await this.sign({ secret, body, timestamp, id })).slice(3);
      return String(header)
        .split(' ')
        .some((p) => p.startsWith('v1,') && safeEq(p.slice(3), exp));
    },
  },
};

3. Two subtle details that save hours

  1. Key rotation headers: Both Stripe (comma-separated v1=... entries) and Svix (space-separated v1,... entries) send multiple signatures during secret rotation. Checking .some(...) instead of matching a single token keeps your handler alive during rotations.
  2. Replay protection: Stripe's signature includes the Unix timestamp t. Enforcing Math.abs(now - Number(ts)) <= 300 (5-minute tolerance) stops attackers from replaying captured valid payloads later.

Try it locally (no secrets leave your browser)

Building internal AI / webhook workflows?

If you want production-ready local automation templates built with the same zero-bloat philosophy (40% off for Cyber Week via the links below):

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.