Verify Invoice Ninja webhooks
Invoice Ninja doesn't sign its webhooks. You add a secret header of your own to each subscription, Invoice Ninja sends it on every delivery, and you compare its whole value in constant time. A match shows the sender knows your value, but nothing covers the body, and a captured request can be replayed.
The facts
Compare your secret header's whole value with your stored value, in constant time Invoice Ninja webhook secret
You choose the header name and value, and store them on the webhook subscription (headers is fillable), in the app's header key and value fields or through the API. Keep it in an environment variable, not in source code.
- You choose both the header name and the value. Invoice Ninja doesn't generate a secret.
- Add the pair in the Header Key and Header Value fields when you create the webhook, or in
headerswithPOST /api/v1/webhooks. - Invoice Ninja sends the value as you typed it on every delivery, including any
Bearerprefix. - It belongs to one subscription, and a subscription has one event, so rotating means updating every subscription.
- The webhooks API returns
headers, so an API token that can read your webhooks can read the secret.
Source: Invoice Ninja docs ↗
Code
// Generated with: invoice-ninja-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');
const app = express();
// Invoice Ninja sends the webhook with the subscription's rest_method, which its server
// validates as post (the default) or put.
const ALLOWED_METHODS = ['POST', 'PUT'];
/**
* 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);
}
/**
* Invoice Ninja does not sign payloads. You add a secret header (key/value) to the
* webhook; the header name is yours, so it comes from configuration. The WHOLE value
* is compared, including any "Bearer " prefix you typed: nothing is stripped or parsed.
* Node lower-cases header names, which makes the lookup case-insensitive.
*/
function verifyInvoiceNinjaRequest(
headers,
secret = process.env.INVOICE_NINJA_WEBHOOK_SECRET,
headerName = process.env.INVOICE_NINJA_WEBHOOK_HEADER || 'Authorization'
) {
if (!secret) return false; // never accept when unconfigured
const received = headers[headerName.toLowerCase()];
return Boolean(received) && safeEqual(received, secret);
}
/**
* The body is the entity itself (transformer output) and has NO event field. The
* event key (create_invoice, ...) only names the subscription, so route by URL
* (add ?event=create_invoice to the target URL) or fall back to the entity's shape.
*/
function detectEntity(payload) {
if (Array.isArray(payload.line_items)) return 'document'; // invoice, quote, credit, purchase order
if ('applied' in payload) return 'payment';
if (Array.isArray(payload.contacts) && 'paid_to_date' in payload) return 'client'; // vendors have contacts too
return 'unknown';
}
function handleEntity(event, payload) {
const entity = event ? null : detectEntity(payload);
if (event === 'create_invoice') {
console.log(`Invoice created: ${payload.number} (${payload.id})`);
// Your code: sync the new invoice (payload.amount, payload.client_id, payload.line_items)
} else if (event === 'create_payment') {
console.log(`Payment created: ${payload.number} (${payload.id})`);
// Your code: record the payment (payload.amount, payload.client_id, payload.invoices)
} else if (event === 'update_client') {
console.log(`Client updated: ${payload.name} (${payload.id})`);
// Your code: refresh the client record (payload.contacts)
} else if (event) {
console.log(`Unhandled event: ${event}`);
} else if (entity === 'document') {
console.log(`Document received: ${payload.number} (${payload.id})`);
} else if (entity === 'payment') {
console.log(`Payment received: ${payload.number} (${payload.id})`);
} else if (entity === 'client') {
console.log(`Client received: ${payload.name} (${payload.id})`);
} else {
console.log('Unrecognised entity shape');
}
}
// Read the body raw (any content type) so the request is authenticated before parsing.
// Never answer 404, 405 or 410: Invoice Ninja archives the webhook subscription when it sees them.
app.all('/webhooks/invoice-ninja', express.raw({ type: '*/*' }), (req, res) => {
if (!verifyInvoiceNinjaRequest(req.headers)) {
return res.status(401).json({ error: 'Invalid or missing webhook credential' });
}
if (!ALLOWED_METHODS.includes(req.method)) {
return res.status(400).json({ error: `Unsupported method ${req.method}` });
}
// Invoice Ninja always sends a JSON body; an empty one is still acknowledged.
const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
let payload = {};
if (raw.trim() !== '') {
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 {
handleEntity(typeof req.query.event === 'string' ? req.query.event : null, payload);
} catch (err) {
console.error('Error handling Invoice Ninja webhook:', err);
return res.status(500).json({ error: 'Handler error' });
}
res.status(200).json({ received: true });
});
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = app;
module.exports.verifyInvoiceNinjaRequest = verifyInvoiceNinjaRequest;
module.exports.detectEntity = detectEntity;
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|PUT http://localhost:${PORT}/webhooks/invoice-ninja`);
});
} // Generated with: invoice-ninja-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { detectEntity, verifyInvoiceNinjaRequest } from '../../../lib/verify-invoice-ninja';
// Deliveries are never cacheable: the credential check reads request headers.
export const dynamic = 'force-dynamic';
type InvoiceNinjaEntity = Record<string, unknown>;
function handleEntity(event: string | null, payload: InvoiceNinjaEntity): void {
const entity = event ? null : detectEntity(payload);
if (event === 'create_invoice') {
console.log(`Invoice created: ${payload.number} (${payload.id})`);
// Your code: sync the new invoice (payload.amount, payload.client_id, payload.line_items)
} else if (event === 'create_payment') {
console.log(`Payment created: ${payload.number} (${payload.id})`);
// Your code: record the payment (payload.amount, payload.client_id, payload.invoices)
} else if (event === 'update_client') {
console.log(`Client updated: ${payload.name} (${payload.id})`);
// Your code: refresh the client record (payload.contacts)
} else if (event) {
console.log(`Unhandled event: ${event}`);
} else if (entity === 'document') {
console.log(`Document received: ${payload.number} (${payload.id})`);
} else if (entity === 'payment') {
console.log(`Payment received: ${payload.number} (${payload.id})`);
} else if (entity === 'client') {
console.log(`Client received: ${payload.name} (${payload.id})`);
} else {
console.log('Unrecognised entity shape');
}
}
// The method is the Invoice Ninja subscription's rest_method, which its server validates as
// post (the default) or put, so the same handler serves POST and PUT.
// Never answer 404, 405 or 410: Invoice Ninja archives the webhook subscription when it sees them.
async function handle(request: NextRequest) {
// Authenticate before reading or parsing the body.
if (!verifyInvoiceNinjaRequest(request.headers)) {
return NextResponse.json({ error: 'Invalid or missing webhook credential' }, { status: 401 });
}
// Read as text so any content type is accepted. Invoice Ninja always sends a JSON body;
// an empty one is still acknowledged.
const raw = await request.text();
let payload: InvoiceNinjaEntity = {};
if (raw.trim() !== '') {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return NextResponse.json({ error: 'Expected a JSON object' }, { status: 400 });
}
payload = parsed as InvoiceNinjaEntity;
}
try {
handleEntity(request.nextUrl.searchParams.get('event'), payload);
} catch (err) {
console.error('Error handling Invoice Ninja webhook:', err);
return NextResponse.json({ error: 'Handler error' }, { status: 500 });
}
return NextResponse.json({ received: true });
}
export const POST = handle;
export const PUT = handle; # Generated with: invoice-ninja-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hmac
import json
import os
from typing import Optional
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
load_dotenv()
app = FastAPI()
# Invoice Ninja sends the webhook with the subscription's rest_method, which its server
# validates as post (the default) or put.
ALLOWED_METHODS = ["POST", "PUT"]
def safe_equal(a: str, b: str) -> bool:
"""Constant-time comparison. Encode both sides: compare_digest raises TypeError on
non-ASCII str, and returns False (without raising) for bytes of different lengths."""
return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))
def verify_invoice_ninja_request(headers, secret: Optional[str] = None, header_name: Optional[str] = None) -> bool:
"""Invoice Ninja does not sign payloads. You add a secret header (key/value) to the
webhook; the header name is yours, so it comes from configuration. The WHOLE value is
compared, including any "Bearer " prefix you typed: nothing is stripped or parsed.
The lookup is case-insensitive.
"""
secret = secret if secret is not None else os.environ.get("INVOICE_NINJA_WEBHOOK_SECRET")
header_name = header_name or os.environ.get("INVOICE_NINJA_WEBHOOK_HEADER") or "Authorization"
if not secret:
return False # never accept when unconfigured
received = {k.lower(): v for k, v in headers.items()}.get(header_name.lower())
return bool(received) and safe_equal(received, secret)
async def require_invoice_ninja_credential(request: Request) -> None:
"""FastAPI dependency: reject the request before the body is read or parsed.
401, never 404/405/410: Invoice Ninja archives the webhook subscription on those."""
if not verify_invoice_ninja_request(request.headers):
raise HTTPException(status_code=401, detail="Invalid or missing webhook credential")
def detect_entity(payload: dict) -> str:
"""The body is the entity itself (transformer output) and has NO event field. The event
key (create_invoice, ...) only names the subscription, so route by URL (add
?event=create_invoice to the target URL) or fall back to the entity's shape."""
if isinstance(payload.get("line_items"), list):
return "document" # invoice, quote, credit, purchase order
if "applied" in payload:
return "payment"
if isinstance(payload.get("contacts"), list) and "paid_to_date" in payload: # vendors have contacts too
return "client"
return "unknown"
def handle_entity(event: Optional[str], payload: dict) -> None:
entity = None if event else detect_entity(payload)
if event == "create_invoice":
print(f"Invoice created: {payload.get('number')} ({payload.get('id')})")
# Your code: sync the new invoice (payload["amount"], payload["client_id"], payload["line_items"])
elif event == "create_payment":
print(f"Payment created: {payload.get('number')} ({payload.get('id')})")
# Your code: record the payment (payload["amount"], payload["client_id"], payload["invoices"])
elif event == "update_client":
print(f"Client updated: {payload.get('name')} ({payload.get('id')})")
# Your code: refresh the client record (payload["contacts"])
elif event:
print(f"Unhandled event: {event}")
elif entity == "document":
print(f"Document received: {payload.get('number')} ({payload.get('id')})")
elif entity == "payment":
print(f"Payment received: {payload.get('number')} ({payload.get('id')})")
elif entity == "client":
print(f"Client received: {payload.get('name')} ({payload.get('id')})")
else:
print("Unrecognised entity shape")
@app.api_route(
"/webhooks/invoice-ninja",
methods=ALLOWED_METHODS,
dependencies=[Depends(require_invoice_ninja_credential)],
)
async def invoice_ninja_webhook(request: Request):
# Raw bytes, any content type. Invoice Ninja always sends a JSON body; an empty one is still acknowledged.
raw = (await request.body()).decode("utf-8", errors="replace")
payload: dict = {}
if raw.strip():
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON body")
if not isinstance(parsed, dict):
raise HTTPException(status_code=400, detail="Expected a JSON object")
payload = parsed
try:
handle_entity(request.query_params.get("event"), payload)
except Exception as exc: # noqa: BLE001
print(f"Error handling Invoice Ninja webhook: {exc}")
raise HTTPException(status_code=500, detail="Handler error")
return {"received": True}
@app.get("/health")
async def health():
return {"status": "ok"} Or install the Invoice Ninja webhooks skill:
npx skills add hookdeck/webhook-skills --skill invoice-ninja-webhooks
Common failures
Comparing part of the value
Invoice Ninja sends the value as you typed it. If you typed Bearer abc123, compare against Bearer abc123, not abc123.
A proxy removes the header
The header name is yours, and some proxies strip Authorization. If only proxied requests fail, use a custom name such as X-Invoice-Ninja-Secret.
Changing the secret on one side
Each subscription holds its own copy, and a 401 isn't retried. Accept both values while you update every subscription, or the events in between are lost.
Let Event Gateway check Invoice Ninja's secret header.
Event Gateway compares the header you name with the exact value you enter on each Invoice Ninja delivery, before it reaches your service, then queues it and retries failures on your schedule.