Skip to content
会nokai.studio

Webhook signature verification

Every webhook nokai.studio POSTs carries three headers:

X-Webhook-Timestamp: 1748563200
X-Webhook-Signature: <base64_hmac>
X-Webhook-Event:     job.completed
HeaderNotes
X-Webhook-TimestampUnix time (seconds) when the request was signed.
X-Webhook-SignatureBase64 HMAC-SHA256 — see below.
X-Webhook-EventEvent name, e.g. job.completed / job.failed.

The signature is computed as:

base64( HMAC_SHA256(<endpoint_signing_secret>, "<taskId>.<timestamp>") )

The signed string is the task id joined to the timestamp with a . — not the request body. <taskId> is the data.taskId field from the payload, and <timestamp> is the exact value of the X-Webhook-Timestamp header. Because the body is not part of the signature, re-serializing the JSON (pretty-printing, key reordering) does not break verification — but you must read taskId and the timestamp exactly as received.

Verification recipe

  1. Read the X-Webhook-Timestamp and X-Webhook-Signature headers.
  2. Parse the body and read data.taskId.
  3. Reject if X-Webhook-Timestamp is more than 5 minutes off from your wall clock (replay defense).
  4. Recompute the base64 HMAC over <taskId>.<timestamp> using the endpoint signing secret.
  5. Compare it to X-Webhook-Signature in constant time. Reject if they do not match.

Code

Node / TypeScript

import { createHmac, timingSafeEqual } from 'node:crypto';
 
export function verify(
  taskId: string,
  signatureHeader: string,
  timestampHeader: string,
  secret: string,
  toleranceSec = 300,
): boolean {
  if (!signatureHeader || !timestampHeader) return false;
 
  const ts = Number(timestampHeader);
  if (!Number.isFinite(ts)) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - ts) > toleranceSec) return false;
 
  const expected = createHmac('sha256', secret)
    .update(`${taskId}.${ts}`)
    .digest('base64');
  const a = Buffer.from(expected, 'utf8');
  const b = Buffer.from(signatureHeader, 'utf8');
  if (a.length !== b.length) return false;
  return timingSafeEqual(a, b);
}

Python

import base64, hashlib, hmac, time
 
def verify(task_id: str, signature: str, timestamp: str, secret: str, tolerance: int = 300) -> bool:
    if not signature or not timestamp:
        return False
    try:
        ts = int(timestamp)
    except ValueError:
        return False
    if abs(int(time.time()) - ts) > tolerance:
        return False
 
    expected = base64.b64encode(
        hmac.new(secret.encode(), f"{task_id}.{ts}".encode(), hashlib.sha256).digest()
    ).decode()
    return hmac.compare_digest(expected, signature)

Go

package nokai
 
import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "strconv"
    "time"
)
 
func Verify(taskID, signature, timestamp, secret string, tol time.Duration) bool {
    if signature == "" || timestamp == "" {
        return false
    }
    tsInt, err := strconv.ParseInt(timestamp, 10, 64)
    if err != nil {
        return false
    }
    if d := time.Since(time.Unix(tsInt, 0)); d < -tol || d > tol {
        return false
    }
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write([]byte(taskID + "." + timestamp))
    expected := base64.StdEncoding.EncodeToString(mac.Sum(nil))
    return hmac.Equal([]byte(expected), []byte(signature))
}

Common pitfalls

  • Signing the wrong string. The HMAC input is <taskId>.<timestamp>, not the request body and not <timestamp>.<body>. Read taskId from data.taskId.
  • Decoding the signature wrong. X-Webhook-Signature is base64, not hex.
  • Comparing strings with == or === is a timing oracle. Use crypto.timingSafeEqual (Node), hmac.compare_digest (Python), hmac.Equal (Go).
  • Wide tolerance. Do not bump the 5-minute tolerance to mask a clock-drift problem. Run NTP.
  • Logging the secret. Do not. Store it as an env-var only, never in source.

Replay defense

The 5-minute timestamp tolerance protects against an attacker replaying a captured request. For belt-and-suspenders: store event_id (or taskId) in a dedupe table on your side. Idempotency makes replays no-ops even if the signature window is wide open.