Verify project44 webhooks
project44 doesn't sign webhooks. With API_KEY authentication it adds a header you name, holding a value you choose, and you compare the whole value in constant time. A match shows the sender knows your key, but nothing covers the body, and a captured request can be replayed. The code on this page covers API_KEY, one of the five authentication types alongside BASIC, OAUTH2, MTLS and AD_OAUTH2_CERT.
The facts
Compare the header you named in api_key_name with its stored value, in constant time project44 webhook secret
You choose both the header name and its value when you create the push configuration, and project44 sends that header on each request. There's no signing secret to retrieve. Keep it in an environment variable, not in source code.
- Set them in
authenticationMethodsonPUT /api/v4/webhooks:api_key_nameis the header name andapi_keyis the value. - The Webhook Guide's field list calls the value
api_key_value, but its example and the OpenAPI spec useapi_key. - A configuration can hold two API keys, and each gets its own header.
- To change a key, send
PUT /api/v4/webhooksagain with the new value. Each configuration has its own keys.
Source: project44 docs ↗
Code
// Generated with: project44-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');
const app = express();
/**
* Constant-time string comparison. Hashing both sides first gives equal-length
* buffers, so timingSafeEqual never throws and the secret's length isn't leaked.
*/
function safeEqual(a, b) {
const ha = crypto.createHash('sha256').update(String(a)).digest();
const hb = crypto.createHash('sha256').update(String(b)).digest();
return crypto.timingSafeEqual(ha, hb);
}
/**
* project44 does not sign payloads. With the API_KEY authentication method it adds a
* header you named (api_key_name) with the value you chose. The header name is user-chosen,
* so it comes from PROJECT44_WEBHOOK_HEADER; the expected value is the exact, whole header
* value from PROJECT44_WEBHOOK_SECRET (no "Bearer " parsing).
*/
function verifyProject44Request(headers, env = process.env) {
const secret = env.PROJECT44_WEBHOOK_SECRET;
if (!secret) return false; // never accept when unconfigured
const name = (env.PROJECT44_WEBHOOK_HEADER || 'X-Api-Key').toLowerCase();
const received = headers[name]; // Node lowercases incoming header names
return Boolean(received) && safeEqual(received, secret);
}
function handleEvent(payload) {
const { eventType, eventId } = payload;
const shipmentId = payload.context && payload.context.shipment && payload.context.shipment.shipmentId;
// project44 can redeliver after a lost response: dedupe on eventId in real code.
switch (eventType) {
case 'shipments.v1.shipment.created':
console.log(`Shipment created: ${shipmentId} (${eventId})`);
// Your code: register the shipment in your system
break;
case 'shipments.v1.shipment.deleted':
console.log(`Shipment deleted: ${shipmentId} (${eventId})`);
// Your code: stop tracking the shipment
break;
case 'shipments.v1.event.added':
console.log(`Shipment event added: ${shipmentId} (${eventId})`);
// Your code: record the new milestone from payload.data
break;
case 'shipments.v1.event.updated':
console.log(`Shipment event updated: ${shipmentId} (${eventId})`);
// Your code: update the milestone from payload.data
break;
case 'shipments.v1.event.removed':
console.log(`Shipment event removed: ${shipmentId} (${eventId})`);
// Your code: remove the milestone
break;
case 'shipments.v1.state.added':
console.log(`Shipment state added: ${shipmentId} (${eventId})`);
// Your code: record the new state from payload.data
break;
case 'shipments.v1.state.updated':
console.log(`Shipment state updated: ${shipmentId} (${eventId})`);
// Your code: update the state from payload.data
break;
case 'shipments.v1.state.removed':
console.log(`Shipment state removed: ${shipmentId} (${eventId})`);
// Your code: remove the state
break;
case 'shipments.v1.exception.addedOrUpdated':
console.log(`Shipment exception added or updated: ${shipmentId} (${eventId})`);
// Your code: alert on the exception in payload.data
break;
default:
console.log(`Unhandled event: ${eventType}`);
}
}
// The webhook method is configurable in project44 (POST by default), so accept all four.
const METHODS = ['GET', 'POST', 'PUT', 'PATCH'];
// Read the body raw (any content type) so the request is authenticated before parsing.
app.all('/webhooks/project44', express.raw({ type: '*/*' }), (req, res) => {
if (!METHODS.includes(req.method)) {
res.set('Allow', METHODS.join(', '));
return res.status(405).json({ error: 'Method not allowed' });
}
if (!verifyProject44Request(req.headers)) {
return res.status(401).json({ error: 'Invalid or missing API key header' });
}
const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
// An empty body (e.g. GET) is acknowledged without handling.
if (raw.trim() === '') {
return res.status(200).json({ received: true });
}
let payload;
try {
payload = JSON.parse(raw);
} catch {
return res.status(400).json({ error: 'Invalid JSON body' });
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return res.status(400).json({ error: 'Expected a JSON object' });
}
try {
handleEvent(payload);
} catch (err) {
console.error('Error handling project44 event:', err);
// project44 does not retry 500 but does retry 503, so signal a transient failure.
return res.status(503).json({ error: 'Handler error' });
}
res.status(200).json({ received: true });
});
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = app;
module.exports.verifyProject44Request = verifyProject44Request;
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/project44`);
});
} // Generated with: project44-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyProject44Request } from '../../../lib/verify-project44';
interface Project44Payload {
eventId?: string;
eventType?: string;
context?: { shipment?: { shipmentId?: string } };
data?: unknown;
[key: string]: unknown;
}
function handleEvent(payload: Project44Payload): void {
const { eventType, eventId } = payload;
const shipmentId = payload.context?.shipment?.shipmentId;
// project44 can redeliver after a lost response: dedupe on eventId in real code.
switch (eventType) {
case 'shipments.v1.shipment.created':
console.log(`Shipment created: ${shipmentId} (${eventId})`);
// Your code: register the shipment in your system
break;
case 'shipments.v1.shipment.deleted':
console.log(`Shipment deleted: ${shipmentId} (${eventId})`);
// Your code: stop tracking the shipment
break;
case 'shipments.v1.event.added':
console.log(`Shipment event added: ${shipmentId} (${eventId})`);
// Your code: record the new milestone from payload.data
break;
case 'shipments.v1.event.updated':
console.log(`Shipment event updated: ${shipmentId} (${eventId})`);
// Your code: update the milestone from payload.data
break;
case 'shipments.v1.event.removed':
console.log(`Shipment event removed: ${shipmentId} (${eventId})`);
// Your code: remove the milestone
break;
case 'shipments.v1.state.added':
console.log(`Shipment state added: ${shipmentId} (${eventId})`);
// Your code: record the new state from payload.data
break;
case 'shipments.v1.state.updated':
console.log(`Shipment state updated: ${shipmentId} (${eventId})`);
// Your code: update the state from payload.data
break;
case 'shipments.v1.state.removed':
console.log(`Shipment state removed: ${shipmentId} (${eventId})`);
// Your code: remove the state
break;
case 'shipments.v1.exception.addedOrUpdated':
console.log(`Shipment exception added or updated: ${shipmentId} (${eventId})`);
// Your code: alert on the exception in payload.data
break;
default:
console.log(`Unhandled event: ${eventType}`);
}
}
async function handle(request: NextRequest) {
// Authenticate before reading or parsing the body.
if (!verifyProject44Request(request.headers)) {
return NextResponse.json({ error: 'Invalid or missing API key header' }, { status: 401 });
}
// Read as text so any content type is accepted. An empty body (e.g. GET) is fine.
const raw = await request.text();
if (raw.trim() === '') {
return NextResponse.json({ received: true });
}
let payload: unknown;
try {
payload = JSON.parse(raw);
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
return NextResponse.json({ error: 'Expected a JSON object' }, { status: 400 });
}
try {
handleEvent(payload as Project44Payload);
} catch (err) {
console.error('Error handling project44 event:', err);
// project44 does not retry 500 but does retry 503, so signal a transient failure.
return NextResponse.json({ error: 'Handler error' }, { status: 503 });
}
return NextResponse.json({ received: true });
}
// The webhook method is configurable in project44 (POST by default), so accept all four.
export const POST = handle;
export const PUT = handle;
export const PATCH = handle;
export const GET = handle; # Generated with: project44-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hmac
import json
import os
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
load_dotenv()
app = FastAPI()
def verify_project44_request(headers, env=None) -> bool:
"""project44 does not sign payloads. With the API_KEY authentication method it adds a
header you named (api_key_name) with the value you chose. The header name is user-chosen,
so it comes from PROJECT44_WEBHOOK_HEADER; the expected value is the exact, whole header
value from PROJECT44_WEBHOOK_SECRET (no "Bearer " parsing).
"""
env = env if env is not None else os.environ
secret = env.get("PROJECT44_WEBHOOK_SECRET")
if not secret:
return False # never accept when unconfigured
name = env.get("PROJECT44_WEBHOOK_HEADER") or "X-Api-Key"
received = headers.get(name) # Starlette headers are case-insensitive
if not received:
return False
# Encode both sides: compare_digest raises TypeError on non-ASCII str, and bytes
# of different lengths simply compare unequal.
return hmac.compare_digest(received.encode("utf-8"), secret.encode("utf-8"))
async def require_project44_key(request: Request) -> None:
"""FastAPI dependency: reject the request before the body is parsed."""
if not verify_project44_request(request.headers):
raise HTTPException(status_code=401, detail="Invalid or missing API key header")
def handle_event(payload: dict) -> None:
event_type = payload.get("eventType")
event_id = payload.get("eventId")
context = payload.get("context")
shipment = context.get("shipment") if isinstance(context, dict) else None
shipment_id = shipment.get("shipmentId") if isinstance(shipment, dict) else None
# project44 can redeliver after a lost response: dedupe on eventId in real code.
if event_type == "shipments.v1.shipment.created":
print(f"Shipment created: {shipment_id} ({event_id})")
# Your code: register the shipment in your system
elif event_type == "shipments.v1.shipment.deleted":
print(f"Shipment deleted: {shipment_id} ({event_id})")
# Your code: stop tracking the shipment
elif event_type == "shipments.v1.event.added":
print(f"Shipment event added: {shipment_id} ({event_id})")
# Your code: record the new milestone from payload["data"]
elif event_type == "shipments.v1.event.updated":
print(f"Shipment event updated: {shipment_id} ({event_id})")
# Your code: update the milestone from payload["data"]
elif event_type == "shipments.v1.event.removed":
print(f"Shipment event removed: {shipment_id} ({event_id})")
# Your code: remove the milestone
elif event_type == "shipments.v1.state.added":
print(f"Shipment state added: {shipment_id} ({event_id})")
# Your code: record the new state from payload["data"]
elif event_type == "shipments.v1.state.updated":
print(f"Shipment state updated: {shipment_id} ({event_id})")
# Your code: update the state from payload["data"]
elif event_type == "shipments.v1.state.removed":
print(f"Shipment state removed: {shipment_id} ({event_id})")
# Your code: remove the state
elif event_type == "shipments.v1.exception.addedOrUpdated":
print(f"Shipment exception added or updated: {shipment_id} ({event_id})")
# Your code: alert on the exception in payload["data"]
else:
print(f"Unhandled event: {event_type}")
# The webhook method is configurable in project44 (POST by default), so accept all four.
@app.api_route(
"/webhooks/project44",
methods=["GET", "POST", "PUT", "PATCH"],
dependencies=[Depends(require_project44_key)],
)
async def project44_webhook(request: Request):
# Read the raw body so any content type is accepted. An empty body (e.g. GET) is fine.
raw_body = await request.body()
if not raw_body.strip():
return {"received": True}
try:
payload = json.loads(raw_body)
except (json.JSONDecodeError, UnicodeDecodeError):
raise HTTPException(status_code=400, detail="Invalid JSON body")
if not isinstance(payload, dict):
raise HTTPException(status_code=400, detail="Expected a JSON object")
try:
handle_event(payload)
except Exception as err: # noqa: BLE001
print(f"Error handling project44 event: {err}")
# project44 does not retry 500 but does retry 503, so signal a transient failure.
raise HTTPException(status_code=503, detail="Handler error")
return {"received": True}
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the project44 webhooks skill:
npx skills add hookdeck/webhook-skills --skill project44-webhooks
Common failures
Looking for the wrong header
The header is whatever you set as api_key_name, with no fixed default from project44. The code on this page reads the name from PROJECT44_WEBHOOK_HEADER, so set it to match your configuration.
Sending the key as api_key_value
The Webhook Guide's field list says api_key_value, but its example and project44's OpenAPI spec use api_key. Send api_key, and check your configuration if the header doesn't arrive.
Comparing part of the value
project44 sends the value exactly as you configured it. If you set Bearer abc, the expected value is Bearer abc, so don't strip a prefix before comparing.
Using another authentication type
A configuration with only BASIC, OAUTH2, MTLS or AD_OAUTH2_CERT sends no API key header, so this check rejects its deliveries.
Let Event Gateway check project44's API key header.
Event Gateway checks the API key header on each project44 delivery before it reaches your service, then queues it and retries failures on your schedule.