Verify Sigfox webhooks

Sigfox doesn't sign callbacks, so there's no signature to check and no SDK to verify one. You add a secret header to the callback, and your endpoint compares it in constant time. That authenticates the sender, but it doesn't protect the body or stop a replay.

The facts

Signature header
None (unsigned)
What to build
Compare your secret header's whole value with your stored value, in constant time
Key
shared secret

Sigfox webhook secret

You choose the header name and value and add them to the callback. Sigfox generates no secret. Keep it in an environment variable, not in source code.

  • You choose both the header name and the value. Sigfox doesn't generate a secret.
  • Add the pair in the Headers section of the custom callback. Header names can't contain variables, and Authorization is the only standard header Sigfox allows.
  • Sigfox sends the value as you typed it, including any Bearer prefix.
  • You set it on each callback. Event callbacks are created separately, under Event configuration, so add it there too.

Source: Sigfox docs ↗

Code

express/src/index.js
javascript
// Generated with: sigfox-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 comparison. timingSafeEqual throws on unequal lengths, so check
 * lengths first (the length of a random credential isn't a useful secret).
 */
function safeEqual(a, b) {
  const x = Buffer.from(String(a), 'utf8');
  const y = Buffer.from(String(b), 'utf8');
  return x.length === y.length && crypto.timingSafeEqual(x, y);
}

/**
 * Sigfox callbacks are not signed. You add a secret header to the callback's Headers;
 * the header name is yours (SIGFOX_WEBHOOK_HEADER, default Authorization) and the
 * expected value is the exact whole header value (SIGFOX_WEBHOOK_SECRET), including
 * any "Bearer " prefix you typed. A static credential authenticates the sender, not
 * the body, and gives no replay protection.
 */
function verifySigfoxRequest(
  headers,
  secret = process.env.SIGFOX_WEBHOOK_SECRET,
  name = process.env.SIGFOX_WEBHOOK_HEADER || 'Authorization'
) {
  if (!secret) return false; // never accept when unconfigured
  const received = headers[name.toLowerCase()]; // Node lowercases header names
  return typeof received === 'string' && received !== '' && safeEqual(received, secret);
}

/**
 * The callback type isn't in the request, so infer it from the variables present.
 */
function classifyCallback(p) {
  if ('eventType' in p) return 'event'; // Event callbacks also carry severity
  if ('severity' in p) return 'error';
  if ('infoCode' in p) return 'service acknowledge';
  if ('repeatedMsg' in p) return 'service repeater';
  if ('lqi' in p || 'linkQuality' in p) return 'data advanced';
  if ('ack' in p || 'longPolling' in p) return 'data bidir';
  if ('batt' in p || 'temp' in p) return 'service status';
  if ('data' in p) return 'data uplink';
  return 'unknown';
}

function handleCallback(payload) {
  const type = classifyCallback(payload);

  switch (type) {
    case 'data uplink':
      console.log(`Uplink from ${payload.device}: ${payload.data} (seq ${payload.seqNumber})`);
      // Your code: decode payload.data (hex) and store the reading
      break;

    case 'data bidir':
      console.log(`Bidir uplink from ${payload.device}, ack=${payload.ack}`);
      // Your code: respond with downlink data if payload.ack is true
      break;

    case 'data advanced':
      console.log(`Advanced data from ${payload.device}, link quality ${payload.lqi}`);
      // Your code: store link quality and duplicate metadata
      break;

    case 'service status':
      console.log(`Status from ${payload.device}: battery ${payload.batt} V, temp ${payload.temp}`);
      // Your code: update device health
      break;

    case 'service acknowledge':
      console.log(`Downlink ack for ${payload.device}: code ${payload.infoCode}`);
      // Your code: mark the downlink delivered or failed
      break;

    case 'service repeater':
      console.log(`Repeater ${payload.device}: ${payload.repeatedMsg} repeated messages`);
      // Your code: record repeater stats
      break;

    case 'error':
      console.log(`Error for ${payload.device}: ${payload.info} (${payload.severity})`);
      // Your code: alert that the device missed its keep-alive
      break;

    case 'event':
      console.log(`Event ${payload.eventType} for ${payload.sourceId}`);
      // Your code: react to the device's lifecycle or subscription change
      break;

    default:
      console.log('Unhandled Sigfox callback');
  }

  return type;
}

/**
 * Variables arrive in the query string (GET) and/or the body template (POST/PUT, JSON or
 * form-encoded). Throws on a body that can't be parsed into an object.
 */
function parsePayload(req) {
  const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
  let body = {};
  if (raw.trim() !== '') {
    const contentType = String(req.headers['content-type'] || '').toLowerCase();
    body = contentType.includes('application/x-www-form-urlencoded')
      ? Object.fromEntries(new URLSearchParams(raw))
      : JSON.parse(raw);
    if (!body || typeof body !== 'object' || Array.isArray(body)) {
      throw new Error('Expected an object');
    }
  }
  return { ...req.query, ...body };
}

function sigfoxHandler(req, res) {
  // Authenticate before parsing anything.
  if (!verifySigfoxRequest(req.headers)) {
    return res.status(401).json({ error: 'Invalid or missing credential header' });
  }

  let payload;
  try {
    payload = parsePayload(req);
  } catch {
    return res.status(400).json({ error: 'Invalid body' });
  }

  try {
    const type = handleCallback(payload);
    return res.status(200).json({ received: true, type });
  } catch (err) {
    console.error('Error handling Sigfox callback:', err);
    return res.status(500).json({ error: 'Handler error' });
  }
}

// Read the body raw (any content type); the method is user-chosen, so accept GET, POST and PUT.
app
  .route('/webhooks/sigfox')
  .get(express.raw({ type: '*/*' }), sigfoxHandler)
  .post(express.raw({ type: '*/*' }), sigfoxHandler)
  .put(express.raw({ type: '*/*' }), sigfoxHandler)
  .all((req, res) => res.status(405).set('Allow', 'GET, POST, PUT').json({ error: 'Method not allowed' }));

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = app;
module.exports.verifySigfoxRequest = verifySigfoxRequest;
module.exports.classifyCallback = classifyCallback;

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: GET/POST/PUT http://localhost:${PORT}/webhooks/sigfox`);
  });
}
nextjs/app/webhooks/sigfox/route.ts
typescript
// Generated with: sigfox-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { classifyCallback, verifySigfoxRequest } from '../../../lib/verify-sigfox';

type Payload = Record<string, unknown>;

function handleCallback(payload: Payload): string {
  const type = classifyCallback(payload);

  switch (type) {
    case 'data uplink':
      console.log(`Uplink from ${payload.device}: ${payload.data} (seq ${payload.seqNumber})`);
      // Your code: decode payload.data (hex) and store the reading
      break;

    case 'data bidir':
      console.log(`Bidir uplink from ${payload.device}, ack=${payload.ack}`);
      // Your code: respond with downlink data if payload.ack is true
      break;

    case 'data advanced':
      console.log(`Advanced data from ${payload.device}, link quality ${payload.lqi}`);
      // Your code: store link quality and duplicate metadata
      break;

    case 'service status':
      console.log(`Status from ${payload.device}: battery ${payload.batt} V, temp ${payload.temp}`);
      // Your code: update device health
      break;

    case 'service acknowledge':
      console.log(`Downlink ack for ${payload.device}: code ${payload.infoCode}`);
      // Your code: mark the downlink delivered or failed
      break;

    case 'service repeater':
      console.log(`Repeater ${payload.device}: ${payload.repeatedMsg} repeated messages`);
      // Your code: record repeater stats
      break;

    case 'error':
      console.log(`Error for ${payload.device}: ${payload.info} (${payload.severity})`);
      // Your code: alert that the device missed its keep-alive
      break;

    case 'event':
      console.log(`Event ${payload.eventType} for ${payload.sourceId}`);
      // Your code: react to the device's lifecycle or subscription change
      break;

    default:
      console.log('Unhandled Sigfox callback');
  }

  return type;
}

/**
 * Variables arrive in the query string (GET) and/or the body template (POST/PUT, JSON or
 * form-encoded). Throws on a body that can't be parsed into an object.
 */
function parsePayload(request: NextRequest, raw: string): Payload {
  let body: Payload = {};
  if (raw.trim() !== '') {
    const contentType = (request.headers.get('content-type') || '').toLowerCase();
    const parsed: unknown = contentType.includes('application/x-www-form-urlencoded')
      ? Object.fromEntries(new URLSearchParams(raw))
      : JSON.parse(raw);
    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
      throw new Error('Expected an object');
    }
    body = parsed as Payload;
  }
  const query = Object.fromEntries(request.nextUrl.searchParams);
  return { ...query, ...body };
}

async function handle(request: NextRequest) {
  // Authenticate before reading or parsing the body.
  if (!verifySigfoxRequest(request.headers)) {
    return NextResponse.json({ error: 'Invalid or missing credential header' }, { status: 401 });
  }

  let payload: Payload;
  try {
    // Read as text so any content type (and an empty body) is accepted.
    payload = parsePayload(request, await request.text());
  } catch {
    return NextResponse.json({ error: 'Invalid body' }, { status: 400 });
  }

  try {
    const type = handleCallback(payload);
    return NextResponse.json({ received: true, type });
  } catch (err) {
    console.error('Error handling Sigfox callback:', err);
    return NextResponse.json({ error: 'Handler error' }, { status: 500 });
  }
}

// The method is user-chosen in the Sigfox callback, so accept GET, POST and PUT.
export const GET = handle;
export const POST = handle;
export const PUT = handle;
fastapi/main.py
python
# Generated with: sigfox-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hmac
import json
import os
from urllib.parse import parse_qsl

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
    non-ASCII str, but accepts bytes of any content."""
    return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))


def verify_sigfox_request(headers, secret=None, name=None) -> bool:
    """Sigfox callbacks are not signed. You add a secret header to the callback's Headers;
    the header name is yours (SIGFOX_WEBHOOK_HEADER, default Authorization) and the
    expected value is the exact whole header value (SIGFOX_WEBHOOK_SECRET), including any
    "Bearer " prefix you typed. A static credential authenticates the sender, not the
    body, and gives no replay protection.
    """
    secret = secret if secret is not None else os.environ.get("SIGFOX_WEBHOOK_SECRET", "")
    name = name or os.environ.get("SIGFOX_WEBHOOK_HEADER") or "Authorization"
    if not secret:
        return False  # never accept when unconfigured
    received = headers.get(name)  # Starlette headers are case-insensitive
    return bool(received) and safe_equal(received, secret)


async def require_sigfox_credential(request: Request) -> None:
    """FastAPI dependency: reject the request before the body is parsed."""
    if not verify_sigfox_request(request.headers):
        raise HTTPException(status_code=401, detail="Invalid or missing credential header")


def classify_callback(p: dict) -> str:
    """The callback type isn't in the request, so infer it from the variables present."""
    if "eventType" in p:  # Event callbacks also carry severity
        return "event"
    if "severity" in p:
        return "error"
    if "infoCode" in p:
        return "service acknowledge"
    if "repeatedMsg" in p:
        return "service repeater"
    if "lqi" in p or "linkQuality" in p:
        return "data advanced"
    if "ack" in p or "longPolling" in p:
        return "data bidir"
    if "batt" in p or "temp" in p:
        return "service status"
    if "data" in p:
        return "data uplink"
    return "unknown"


def handle_callback(payload: dict) -> str:
    callback_type = classify_callback(payload)

    if callback_type == "data uplink":
        print(f"Uplink from {payload.get('device')}: {payload.get('data')} (seq {payload.get('seqNumber')})")
        # Your code: decode payload["data"] (hex) and store the reading

    elif callback_type == "data bidir":
        print(f"Bidir uplink from {payload.get('device')}, ack={payload.get('ack')}")
        # Your code: respond with downlink data if payload["ack"] is true

    elif callback_type == "data advanced":
        print(f"Advanced data from {payload.get('device')}, link quality {payload.get('lqi')}")
        # Your code: store link quality and duplicate metadata

    elif callback_type == "service status":
        print(f"Status from {payload.get('device')}: battery {payload.get('batt')} V, temp {payload.get('temp')}")
        # Your code: update device health

    elif callback_type == "service acknowledge":
        print(f"Downlink ack for {payload.get('device')}: code {payload.get('infoCode')}")
        # Your code: mark the downlink delivered or failed

    elif callback_type == "service repeater":
        print(f"Repeater {payload.get('device')}: {payload.get('repeatedMsg')} repeated messages")
        # Your code: record repeater stats

    elif callback_type == "error":
        print(f"Error for {payload.get('device')}: {payload.get('info')} ({payload.get('severity')})")
        # Your code: alert that the device missed its keep-alive

    elif callback_type == "event":
        print(f"Event {payload.get('eventType')} for {payload.get('sourceId')}")
        # Your code: react to the device's lifecycle or subscription change

    else:
        print("Unhandled Sigfox callback")

    return callback_type


def parse_payload(request: Request, raw_body: bytes) -> dict:
    """Variables arrive in the query string (GET) and/or the body template (POST/PUT, JSON
    or form-encoded). Raises ValueError on a body that can't be parsed into an object."""
    body: dict = {}
    text = raw_body.decode("utf-8").strip()  # UnicodeDecodeError is a ValueError
    if text:
        content_type = request.headers.get("content-type", "").lower()
        if "application/x-www-form-urlencoded" in content_type:
            body = dict(parse_qsl(text, keep_blank_values=True))
        else:
            body = json.loads(text)  # JSONDecodeError is a ValueError
            if not isinstance(body, dict):
                raise ValueError("Expected an object")
    return {**dict(request.query_params), **body}


# The method is user-chosen in the Sigfox callback, so accept GET, POST and PUT.
@app.api_route(
    "/webhooks/sigfox",
    methods=["GET", "POST", "PUT"],
    dependencies=[Depends(require_sigfox_credential)],
)
async def sigfox_webhook(request: Request):
    # Read the raw body so any content type (and an empty body) is accepted.
    raw_body = await request.body()

    try:
        payload = parse_payload(request, raw_body)
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid body")

    try:
        callback_type = handle_callback(payload)
    except Exception as err:  # noqa: BLE001
        print(f"Error handling Sigfox callback: {err}")
        raise HTTPException(status_code=500, detail="Handler error")

    return {"received": True, "type": callback_type}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

From hookdeck/webhook-skills ↗

Or install the Sigfox webhooks skill:

npx skills add hookdeck/webhook-skills --skill sigfox-webhooks

Common failures

Comparing part of the value

Sigfox sends the value as you typed it. If you typed Bearer abc123, compare against Bearer abc123, not abc123.

A callback without the header

Headers are set per callback. A new callback, or an Event callback created under Event configuration, fails until you add the header to it as well.

Changing the secret on one side

Each callback holds its own copy. Accept both values while you update every callback, because Sigfox only retries for a few minutes.

URL credentials and an Authorization header together

Sigfox warns against an Authorization header when the URL also holds login:password@. Use one or the other.

From Hookdeck's Sigfox guide

Let Event Gateway check Sigfox's secret header.

Event Gateway compares the header you name with the exact value you enter on each Sigfox callback, before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with Sigfox. Facts are compiled from public sources and linked inline.