Verify Luma webhooks
The Webhook-Signature header lets you confirm that a delivery came from Luma 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 whole whsec_ secret. The header names and the prefix look like Standard Webhooks, but the scheme is different, so a Standard Webhooks or Svix library rejects every delivery. Luma's help page has verification samples in Node.js and Python.
The facts
{t}.{raw body} t from the Webhook-Signature header, a literal dot, then the raw JSON body.
Luma webhook secret
Luma generates a secret starting with whsec_ when you create a webhook. It isn't your API key. Keep it in an environment variable, not in source code.
- In the dashboard: Luma generates it when you create the webhook under Settings > Developer.
- From the API:
POST /v2/webhooks/createreturns it assecret, andGET /v2/webhooks/getreturns it too. - One per webhook: a calendar with several webhooks has a secret for each.
- Format: use the whole string as the HMAC key,
whsec_included. Don't strip the prefix or base64-decode it. - Rotation: Luma documents no way to roll a secret, and the update endpoint changes only
event_typesandstatus.
Source: Luma docs ↗
Code
// Generated with: luma-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const express = require('express');
const crypto = require('crypto');
const app = express();
// Optional replay window in seconds. Off by default (0): Hookdeck's retries and replays carry
// the original timestamp, so a window would reject late redeliveries.
// Set LUMA_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.LUMA_TIMESTAMP_TOLERANCE_SECONDS ?? '').trim();
if (raw === '') return 0;
if (!/^\d+$/.test(raw)) {
if (!warnedInvalidTolerance) {
console.warn(`LUMA_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
/**
* Verify a Luma webhook signature.
*
* Header: `Webhook-Signature: t=<unix seconds>,v1=<hex>`
* v1 = hex HMAC-SHA256 over `<t>.<raw body>`, keyed with the WHOLE secret string
* (including the `whsec_` prefix) as UTF-8. This is not Standard Webhooks.
*
* @param {Buffer|string} rawBody - Raw request body (do NOT re-stringify parsed JSON)
* @param {string} header - `Webhook-Signature` header value
* @param {string} secret - Webhook secret (whsec_...)
* @param {number} toleranceSeconds - Max age of `t`; 0 turns the check off (default from env)
* @param {number} nowSeconds - Current time in seconds (injectable for tests)
* @returns {boolean} Whether the signature is valid and fresh
*/
function verifyLumaWebhook(
rawBody,
header,
secret,
toleranceSeconds = timestampToleranceSeconds(),
nowSeconds = Date.now() / 1000
) {
if (!header || !secret) return false;
const parts = header.split(',').map((p) => p.trim().split('='));
const t = parts.find(([k]) => k === 't')?.[1];
const signatures = parts.filter(([k]) => k === 'v1').map(([, v]) => v);
if (!t || !/^\d+$/.test(t) || signatures.length === 0) return false;
// Luma suggests rejecting old timestamps, but Hookdeck's retries and replays carry the
// original `t`, so the window is opt-in (toleranceSeconds > 0).
if (toleranceSeconds > 0 && Math.abs(nowSeconds - Number(t)) > toleranceSeconds) return false;
const expected = crypto
.createHmac('sha256', secret)
.update(`${t}.`)
.update(rawBody)
.digest('hex');
return signatures.some((sig) => {
try {
return crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
} catch {
return false; // length mismatch = invalid
}
});
}
// Luma webhook endpoint - must use the raw body for signature verification.
// type '*/*' so the body is raw whatever Content-Type the sender (or a proxy) uses.
app.post('/webhooks/luma', express.raw({ type: '*/*' }), (req, res) => {
const header = req.headers['webhook-signature'];
const secret = process.env.LUMA_WEBHOOK_SECRET;
if (!header) {
return res.status(400).send('Missing Webhook-Signature header');
}
if (!secret) {
console.error('LUMA_WEBHOOK_SECRET is not set');
return res.status(500).send('Webhook secret not configured');
}
if (!verifyLumaWebhook(req.body, header, secret)) {
console.error('Luma webhook signature verification failed');
return res.status(400).send('Invalid signature');
}
// Parse only after verification. Body shape: { type, data }.
let event;
try {
event = JSON.parse(req.body.toString());
} catch {
return res.status(400).send('Invalid JSON');
}
const { type, data } = event;
switch (type) {
case 'guest.registered':
console.log(`Guest registered: ${data?.user_email} for ${data?.event?.name}`);
break;
case 'guest.updated':
console.log(`Guest updated: ${data?.user_email} (${data?.approval_status})`);
break;
case 'guest.refunded':
console.log(`Guest refunded: ${data?.user_email}`);
break;
case 'ticket.registered':
console.log(`Ticket registered: ${data?.event_ticket?.id} for ${data?.user_email}`);
break;
case 'event.created':
console.log(`Event created: ${data?.name} (${data?.id})`);
break;
case 'event.updated':
console.log(`Event updated: ${data?.name} (${data?.id})`);
break;
case 'event.canceled':
console.log(`Event canceled: ${data?.name} (${data?.id})`);
break;
case 'calendar.event.added':
console.log(`Event added to calendar: ${data?.name ?? data?.id}`);
break;
case 'calendar.event.submitted':
console.log(`Event submitted for approval: ${data?.name ?? data?.id}`);
break;
case 'calendar.person.subscribed':
console.log(`Calendar person subscribed: ${data?.email}`);
break;
case 'calendar.person.unsubscribed':
console.log(`Calendar person unsubscribed: ${data?.email}`);
break;
default:
console.log(`Unhandled event type: ${type}`);
}
// Your code: persist / forward. Use the Webhook-Id header as an idempotency key; Luma may
// deliver the same event more than once.
// Respond 2xx within 5 seconds, otherwise Luma retries (a 410 pauses the webhook).
res.status(200).send('OK');
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Export app for testing
module.exports = { app, verifyLumaWebhook };
// Start server only when run directly (not when imported for testing)
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/luma`);
});
} // Generated with: luma-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyLumaWebhook } from '../../../lib/luma';
interface LumaEvent {
type: string;
data: Record<string, any> | null;
}
export async function POST(request: NextRequest) {
// Read the raw body BEFORE parsing - the signature is over the exact bytes.
const rawBody = await request.text();
const header = request.headers.get('webhook-signature');
const secret = process.env.LUMA_WEBHOOK_SECRET;
if (!header) {
return NextResponse.json({ error: 'Missing Webhook-Signature header' }, { status: 400 });
}
if (!secret) {
console.error('LUMA_WEBHOOK_SECRET is not set');
return NextResponse.json({ error: 'Webhook secret not configured' }, { status: 500 });
}
if (!verifyLumaWebhook(rawBody, header, secret)) {
console.error('Luma webhook signature verification failed');
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
}
// Parse only after verification. Body shape: { type, data }.
let event: LumaEvent;
try {
event = JSON.parse(rawBody);
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
}
const { type, data } = event;
switch (type) {
case 'guest.registered':
console.log(`Guest registered: ${data?.user_email} for ${data?.event?.name}`);
break;
case 'guest.updated':
console.log(`Guest updated: ${data?.user_email} (${data?.approval_status})`);
break;
case 'guest.refunded':
console.log(`Guest refunded: ${data?.user_email}`);
break;
case 'ticket.registered':
console.log(`Ticket registered: ${data?.event_ticket?.id} for ${data?.user_email}`);
break;
case 'event.created':
console.log(`Event created: ${data?.name} (${data?.id})`);
break;
case 'event.updated':
console.log(`Event updated: ${data?.name} (${data?.id})`);
break;
case 'event.canceled':
console.log(`Event canceled: ${data?.name} (${data?.id})`);
break;
case 'calendar.event.added':
console.log(`Event added to calendar: ${data?.name ?? data?.id}`);
break;
case 'calendar.event.submitted':
console.log(`Event submitted for approval: ${data?.name ?? data?.id}`);
break;
case 'calendar.person.subscribed':
console.log(`Calendar person subscribed: ${data?.email}`);
break;
case 'calendar.person.unsubscribed':
console.log(`Calendar person unsubscribed: ${data?.email}`);
break;
default:
console.log(`Unhandled event type: ${type}`);
}
// Your code: persist / forward. Use the Webhook-Id header as an idempotency key; Luma may
// deliver the same event more than once.
// Respond 2xx within 5 seconds, otherwise Luma retries (a 410 pauses the webhook).
return NextResponse.json({ received: true });
} # Generated with: luma-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import logging
import os
import time
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request
load_dotenv()
app = FastAPI()
# Optional replay window in seconds. Off by default (0): Hookdeck's retries and replays carry
# the original timestamp, so a window would reject late redeliveries.
# Set LUMA_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("LUMA_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(
"LUMA_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
def verify_luma_webhook(
raw_body: bytes,
header: str | None,
secret: str,
tolerance: int | None = None,
now: float | None = None,
) -> bool:
"""Verify a Luma webhook signature.
Header: ``Webhook-Signature: t=<unix seconds>,v1=<hex>``
v1 = hex HMAC-SHA256 over ``<t>.<raw body>``, keyed with the WHOLE secret string
(including the ``whsec_`` prefix) as UTF-8. This is not Standard Webhooks.
"""
if not header or not secret:
return False
pairs = [p.strip().split("=", 1) for p in header.split(",") if "=" in p]
t = next((v for k, v in pairs if k == "t"), None)
signatures = [v for k, v in pairs if k == "v1"]
if not t or not (t.isascii() and t.isdigit()) or not signatures:
return False
# Luma suggests rejecting old timestamps, but Hookdeck's retries and replays carry the
# original `t`, so the window is opt-in (tolerance > 0).
if tolerance is None:
tolerance = timestamp_tolerance_seconds()
if tolerance > 0 and abs((time.time() if now is None else now) - int(t)) > tolerance:
return False
expected = hmac.new(
secret.encode("utf-8"), t.encode("utf-8") + b"." + raw_body, hashlib.sha256
).hexdigest()
return any(hmac.compare_digest(sig, expected) for sig in signatures)
@app.post("/webhooks/luma")
async def luma_webhook(request: Request):
# Read the raw body BEFORE parsing - the signature is over the exact bytes.
raw_body = await request.body()
header = request.headers.get("webhook-signature")
secret = os.environ.get("LUMA_WEBHOOK_SECRET")
if not header:
raise HTTPException(status_code=400, detail="Missing Webhook-Signature header")
if not secret:
raise HTTPException(status_code=500, detail="Webhook secret not configured")
if not verify_luma_webhook(raw_body, header, secret):
raise HTTPException(status_code=400, detail="Invalid signature")
# Parse only after verification. Body shape: {"type": ..., "data": ...}.
try:
event = json.loads(raw_body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON")
if not isinstance(event, dict):
raise HTTPException(status_code=400, detail="Expected an event object")
event_type = event.get("type")
data = event.get("data") or {}
if event_type == "guest.registered":
print(f"Guest registered: {data.get('user_email')} for {(data.get('event') or {}).get('name')}")
elif event_type == "guest.updated":
print(f"Guest updated: {data.get('user_email')} ({data.get('approval_status')})")
elif event_type == "guest.refunded":
print(f"Guest refunded: {data.get('user_email')}")
elif event_type == "ticket.registered":
print(f"Ticket registered: {(data.get('event_ticket') or {}).get('id')} for {data.get('user_email')}")
elif event_type == "event.created":
print(f"Event created: {data.get('name')} ({data.get('id')})")
elif event_type == "event.updated":
print(f"Event updated: {data.get('name')} ({data.get('id')})")
elif event_type == "event.canceled":
print(f"Event canceled: {data.get('name')} ({data.get('id')})")
elif event_type == "calendar.event.added":
print(f"Event added to calendar: {data.get('name') or data.get('id')}")
elif event_type == "calendar.event.submitted":
print(f"Event submitted for approval: {data.get('name') or data.get('id')}")
elif event_type == "calendar.person.subscribed":
print(f"Calendar person subscribed: {data.get('email')}")
elif event_type == "calendar.person.unsubscribed":
print(f"Calendar person unsubscribed: {data.get('email')}")
else:
print(f"Unhandled event type: {event_type}")
# Your code: persist / forward. Use the Webhook-Id header as an idempotency key; Luma may
# deliver the same event more than once.
# Respond 2xx within 5 seconds, otherwise Luma retries (a 410 pauses the webhook).
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 Luma webhooks skill:
npx skills add hookdeck/webhook-skills --skill luma-webhooks
Common failures
Using a Standard Webhooks library
Luma signs t, a dot and the body, and sends hex in a t=,v1= header. A Standard Webhooks or Svix verifier expects a signed ID, a decoded key and base64, so it rejects every delivery.
Stripping whsec_ from the secret
Luma's samples use the whole string as the key. Don't remove the prefix or base64-decode what's left.
Body parsed before verification
The signature covers the raw JSON body, so verify the exact bytes before any framework parses them.
A replay window rejects redeliveries
Luma suggests rejecting timestamps more than a few minutes old, but sets no number and doesn't say whether a retry gets a new t. Deliveries that Hookdeck retries or replays keep their original t, so widen the window or drop it and deduplicate on Webhook-Id.
Let Event Gateway verify Luma signatures.
Event Gateway verifies the signature on each Luma delivery before it reaches your service, then queues it and retries failures on your schedule.