Verify Agentcard webhooks
The AgentCard-Signature header lets you confirm that a delivery came from Agentcard and wasn't changed on the way. It holds a timestamp t and v1, a hex HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with the endpoint's whole whsec_ secret, so it isn't Standard Webhooks despite the prefix. Agentcard's docs have Node and Python samples, and its Commerce SDK exports verifyAgentcardWebhook.
The facts
{t}.{raw body} t from the AgentCard-Signature header, a literal dot, then the raw body bytes.
X-AgentCard-Signature sha256=<...> over the body alone; encoding not stated
Recompute an HMAC-SHA256 over the timestamp, a dot and the raw body, keyed with the whole whsec_ secret, then compare it with v1. Agentcard webhook secret
Agentcard generates one whsec_-prefixed secret per endpoint and returns it on create. Endpoints belong to one mode, so a sandbox endpoint and a production endpoint have different secrets. Keep it in an environment variable, not in source code.
- From the API:
POST /api/v2/webhook_endpointsreturns it assecret, andGET /api/v2/webhook_endpoints/{id}/secretreads it again. Reads are logged. - From the dashboard: Developers > Webhooks manages endpoints and secrets.
- Format: use the whole string,
whsec_included, as the HMAC key. Don't strip the prefix or base64-decode it. Despite the prefix, this isn't Standard Webhooks. - Per mode: the token you create the endpoint with decides its mode, so sandbox and production each have their own secret.
- Rotation:
POST /api/v2/webhook_endpoints/{id}/roll_secretreplaces it, and deliveries use the new secret from the next event. Agentcard documents no overlap, so update your verifier first.
Source: Agentcard docs ↗
Code
// Generated with: agentcard-webhooks skill
// https://github.com/hookdeck/webhook-skills
const express = require('express');
const crypto = require('crypto');
require('dotenv').config({ quiet: true });
const app = express();
const PORT = process.env.PORT || 3000;
// Agentcard signs every delivery with an AgentCard-Signature header:
// t=<unix seconds>,v1=<hex>
// v1 is HMAC-SHA256 (hex) of "<t>.<raw body>". The key is the endpoint's WHOLE secret string,
// including the whsec_ prefix, as UTF-8. This is NOT Standard Webhooks: don't strip the prefix or
// base64-decode it, and don't use the standardwebhooks or svix libraries.
// The legacy X-AgentCard-Signature (sha256=..., body only) header is not used here.
// https://docs.agentcard.com/webhooks/overview
// Optional replay window in seconds. Off by default (0): retries and replays, including
// Hookdeck's, carry the original timestamp, so a window would reject late redeliveries.
// Set AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS to a positive whole number to opt in; any other value is
// treated as 0, with a warning.
let warnedInvalidTolerance = false;
function timestampToleranceSeconds() {
const raw = (process.env.AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS ?? '').trim();
if (raw === '') return 0;
if (!/^\d+$/.test(raw)) {
if (!warnedInvalidTolerance) {
console.warn(`AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS=${JSON.stringify(raw)} is not a whole number of seconds; the timestamp check is off`);
warnedInvalidTolerance = true;
}
return 0;
}
return Number(raw);
}
timestampToleranceSeconds(); // surface an invalid value at startup
// Split on ',', trim each part (a space after the comma is allowed), split on the first '='.
// Keep every v1 (Agentcard's docs show one; accepting any match is harmless).
function parseSignatureHeader(header) {
let t;
const v1 = [];
for (const part of header.split(',')) {
const trimmed = part.trim();
const i = trimmed.indexOf('=');
if (i <= 0) continue;
const key = trimmed.slice(0, i).trim();
const value = trimmed.slice(i + 1).trim();
if (key === 't') t = value;
else if (key === 'v1') v1.push(value);
}
return { t, v1 };
}
function verifyAgentcard(rawBody, signatureHeader, secret) {
if (!secret || !signatureHeader) return false;
const { t, v1 } = parseSignatureHeader(signatureHeader);
if (!t || v1.length === 0 || !/^\d+$/.test(t)) return false;
// Opt-in only: off unless AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS > 0.
const tolerance = timestampToleranceSeconds();
if (tolerance > 0 && Math.abs(Math.floor(Date.now() / 1000) - Number(t)) > tolerance) {
return false;
}
const expected = crypto
.createHmac('sha256', secret) // whole secret string incl. whsec_, UTF-8, not decoded
.update(`${t}.`)
.update(rawBody)
.digest(); // 32 bytes
// Check for exactly 64 hex chars before Buffer.from(x, 'hex'): invalid hex silently truncates.
return v1.some(
(sig) => /^[0-9a-f]{64}$/i.test(sig) && crypto.timingSafeEqual(Buffer.from(sig, 'hex'), expected)
);
}
// Raw body is required: the signature covers the exact bytes Agentcard sent.
// type: '*/*' reads the body whatever the Content-Type is, so verification never depends on it.
app.post('/webhooks/agentcard', express.raw({ type: '*/*' }), (req, res) => {
const secret = process.env.AGENTCARD_WEBHOOK_SECRET;
if (!secret) {
console.error('AGENTCARD_WEBHOOK_SECRET is not set');
return res.status(500).send('Webhook secret not configured');
}
const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
if (!verifyAgentcard(rawBody, req.headers['agentcard-signature'], secret)) {
console.error('Agentcard webhook signature verification failed');
return res.status(400).send('Invalid signature');
}
let event;
try {
event = JSON.parse(rawBody.toString('utf8'));
} catch {
return res.status(400).send('Invalid JSON');
}
// Envelope: { id, type, created, livemode, data }. Delivery is at least once: dedupe on event.id.
const data = event.data || {};
switch (event.type) {
case 'card.created':
console.log(`Card ${data.id} created (**** ${data.last4}), balance ${data.balance_cents} cents`);
break;
case 'card.updated':
console.log(`Card ${data.id} updated: status ${data.status}, balance ${data.balance_cents} cents`);
break;
case 'card.closed':
console.log(`Card ${data.id} closed`);
break;
case 'transaction.authorized':
console.log(`Transaction ${data.id} authorized on card ${data.card_id}: ${data.amount_display} at ${data.merchant}`);
break;
case 'approval.requested':
console.log(`Approval ${data.approval_id} requested: ${data.action} (expires ${data.expires_at})`);
break;
case 'checkout_authorization.approved':
console.log(`Checkout authorization ${data.authorization_id} approved: ${data.amount_display} at ${data.merchant}`);
break;
case 'balance.low':
console.log(`Card ${data.card_id} balance low: ${data.balance_cents} cents`);
break;
default:
console.log(`Unhandled event: ${event.type}`);
}
res.json({ received: true });
});
if (require.main === module) {
app.listen(PORT, () => {
console.log(`Agentcard webhook server listening on http://localhost:${PORT}`);
});
}
module.exports = { app, verifyAgentcard }; // Generated with: agentcard-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
// Agentcard signs every delivery with an AgentCard-Signature header:
// t=<unix seconds>,v1=<hex>
// v1 is HMAC-SHA256 (hex) of "<t>.<raw body>". The key is the endpoint's WHOLE secret string,
// including the whsec_ prefix, as UTF-8. This is NOT Standard Webhooks: don't strip the prefix or
// base64-decode it, and don't use the standardwebhooks or svix libraries.
// The legacy X-AgentCard-Signature (sha256=..., body only) header is not used here.
// https://docs.agentcard.com/webhooks/overview
// Optional replay window in seconds. Off by default (0): retries and replays, including
// Hookdeck's, carry the original timestamp, so a window would reject late redeliveries.
// Set AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS to a positive whole number to opt in; any other value is
// treated as 0, with a warning.
let warnedInvalidTolerance = false;
function timestampToleranceSeconds(): number {
const raw = (process.env.AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS ?? '').trim();
if (raw === '') return 0;
if (!/^\d+$/.test(raw)) {
if (!warnedInvalidTolerance) {
console.warn(`AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS=${JSON.stringify(raw)} is not a whole number of seconds; the timestamp check is off`);
warnedInvalidTolerance = true;
}
return 0;
}
return Number(raw);
}
timestampToleranceSeconds(); // surface an invalid value at startup
// Split on ',', trim each part (a space after the comma is allowed), split on the first '='.
// Keep every v1 (Agentcard's docs show one; accepting any match is harmless).
function parseSignatureHeader(header: string): { t?: string; v1: string[] } {
let t: string | undefined;
const v1: string[] = [];
for (const part of header.split(',')) {
const trimmed = part.trim();
const i = trimmed.indexOf('=');
if (i <= 0) continue;
const key = trimmed.slice(0, i).trim();
const value = trimmed.slice(i + 1).trim();
if (key === 't') t = value;
else if (key === 'v1') v1.push(value);
}
return { t, v1 };
}
function verifyAgentcard(rawBody: string, signatureHeader: string | null, secret: string): boolean {
if (!secret || !signatureHeader) return false;
const { t, v1 } = parseSignatureHeader(signatureHeader);
if (!t || v1.length === 0 || !/^\d+$/.test(t)) return false;
// Opt-in only: off unless AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS > 0.
const tolerance = timestampToleranceSeconds();
if (tolerance > 0 && Math.abs(Math.floor(Date.now() / 1000) - Number(t)) > tolerance) {
return false;
}
const expected = crypto
.createHmac('sha256', secret) // whole secret string incl. whsec_, UTF-8, not decoded
.update(`${t}.${rawBody}`)
.digest(); // 32 bytes
// Check for exactly 64 hex chars before Buffer.from(x, 'hex'): invalid hex silently truncates.
return v1.some(
(sig) => /^[0-9a-f]{64}$/i.test(sig) && crypto.timingSafeEqual(Buffer.from(sig, 'hex'), expected)
);
}
export async function POST(request: NextRequest) {
const secret = process.env.AGENTCARD_WEBHOOK_SECRET;
if (!secret) {
console.error('AGENTCARD_WEBHOOK_SECRET is not set');
return NextResponse.json({ error: 'Webhook secret not configured' }, { status: 500 });
}
// Raw body: read as text before any JSON parsing, whatever the Content-Type is
const rawBody = await request.text();
if (!verifyAgentcard(rawBody, request.headers.get('agentcard-signature'), secret)) {
console.error('Agentcard webhook signature verification failed');
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
}
let event: any;
try {
event = JSON.parse(rawBody);
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
}
// Envelope: { id, type, created, livemode, data }. Delivery is at least once: dedupe on event.id.
const data = event.data || {};
switch (event.type) {
case 'card.created':
console.log(`Card ${data.id} created (**** ${data.last4}), balance ${data.balance_cents} cents`);
break;
case 'card.updated':
console.log(`Card ${data.id} updated: status ${data.status}, balance ${data.balance_cents} cents`);
break;
case 'card.closed':
console.log(`Card ${data.id} closed`);
break;
case 'transaction.authorized':
console.log(`Transaction ${data.id} authorized on card ${data.card_id}: ${data.amount_display} at ${data.merchant}`);
break;
case 'approval.requested':
console.log(`Approval ${data.approval_id} requested: ${data.action} (expires ${data.expires_at})`);
break;
case 'checkout_authorization.approved':
console.log(`Checkout authorization ${data.authorization_id} approved: ${data.amount_display} at ${data.merchant}`);
break;
case 'balance.low':
console.log(`Card ${data.card_id} balance low: ${data.balance_cents} cents`);
break;
default:
console.log(`Unhandled event: ${event.type}`);
}
return NextResponse.json({ received: true });
} # Generated with: agentcard-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import logging
import os
import re
import time
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
load_dotenv()
logger = logging.getLogger("agentcard-webhooks")
app = FastAPI()
# Agentcard signs every delivery with an AgentCard-Signature header:
# t=<unix seconds>,v1=<hex>
# v1 is HMAC-SHA256 (hex) of "<t>.<raw body>". The key is the endpoint's WHOLE secret string,
# including the whsec_ prefix, as UTF-8. This is NOT Standard Webhooks: don't strip the prefix or
# base64-decode it, and don't use the standardwebhooks or svix libraries.
# The legacy X-AgentCard-Signature (sha256=..., body only) header is not used here.
# https://docs.agentcard.com/webhooks/overview
# Optional replay window in seconds. Off by default (0): retries and replays, including
# Hookdeck's, carry the original timestamp, so a window would reject late redeliveries.
# Set AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS to a positive whole number to opt in; any other value is
# treated as 0, with a warning.
_warned_invalid_tolerance = False
def timestamp_tolerance_seconds() -> int:
global _warned_invalid_tolerance
raw = (os.getenv("AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS") or "").strip()
if not raw:
return 0
if not (raw.isascii() and raw.isdigit()):
if not _warned_invalid_tolerance:
logging.getLogger(__name__).warning(
"AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS=%r is not a whole number of seconds; the timestamp check is off",
raw,
)
_warned_invalid_tolerance = True
return 0
return int(raw)
timestamp_tolerance_seconds() # surface an invalid value at startup
_TS_RE = re.compile(r"[0-9]+", re.ASCII)
def parse_signature_header(header: str):
"""Split on ',', trim each part, split on the first '='. Keep every v1 (defensive; the docs show one)."""
t = None
v1 = []
for part in header.split(","):
key, sep, value = part.strip().partition("=")
key, value = key.strip(), value.strip()
if not sep or not key:
continue
if key == "t":
t = value
elif key == "v1":
v1.append(value)
return t, v1
def verify_agentcard(raw_body: bytes, signature_header, secret: str) -> bool:
if not secret or not signature_header:
return False
t, v1 = parse_signature_header(signature_header)
if not t or not v1 or not _TS_RE.fullmatch(t):
return False
# Opt-in only: off unless AGENTCARD_TIMESTAMP_TOLERANCE_SECONDS > 0.
tolerance = timestamp_tolerance_seconds()
if tolerance > 0 and abs(time.time() - int(t)) > tolerance:
return False
signed = t.encode() + b"." + raw_body
# whole secret string incl. whsec_, UTF-8, not decoded
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest().encode()
# compare_digest on bytes: a non-ASCII header value gives a mismatch (401/400), not a 500
return any(hmac.compare_digest(sig.lower().encode(), expected) for sig in v1)
async def verified_body(request: Request) -> bytes:
"""Dependency: read the raw body and verify it before any JSON parsing."""
secret = os.getenv("AGENTCARD_WEBHOOK_SECRET", "")
if not secret:
logger.error("AGENTCARD_WEBHOOK_SECRET is not set")
raise HTTPException(status_code=500, detail="Webhook secret not configured")
raw_body = await request.body()
if not verify_agentcard(raw_body, request.headers.get("agentcard-signature"), secret):
logger.error("Agentcard webhook signature verification failed")
raise HTTPException(status_code=400, detail="Invalid signature")
return raw_body
@app.post("/webhooks/agentcard")
async def agentcard_webhook(raw_body: bytes = Depends(verified_body)):
try:
event = json.loads(raw_body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON")
# Envelope: {id, type, created, livemode, data}. Delivery is at least once: dedupe on event["id"].
event_type = event.get("type")
data = event.get("data") or {}
if event_type == "card.created":
logger.info("Card %s created (**** %s), balance %s cents", data.get("id"), data.get("last4"), data.get("balance_cents"))
elif event_type == "card.updated":
logger.info("Card %s updated: status %s, balance %s cents", data.get("id"), data.get("status"), data.get("balance_cents"))
elif event_type == "card.closed":
logger.info("Card %s closed", data.get("id"))
elif event_type == "transaction.authorized":
logger.info("Transaction %s authorized on card %s: %s at %s", data.get("id"), data.get("card_id"), data.get("amount_display"), data.get("merchant"))
elif event_type == "approval.requested":
logger.info("Approval %s requested: %s (expires %s)", data.get("approval_id"), data.get("action"), data.get("expires_at"))
elif event_type == "checkout_authorization.approved":
logger.info("Checkout authorization %s approved: %s at %s", data.get("authorization_id"), data.get("amount_display"), data.get("merchant"))
elif event_type == "balance.low":
logger.info("Card %s balance low: %s cents", data.get("card_id"), data.get("balance_cents"))
else:
logger.info("Unhandled event: %s", event_type)
return {"received": True}
@app.get("/health")
async def health():
return {"status": "ok"} Or install the Agentcard webhooks skill:
npx skills add hookdeck/webhook-skills --skill agentcard-webhooks
Common failures
Standard Webhooks library
The whsec_ prefix suggests Standard Webhooks, but Agentcard uses the whole string as a plain HMAC key and signs {t}.{raw body}. Don't strip or base64-decode the prefix.
Body parsed before verification
The signature covers the exact bytes, so verify before any JSON parser runs. In Express, mount express.raw() ahead of express.json().
Wrong or rotated secret
Sandbox and production endpoints have different secrets. After roll_secret, deliveries use the new secret from the next event, and Agentcard documents no overlap.
Timestamp outside the tolerance
verifyAgentcardWebhook rejects a t more than 300 seconds from now as stale_timestamp. A delivery queued or replayed through Hookdeck keeps its original t, so raise toleranceSeconds and rely on deduplicating by id.
Let Event Gateway verify Agentcard signatures.
Event Gateway verifies the signature on each Agentcard delivery before it reaches your service, then queues it and retries failures on your schedule.