# Webhook Signature Verifier

URL: /docs/experiments/webhook-signature-verifier
> Verify HMAC-SHA256 webhook signatures with timing-safe comparison at the edge - Stripe/GitHub-style webhook auth
Tags: edge, security, webhooks, hmac, signatures, auth
Markdown: /llms.mdx/experiments/webhook-signature-verifier/content.md



Accept a raw payload, secret, signature header value, and algorithm. Computes the expected HMAC (Stripe/GitHub `sha256=` hex style) and returns whether it matches using a **timing-safe compare**.

## Features [#features]

* POST /verify - HMAC-SHA256 verification with clear comparison explanation
* Supports prefixed signatures (`sha256=...`) and raw hex
* Uses Web Crypto at the edge; no external libraries

## API Reference [#api-reference]

### POST /verify [#post-verify]

**`payload`** `string` (required) - Raw request body as received.

**`secret`** `string` (required) - Shared signing secret.

**`signature`** `string` (required) - Signature from the webhook header.

**`algorithm`** `string` (optional) - Default `sha256`.

#### Example Request [#example-request]

```bash
curl -X POST "https://your-worker.workers.dev/verify" \
  -H "Content-Type: application/json" \
  -d '{"payload":"{\"id\":1}","secret":"whsec_test","signature":"sha256=..."}'
```

#### Success Response [#success-response]

```json
{
  "match": true,
  "algorithm": "sha256",
  "expectedSignature": "sha256=...",
  "providedSignature": "sha256=...",
  "explanation": "Timing-safe comparison of 32-byte HMAC digests returned match."
}
```

#### Error Codes [#error-codes]

* `400` - `INVALID_BODY`, `MISSING_FIELD`, `INVALID_ALGORITHM`

## Use Cases [#use-cases]

* Debug Stripe, GitHub, or Shopify webhook signature mismatches
* Learn timing-safe HMAC verification patterns for Workers
* Validate signing logic before wiring production webhook handlers

## Limitations [#limitations]

* HMAC-SHA256 only in this experiment
* Secrets are sent in the request body; use only for debugging, not production traffic
* No replay protection or timestamp validation

## Use in your project [#use-in-your-project]

<UseInYourProject
  experiment="webhook-signature-verifier"
  platform="[&#x22;Web Crypto&#x22;]"
  files="[
  &#x22;src/lib/url.ts&#x22;,
  &#x22;src/lib/verify.ts&#x22;,
  &#x22;src/constants/defaults.ts&#x22;,
  &#x22;examples/usage.ts&#x22;,
]"
  sources="[{&#x22;path&#x22;:&#x22;src/lib/url.ts&#x22;,&#x22;title&#x22;:&#x22;url.ts&#x22;,&#x22;lang&#x22;:&#x22;ts&#x22;,&#x22;code&#x22;:&#x22;/** Allowed URL schemes for optional webhook URL validation helpers. */\nexport const ALLOWED_SCHEMES = [\&#x22;http:\&#x22;, \&#x22;https:\&#x22;] as const;\n\n/**\n * Validates and normalizes a URL.\n */\nexport function validateUrl(input: string | undefined): string | null {\n  if (!input || typeof input !== \&#x22;string\&#x22;) return null;\n  const trimmed = input.trim();\n  if (!trimmed) return null;\n  try {\n    const url = new URL(trimmed);\n    if (!ALLOWED_SCHEMES.includes(url.protocol as (typeof ALLOWED_SCHEMES)[number])) {\n      return null;\n    }\n    return url.href;\n  } catch {\n    return null;\n  }\n}&#x22;},{&#x22;path&#x22;:&#x22;src/lib/verify.ts&#x22;,&#x22;title&#x22;:&#x22;verify.ts&#x22;,&#x22;lang&#x22;:&#x22;ts&#x22;,&#x22;code&#x22;:&#x22;import {\n  DEFAULT_ALGORITHM,\n  MAX_PAYLOAD_LENGTH,\n  MAX_SECRET_LENGTH,\n  MAX_SIGNATURE_LENGTH,\n  SUPPORTED_ALGORITHMS,\n} from \&#x22;../constants/defaults\&#x22;;\nimport type { VerifyAlgorithm, VerifyRequest, VerifyResponse } from \&#x22;../types/verify\&#x22;;\n\nconst HEX_REGEX = /^[0-9a-f]+$/i;\n\nfunction bufferToHex(buffer: ArrayBuffer): string {\n  return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, \&#x22;0\&#x22;)).join(\&#x22;\&#x22;);\n}\n\nexport function timingSafeEqual(a: string, b: string): boolean {\n  if (a.length !== b.length) return false;\n  let mismatch = 0;\n  for (let i = 0; i < a.length; i++) {\n    mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n  }\n  return mismatch === 0;\n}\n\nexport function normalizeAlgorithm(input: string | undefined): VerifyAlgorithm | null {\n  const raw = (input ?? DEFAULT_ALGORITHM).trim().toLowerCase();\n  if (!raw) return null;\n  const normalized = raw === \&#x22;hmac_sha256\&#x22; ? \&#x22;hmac-sha256\&#x22; : raw;\n  if (SUPPORTED_ALGORITHMS.includes(normalized as VerifyAlgorithm)) {\n    return normalized as VerifyAlgorithm;\n  }\n  return null;\n}\n\nexport function parseSignature(signature: string): {\n  providedHex: string;\n  format: \&#x22;prefixed-hex\&#x22; | \&#x22;raw-hex\&#x22;;\n} | null {\n  const trimmed = signature.trim();\n  if (!trimmed) return null;\n\n  const prefixed = trimmed.match(/^sha256=(.+)$/i);\n  if (prefixed) {\n    const hex = prefixed[1].trim().toLowerCase();\n    if (!HEX_REGEX.test(hex)) return null;\n    return { providedHex: hex, format: \&#x22;prefixed-hex\&#x22; };\n  }\n\n  const raw = trimmed.toLowerCase();\n  if (!HEX_REGEX.test(raw)) return null;\n  return { providedHex: raw, format: \&#x22;raw-hex\&#x22; };\n}\n\nexport async function computeHmacSha256(payload: string, secret: string): Promise<string> {\n  const key = await crypto.subtle.importKey(\n    \&#x22;raw\&#x22;,\n    new TextEncoder().encode(secret),\n    { name: \&#x22;HMAC\&#x22;, hash: \&#x22;SHA-256\&#x22; },\n    false,\n    [\&#x22;sign\&#x22;]\n  );\n  const digest = await crypto.subtle.sign(\&#x22;HMAC\&#x22;, key, new TextEncoder().encode(payload));\n  return bufferToHex(digest);\n}\n\nexport function validateVerifyRequest(body: Partial<VerifyRequest>): VerifyRequest | null {\n  if (!body.payload || typeof body.payload !== \&#x22;string\&#x22;) return null;\n  if (!body.secret || typeof body.secret !== \&#x22;string\&#x22;) return null;\n  if (!body.signature || typeof body.signature !== \&#x22;string\&#x22;) return null;\n  if (body.payload.length > MAX_PAYLOAD_LENGTH) return null;\n  if (body.secret.length > MAX_SECRET_LENGTH) return null;\n  if (body.signature.length > MAX_SIGNATURE_LENGTH) return null;\n  return {\n    payload: body.payload,\n    secret: body.secret,\n    signature: body.signature,\n    algorithm: body.algorithm,\n  };\n}\n\nexport async function verifyWebhookSignature(\n  request: VerifyRequest\n): Promise<VerifyResponse | { error: string; code: string }> {\n  const algorithm = normalizeAlgorithm(request.algorithm);\n  if (!algorithm) {\n    return {\n      error: \&#x22;Unsupported algorithm (supported: sha256, hmac-sha256)\&#x22;,\n      code: \&#x22;INVALID_ALGORITHM\&#x22;,\n    };\n  }\n\n  const parsed = parseSignature(request.signature);\n  if (!parsed) {\n    return {\n      error: \&#x22;Invalid signature format (expected sha256=<hex> or raw hex)\&#x22;,\n      code: \&#x22;INVALID_SIGNATURE\&#x22;,\n    };\n  }\n\n  const expectedSignature = await computeHmacSha256(request.payload, request.secret);\n  const match = timingSafeEqual(expectedSignature, parsed.providedHex);\n\n  const explanation = match\n    ? `HMAC-SHA256 signature matches using ${parsed.format} format.`\n    : `HMAC-SHA256 signature does not match. Expected ${expectedSignature}, received ${parsed.providedHex}.`;\n\n  return {\n    match,\n    algorithm,\n    expectedSignature,\n    providedSignature: parsed.providedHex,\n    signatureFormat: parsed.format,\n    explanation,\n  };\n}&#x22;},{&#x22;path&#x22;:&#x22;src/constants/defaults.ts&#x22;,&#x22;title&#x22;:&#x22;defaults.ts&#x22;,&#x22;lang&#x22;:&#x22;ts&#x22;,&#x22;code&#x22;:&#x22;export const DEFAULT_ALGORITHM = \&#x22;sha256\&#x22; as const;\n\nexport const SUPPORTED_ALGORITHMS = [\&#x22;sha256\&#x22;, \&#x22;hmac-sha256\&#x22;] as const;\n\nexport const MAX_PAYLOAD_LENGTH = 1_000_000;\n\nexport const MAX_SECRET_LENGTH = 10_000;\n\nexport const MAX_SIGNATURE_LENGTH = 512;&#x22;},{&#x22;path&#x22;:&#x22;examples/usage.ts&#x22;,&#x22;title&#x22;:&#x22;usage.ts&#x22;,&#x22;lang&#x22;:&#x22;ts&#x22;,&#x22;code&#x22;:&#x22;/**\n * Minimal paste example for docs (\&#x22;Use in your project\&#x22;).\n * Not part of the Worker runtime — copy into your own project.\n *\n * Typical API: POST /verify {\n * Wire verifyWebhookSignature() the same way src/routes/ does (see that file for args / bindings).\n */\nimport { verifyWebhookSignature } from \&#x22;../src/lib/verify\&#x22;;\n\nexport default {\n  async fetch(request: Request, env: unknown): Promise<Response> {\n    // Typical API: POST /verify {\n    // Replace the placeholder call with the arguments used in this experiment's routes.\n    const result = await verifyWebhookSignature(/* args from src/routes/, env if needed */ env as never);\n    return Response.json(result);\n  },\n};&#x22;}]"
/>

## Deployment [#deployment]

<Steps>
  <Step>
    ### Click the deploy button [#click-the-deploy-button]

    [![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/shrinathsnayak/cloudflare-experiments/tree/main/apps/experiments/webhook-signature-verifier)
  </Step>

  <Step>
    ### Configure bindings [#configure-bindings]

    See `wrangler.json` and the experiment README for required bindings.
  </Step>

  <Step>
    ### Test your deployment [#test-your-deployment]

    See the experiment README for curl examples.
  </Step>
</Steps>

## Local Development [#local-development]

```bash
cd apps/experiments/webhook-signature-verifier
npm install
npm run dev
```

## Configuration [#configuration]

No bindings required beyond the Workers runtime.

## Cloudflare Features Used [#cloudflare-features-used]

* **[Workers](https://developers.cloudflare.com/workers/)**
* **[Web Crypto](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)**
