How to verify FormKeep webhook signatures

Webhooks to your own URLs (a custom webhook URL, or a Manual webhook) carry an X-FormKeep-Signature header. Check it before you trust a request: anyone who learns your URL could post to it, but only FormKeep and you know the signing secret. Signing needs a paid plan. Zapier, Rollout and ActiveCampaign hooks are not signed.

The header

X-FormKeep-Signature: t=1700000000,v1=1abedf2450403df988d7858a13a87ac0a1a276a322a1b7e7030d1ffa3c2edde5

Find the secret on your form's Webhooks settings page. Keep it on your server and out of your code repository.

How to verify

  1. Read the raw request body, as bytes or a string, before any JSON or form parsing. Re-serialising parsed data changes the bytes and the signature will not match.
  2. Split the header on ,, then each part on the first =, to get t and v1.
  3. Compute HMAC-SHA256 of "#{t}.#{body}" with your secret, as hex.
  4. Compare it with v1 in constant time (not ==).
  5. Reject the request if t is more than 5 minutes from your clock. This stops someone replaying a request they captured.

Test vector

Check your code against this before you go live:

secret: whsec_test_secret_0123456789abcdef
t:      1700000000
body:   {"name":"Ada","email":"ada@example.com"}
signed: 1700000000.{"name":"Ada","email":"ada@example.com"}
v1:     1abedf2450403df988d7858a13a87ac0a1a276a322a1b7e7030d1ffa3c2edde5

Node (Express)

const crypto = require('crypto');
const express = require('express');
const app = express();

const SECRET = process.env.FORMKEEP_WEBHOOK_SECRET;
const TOLERANCE_SECONDS = 300;

function verify(rawBody, header) {
  const parts = Object.fromEntries(
    (header || '').split(',').map((p) => [p.slice(0, p.indexOf('=')), p.slice(p.indexOf('=') + 1)])
  );
  const t = Number(parts.t);
  if (!parts.v1 || !Number.isFinite(t)) return false;
  if (Math.abs(Date.now() / 1000 - t) > TOLERANCE_SECONDS) return false;

  const expected = crypto
    .createHmac('sha256', SECRET)
    .update(`${parts.t}.${rawBody}`)
    .digest('hex');

  const a = Buffer.from(expected);
  const b = Buffer.from(parts.v1);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// express.raw keeps the body as a Buffer; do not use express.json() on this route.
app.post('/formkeep', express.raw({ type: '*/*' }), (req, res) => {
  const rawBody = req.body.toString('utf8');
  if (!verify(rawBody, req.get('X-FormKeep-Signature'))) return res.sendStatus(400);

  // Parse only after verifying, by the content type FormKeep sent.
  const submission = (req.get('Content-Type') || '').startsWith('application/x-www-form-urlencoded')
    ? Object.fromEntries(new URLSearchParams(rawBody))
    : JSON.parse(rawBody);
  // ... use submission ...
  res.sendStatus(200);
});

Python (Flask)

import hashlib
import hmac
import os
import time

from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ['FORMKEEP_WEBHOOK_SECRET'].encode()
TOLERANCE_SECONDS = 300


def verify(raw_body: bytes, header: str) -> bool:
    try:
        parts = dict(p.split('=', 1) for p in (header or '').split(','))
        timestamp = int(parts['t'])
        v1 = parts['v1']
    except (ValueError, KeyError):
        return False
    if not v1.isascii() or any(c not in '0123456789abcdef' for c in v1):
        return False
    if abs(time.time() - timestamp) > TOLERANCE_SECONDS:
        return False

    signed = parts['t'].encode() + b'.' + raw_body
    expected = hmac.new(SECRET, signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected.encode(), v1.encode())


@app.post('/formkeep')
def formkeep():
    raw_body = request.get_data()  # before request.json or request.form
    if not verify(raw_body, request.headers.get('X-FormKeep-Signature')):
        abort(400)
    # Parse only after verifying.
    if request.mimetype == 'application/x-www-form-urlencoded':
        submission = request.form
    else:
        submission = request.get_json()
    # ... use submission ...
    return '', 200

Ruby (Sinatra)

require 'json'
require 'openssl'
require 'rack/utils'
require 'sinatra'

SECRET = ENV.fetch('FORMKEEP_WEBHOOK_SECRET')
TOLERANCE_SECONDS = 300

def verified?(raw_body, header)
  pairs = header.to_s.split(',').map { |part| part.split('=', 2) }
  parts = pairs.select { |pair| pair.size == 2 }.to_h
  timestamp = Integer(parts['t'], exception: false)
  return false if timestamp.nil? || parts['v1'].nil?
  return false if (Time.now.to_i - timestamp).abs > TOLERANCE_SECONDS

  expected = OpenSSL::HMAC.hexdigest('SHA256', SECRET, "#{parts['t']}.#{raw_body}")
  Rack::Utils.secure_compare(expected, parts['v1'])
end

post '/formkeep' do
  request.body.rewind
  raw_body = request.body.read # before parsing
  halt 400 unless verified?(raw_body, request.env['HTTP_X_FORMKEEP_SIGNATURE'])

  submission = if request.media_type == 'application/x-www-form-urlencoded'
                 Rack::Utils.parse_nested_query(raw_body)
               else
                 JSON.parse(raw_body)
               end
  # ... use submission ...
  status 200
end

Form-encoded webhooks

Hooks that are not set to send JSON arrive as application/x-www-form-urlencoded. The signature covers the encoded body exactly as sent, so verify the raw string first and parse it afterwards, just as with JSON.

Rotating the secret

Rotate secret on the Webhooks settings page makes a new secret and stops the old one signing at once. Copy the new secret to your server right after rotating; requests sent in between will fail your check.

That's it! Why not get started now?

Looking for something else?

Email us