Verify Speechmatics webhooks
Speechmatics doesn't sign notifications, so there's no signature to check and no SDK to verify one. You add a secret header through auth_headers on each job, and your endpoint compares the whole value in constant time. That authenticates the sender, but it doesn't protect the body or stop a replay, and Speechmatics' own origin check is a published list of egress IPs.
The facts
Speechmatics webhook secret
Speechmatics issues no webhook secret. Whoever submits the job chooses the header and its value, in notification_config[].auth_headers. Keep it in an environment variable, not in source code.
- Generate a long random value yourself, because this is the credential your service accepts, not your Speechmatics API key
- To rotate it, submit new jobs with the new value and accept the old one until jobs already running have called back
Source: Speechmatics docs ↗
Code
// Generated with: speechmatics-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);
}
/**
* Speechmatics does not sign notifications. It sends the header you listed in
* notification_config[].auth_headers, verbatim. The whole value is compared:
* a "Bearer " prefix is part of the value, not parsed off.
* Node lowercases incoming header names, so lowercase the configured name.
* A static credential authenticates the sender only: no body signature, no replay protection.
*/
function verifySpeechmaticsRequest(headers, config = process.env) {
const name = (config.SPEECHMATICS_WEBHOOK_HEADER || 'Authorization').toLowerCase();
const expected = config.SPEECHMATICS_WEBHOOK_SECRET;
if (!expected) return false; // never accept when unconfigured
const received = headers[name];
return typeof received === 'string' && safeEqual(received, expected);
}
/**
* Speechmatics appends ?id=<job id>&status=<status> to your URL. The body is whatever
* `contents` you requested (JSON, text, multipart) and may be empty, so dispatch on the query.
*/
function handleEvent({ jobId, status, contentType, body }) {
switch (status) {
case 'success':
console.log(`Job succeeded: ${jobId} (${describeBody(contentType, body)})`);
// Your code: store the transcript from `body`, or fetch it from the API by job id
break;
case 'error':
console.log(`Job failed: ${jobId} (${describeBody(contentType, body)})`);
// Your code: outputs that are not available are left out on error; read the job's errors from the API
break;
case 'fetch_error':
console.log(`Could not fetch the data file for job: ${jobId}`);
break;
case 'trim_error':
console.log(`Could not process the audio file for job: ${jobId}`);
break;
default:
console.log(`Unhandled status: ${status} (job: ${jobId})`);
}
}
function describeBody(contentType, body) {
if (!body || body.length === 0) return 'no body';
return `${contentType || 'unknown type'}, ${body.length} bytes`;
}
// Authenticate first, before the (possibly large) body is read.
function requireSpeechmaticsAuth(req, res, next) {
if (!verifySpeechmaticsRequest(req.headers)) {
return res.status(401).json({ error: 'Invalid or missing webhook auth header' });
}
next();
}
// Raw body, any content type: transcripts, media and multipart all arrive here.
// Speechmatics retries on 413, so keep the limit above the media you request.
const rawBody = express.raw({ type: '*/*', limit: '100mb' });
function receive(req, res) {
const contentType = (req.headers['content-type'] || '').toLowerCase();
const body = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0); // empty body: no parse
// Parse only after authentication, and only JSON content types.
if (body.length > 0 && /json/.test(contentType)) {
try {
JSON.parse(body.toString('utf8'));
} catch {
return res.status(400).json({ error: 'Invalid JSON body' });
}
}
try {
handleEvent({
jobId: req.query.id,
status: req.query.status,
contentType,
body,
});
} catch (err) {
console.error('Error handling Speechmatics notification:', err);
// A non-2xx makes Speechmatics retry until its timeout.
return res.status(500).json({ error: 'Handler error' });
}
res.status(200).json({ received: true });
}
// The notification method is user-chosen: POST (default) or PUT.
app
.route('/webhooks/speechmatics')
.post(requireSpeechmaticsAuth, rawBody, receive)
.put(requireSpeechmaticsAuth, rawBody, receive)
.all((req, res) => res.set('Allow', 'POST, PUT').status(405).json({ error: 'Method not allowed' }));
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = app;
module.exports.verifySpeechmaticsRequest = verifySpeechmaticsRequest;
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 or PUT http://localhost:${PORT}/webhooks/speechmatics`);
});
} // Generated with: speechmatics-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifySpeechmaticsRequest } from '../../../lib/verify-speechmatics';
interface SpeechmaticsNotification {
jobId: string | null;
status: string | null;
contentType: string;
body: Uint8Array;
}
function describeBody(contentType: string, body: Uint8Array): string {
if (body.length === 0) return 'no body';
return `${contentType || 'unknown type'}, ${body.length} bytes`;
}
/**
* Speechmatics appends ?id=<job id>&status=<status> to your URL. The body is whatever
* `contents` you requested (JSON, text, multipart) and may be empty, so dispatch on the query.
*/
function handleEvent({ jobId, status, contentType, body }: SpeechmaticsNotification): void {
switch (status) {
case 'success':
console.log(`Job succeeded: ${jobId} (${describeBody(contentType, body)})`);
// Your code: store the transcript from `body`, or fetch it from the API by job id
break;
case 'error':
console.log(`Job failed: ${jobId} (${describeBody(contentType, body)})`);
// Your code: outputs that are not available are left out on error; read the job's errors from the API
break;
case 'fetch_error':
console.log(`Could not fetch the data file for job: ${jobId}`);
break;
case 'trim_error':
console.log(`Could not process the audio file for job: ${jobId}`);
break;
default:
console.log(`Unhandled status: ${status} (job: ${jobId})`);
}
}
// The notification method is user-chosen: POST (default) or PUT.
async function receive(request: NextRequest) {
// Authenticate before reading the (possibly large) body.
if (!verifySpeechmaticsRequest(request.headers)) {
return NextResponse.json({ error: 'Invalid or missing webhook auth header' }, { status: 401 });
}
// Read the body raw, whatever the content type; it may be empty.
const body = new Uint8Array(await request.arrayBuffer());
const contentType = (request.headers.get('content-type') || '').toLowerCase();
// Parse only after authentication, and only JSON content types.
if (body.length > 0 && /json/.test(contentType)) {
try {
JSON.parse(new TextDecoder().decode(body));
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
}
const { searchParams } = new URL(request.url);
try {
handleEvent({
jobId: searchParams.get('id'),
status: searchParams.get('status'),
contentType,
body,
});
} catch (err) {
console.error('Error handling Speechmatics notification:', err);
// A non-2xx makes Speechmatics retry until its timeout.
return NextResponse.json({ error: 'Handler error' }, { status: 500 });
}
return NextResponse.json({ received: true });
}
export const POST = receive;
export const PUT = receive; # Generated with: speechmatics-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 safe_equal(a: str, b: str) -> bool:
"""Constant-time comparison. Encode both sides: compare_digest raises
TypeError on a non-ASCII str, but accepts any bytes."""
return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))
def verify_speechmatics_request(headers, config=os.environ) -> bool:
"""Speechmatics does not sign notifications. It sends the header you listed
in notification_config[].auth_headers, verbatim. The whole value is compared:
a "Bearer " prefix is part of the value, not parsed off. Starlette headers
are case-insensitive. A static credential authenticates the sender only: no
body signature, no replay protection."""
name = config.get("SPEECHMATICS_WEBHOOK_HEADER") or "Authorization"
expected = config.get("SPEECHMATICS_WEBHOOK_SECRET")
if not expected:
return False # never accept when unconfigured
received = headers.get(name.lower())
return received is not None and safe_equal(received, expected)
async def require_speechmatics_auth(request: Request) -> None:
"""FastAPI dependency: reject the request before the body is read."""
if not verify_speechmatics_request(request.headers):
raise HTTPException(status_code=401, detail="Invalid or missing webhook auth header")
def describe_body(content_type: str, body: bytes) -> str:
return f"{content_type or 'unknown type'}, {len(body)} bytes" if body else "no body"
def handle_event(job_id, status, content_type: str, body: bytes) -> None:
"""Speechmatics appends ?id=<job id>&status=<status> to your URL. The body is
whatever `contents` you requested (JSON, text, multipart) and may be empty,
so dispatch on the query."""
if status == "success":
print(f"Job succeeded: {job_id} ({describe_body(content_type, body)})")
# Your code: store the transcript from `body`, or fetch it from the API by job id
elif status == "error":
print(f"Job failed: {job_id} ({describe_body(content_type, body)})")
# Your code: outputs that are not available are left out on error; read the job's errors from the API
elif status == "fetch_error":
print(f"Could not fetch the data file for job: {job_id}")
elif status == "trim_error":
print(f"Could not process the audio file for job: {job_id}")
else:
print(f"Unhandled status: {status} (job: {job_id})")
# The notification method is user-chosen: POST (default) or PUT.
@app.api_route(
"/webhooks/speechmatics",
methods=["POST", "PUT"],
dependencies=[Depends(require_speechmatics_auth)],
)
async def speechmatics_webhook(request: Request):
# Read the body raw, whatever the content type; it may be empty.
body = await request.body()
content_type = request.headers.get("content-type", "").lower()
# Parse only after authentication, and only JSON content types.
if body and "json" in content_type:
try:
json.loads(body)
except (json.JSONDecodeError, UnicodeDecodeError):
raise HTTPException(status_code=400, detail="Invalid JSON body")
try:
handle_event(
request.query_params.get("id"),
request.query_params.get("status"),
content_type,
body,
)
except Exception as err: # noqa: BLE001
print(f"Error handling Speechmatics notification: {err}")
# A non-2xx makes Speechmatics retry until its timeout.
raise HTTPException(status_code=500, 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 Speechmatics webhooks skill:
npx skills add hookdeck/webhook-skills --skill speechmatics-webhooks
Common failures
Job submitted without the header
auth_headers is set per job, so a job from a script or another service that leaves it out sends a notification with nothing to compare.
Prefix left out of the comparison
For Authorization: Bearer abc123, the value to compare is Bearer abc123, not abc123.
Value rotated while jobs are running
A job keeps the header it was submitted with. Accept the old value until jobs already running have called back.
Route accepts only POST
A notification whose method is put arrives as PUT, so a POST-only route rejects it before your check runs. Accept both.
Let Event Gateway check the Speechmatics header.
Give your Speechmatics source the header name and the whole value you set in auth_headers. Event Gateway compares it on each notification. A request that doesn't match still gets a 200, but it's recorded as failed verification and creates no event. It stores the rest and retries failures on your schedule.