Verify Truework webhooks
Truework doesn't sign its webhooks. Each webhook has its own authentication token, Truework sends it in the X-Truework-Token header on every request, and you compare the whole value with your stored token in constant time. A match shows the sender holds the token, but nothing covers the body and no timestamp stops a replay, so Truework's published source IP addresses are worth allowlisting where you can.
The facts
Compare X-Truework-Token's whole value with the webhook's token, in constant time Truework webhook secret
One token per webhook, generated by Truework and shown on the developer settings page. Deleting and recreating a webhook for the same URL issues a different token. Keep it in an environment variable, not in source code.
- Each webhook has its own authentication token, shown for that webhook on the developer settings page under Developer > Webhooks.
- Sandbox and Production webhooks are created separately, so each environment's webhooks have their own tokens. If one endpoint serves several webhooks, accept each webhook's token.
- Truework generates the token. No rotate action is documented, and a webhook you delete and recreate for the same URL gets a different token.
Source: Truework docs ↗
Code
// Generated with: truework-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const express = require('express');
const crypto = require('crypto');
// Receiver for Truework webhooks (order.completed, verification_request.state.change).
//
// Truework does NOT sign the payload: there is no HMAC and no signature header.
// Each webhook has an authentication token (Developer Settings > Webhooks) that
// Truework sends raw in the X-Truework-Token header. Reject any request whose
// token does not match, comparing in constant time.
const TOKEN_HEADER = 'x-truework-token';
// Read config per request so tests (and token rotation) don't need a restart.
function configuredToken() {
return process.env.TRUEWORK_WEBHOOK_TOKEN || '';
}
// Constant-time string compare. Hashing both sides first gives equal-length
// buffers, so timingSafeEqual never throws and the token's length isn't leaked.
function safeEqual(a, b) {
if (typeof a !== 'string' || typeof b !== 'string') return false;
const ha = crypto.createHash('sha256').update(a).digest();
const hb = crypto.createHash('sha256').update(b).digest();
return crypto.timingSafeEqual(ha, hb);
}
/**
* Check the X-Truework-Token header against the configured webhook token.
* @returns {boolean|null} null when no token is configured (caller fails closed)
*/
function verifyTrueworkToken(headerValue, token = configuredToken()) {
if (!token) return null;
return safeEqual(headerValue, token);
}
/**
* Handle one webhook. Payload shape (from Truework's docs):
* { version, hook: { id, event, target }, data: { order_id, ... } }
* Webhooks can be delivered more than once, so handlers must be idempotent.
*/
function handleTrueworkEvent(payload) {
const event = payload && payload.hook && payload.hook.event;
const data = (payload && payload.data) || {};
switch (event) {
case 'order.completed':
// All verifications on the order are completed or canceled: fetch results from the API.
console.log(`Truework order completed: ${data.order_id}`);
break;
case 'verification_request.state.change':
// state: pending-approval | processing | action-required | completed | canceled | invalid
console.log(
`Truework verification request ${data.verification_request_id} on order ${data.order_id} -> ${data.state}`
);
break;
default:
console.log(`Unhandled Truework event: ${event}`);
}
return event;
}
const app = express();
app.post(
'/webhooks/truework',
// Read every content type as raw bytes so the body is never parsed before auth.
express.raw({ type: '*/*' }),
(req, res) => {
const result = verifyTrueworkToken(req.get(TOKEN_HEADER));
if (result === null) {
console.error('Truework webhook refused: TRUEWORK_WEBHOOK_TOKEN is not set');
return res.status(500).json({ error: 'Webhook authentication not configured' });
}
if (!result) {
return res.status(401).json({ error: 'Invalid or missing X-Truework-Token' });
}
let payload;
try {
payload = JSON.parse(Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '');
} catch {
return res.status(400).json({ error: 'Invalid JSON body' });
}
const event = handleTrueworkEvent(payload);
res.status(200).json({ received: true, event });
}
);
app.get('/health', (req, res) => res.json({ status: 'ok' }));
module.exports = { app, verifyTrueworkToken, safeEqual, handleTrueworkEvent };
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/truework`);
});
} // Generated with: truework-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { TOKEN_HEADER, handleTrueworkEvent, verifyTrueworkToken } from '../../../lib/truework';
export async function POST(request: NextRequest) {
// Authenticate before parsing anything. Nothing is signed, so the raw body
// is only read afterwards, whatever the content type.
const auth = verifyTrueworkToken(request.headers.get(TOKEN_HEADER));
if (auth === null) {
console.error('Truework webhook refused: TRUEWORK_WEBHOOK_TOKEN is not set');
return NextResponse.json({ error: 'Webhook authentication not configured' }, { status: 500 });
}
if (!auth) {
return NextResponse.json({ error: 'Invalid or missing X-Truework-Token' }, { status: 401 });
}
let payload: unknown;
try {
payload = JSON.parse(await request.text());
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
const event = handleTrueworkEvent(payload);
return NextResponse.json({ received: true, event }, { status: 200 });
} # Generated with: truework-webhooks skill
# https://github.com/hookdeck/webhook-skills
"""Receiver for Truework webhooks (order.completed, verification_request.state.change).
Truework does NOT sign the payload: no HMAC, no signature header. Each webhook
has an authentication token (Developer Settings > Webhooks) that Truework sends
raw in the X-Truework-Token header. Reject any request whose token doesn't
match, comparing in constant time.
"""
import hashlib
import hmac
import json
import logging
import os
from typing import Any, Optional
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
load_dotenv()
logger = logging.getLogger("truework-webhooks")
app = FastAPI()
TOKEN_HEADER = "x-truework-token"
def safe_equal(a: Optional[str], b: str) -> bool:
"""Constant-time compare. Hash both sides first so the comparison doesn't
reveal the token's length (same as the Node examples)."""
if a is None:
return False
return hmac.compare_digest(hashlib.sha256(a.encode()).digest(), hashlib.sha256(b.encode()).digest())
def verify_truework_token(header_value: Optional[str], token: Optional[str] = None) -> Optional[bool]:
"""Returns None when no token is configured, so the caller can fail closed."""
if token is None:
token = os.environ.get("TRUEWORK_WEBHOOK_TOKEN", "")
if not token:
return None
return safe_equal(header_value, token)
async def require_truework_token(request: Request) -> None:
"""FastAPI dependency: authenticate before the body is parsed."""
result = verify_truework_token(request.headers.get(TOKEN_HEADER))
if result is None:
logger.error("Truework webhook refused: TRUEWORK_WEBHOOK_TOKEN is not set")
raise HTTPException(status_code=500, detail="Webhook authentication not configured")
if not result:
raise HTTPException(status_code=401, detail="Invalid or missing X-Truework-Token")
def handle_truework_event(payload: Any) -> Optional[str]:
"""Handle one webhook. Payload shape:
{ version, hook: { id, event, target }, data: { order_id, ... } }
Webhooks can be delivered more than once, so handlers must be idempotent."""
hook = payload.get("hook") if isinstance(payload, dict) else None
event = hook.get("event") if isinstance(hook, dict) else None
data = payload.get("data") if isinstance(payload, dict) else None
data = data if isinstance(data, dict) else {}
if event == "order.completed":
# All verifications on the order are completed or canceled: fetch results from the API.
logger.info("Truework order completed: %s", data.get("order_id"))
elif event == "verification_request.state.change":
# state: pending-approval | processing | action-required | completed | canceled | invalid
logger.info(
"Truework verification request %s on order %s -> %s",
data.get("verification_request_id"),
data.get("order_id"),
data.get("state"),
)
else:
logger.info("Unhandled Truework event: %s", event)
return event
@app.post("/webhooks/truework", dependencies=[Depends(require_truework_token)])
async def truework_webhook(request: Request):
# Raw bytes regardless of content type; parsed only after auth passed.
raw_body = await request.body()
try:
payload = json.loads(raw_body.decode("utf-8"))
except (ValueError, UnicodeDecodeError):
raise HTTPException(status_code=400, detail="Invalid JSON body")
event = handle_truework_event(payload)
return {"received": True, "event": event}
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000"))) Or install the Truework webhooks skill:
npx skills add hookdeck/webhook-skills --skill truework-webhooks
Common failures
The webhook was recreated
Deleting a webhook and creating it again for the same URL issues a different token, so the stored one stops matching.
The token belongs to another webhook
Sandbox and Production webhooks are created separately, and each webhook has its own token. If one endpoint serves several webhooks, accept each one's token.
No token is configured
If your process has no stored token, fail closed and return a 500, so an empty header can never match an empty value. Every delivery fails until you set it.
Let Event Gateway check Truework's webhook token.
Event Gateway compares the token on each Truework delivery before it reaches your service, then queues the event and retries failures on your schedule. A request with a missing or wrong token still gets a 200, but it's recorded as failed verification and creates no event.