Verify parcelLab webhooks

parcelLab doesn't sign webhook requests, so there's no signature to check and no SDK to verify one. With HTTP Basic authentication, each request carries an Authorization: Basic header built from the username and password you gave parcelLab, and your endpoint compares both 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 the Basic username and password with your stored values
Key
shared secret

parcelLab webhook secret

parcelLab issues no secret. You choose the credentials and give them to parcelLab with your HTTPS URL. The docs describe no screen or API for doing this yourself. Keep it in an environment variable, not in source code.

  • For HTTP Basic, choose a username and a long random password
  • The docs also list access token headers and an OAuth 2.0 access token, but name no header or token flow for either, so ask parcelLab what it sends
  • The docs describe no way to rotate credentials yourself, so agree new values with parcelLab and change both sides together

Source: parcelLab docs ↗

Code

express/src/index.js
javascript
// Generated with: parcellab-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');

const app = express();

const CLOUDEVENT_TYPE_PREFIX = 'com.parcellab.tracking.event.';
const EVENTS = [
  'onCreated',
  'onUpdated',
  'onDispatch',
  'onScheduled',
  'onDelay',
  'onInternalDelay',
  'onOutForDelivery',
  'onFailedAttempt',
  'onPickupReady',
  'onDelivered',
  'onReturn',
];
const EVENTS_BY_LOWERCASE = new Map(EVENTS.map((name) => [name.toLowerCase(), name]));

/**
 * Constant-time comparison. Hashing both sides first gives equal-length buffers,
 * so timingSafeEqual never throws and the credential's length isn't leaked.
 */
function safeEqual(a, b) {
  const ha = crypto.createHash('sha256').update(a).digest();
  const hb = crypto.createHash('sha256').update(b).digest();
  return crypto.timingSafeEqual(ha, hb);
}

/**
 * parcelLab does not sign payloads. It sends the HTTP Basic credentials you gave it:
 * `Authorization: Basic base64(username:password)`. Split on the FIRST colon (the
 * password may contain colons), then compare username and password each in constant
 * time. Both comparisons run before the decision, so there is no short-circuit.
 */
function verifyParcellabRequest(headers, config = process.env) {
  const username = config.PARCELLAB_WEBHOOK_USERNAME;
  const password = config.PARCELLAB_WEBHOOK_PASSWORD;
  if (!username || !password) return false; // never accept when unconfigured

  const match = /^basic\s+([A-Za-z0-9+/]+={0,2})\s*$/i.exec(headers['authorization'] || '');
  if (!match) return false;

  const decoded = Buffer.from(match[1], 'base64');
  const colon = decoded.indexOf(0x3a);
  if (colon < 0) return false;

  const usernameOk = safeEqual(decoded.subarray(0, colon), Buffer.from(username, 'utf8'));
  const passwordOk = safeEqual(decoded.subarray(colon + 1), Buffer.from(password, 'utf8'));
  return usernameOk && passwordOk;
}

/**
 * Native payloads carry `event` (for example onDelivered). In CloudEvents format the
 * `type` is com.parcellab.tracking.event.<lowercased event>, e.g. ...event.ondelivered.
 */
function getEventName(payload) {
  if (typeof payload.event === 'string') return payload.event;
  if (typeof payload.type === 'string' && payload.type.startsWith(CLOUDEVENT_TYPE_PREFIX)) {
    const lowercased = payload.type.slice(CLOUDEVENT_TYPE_PREFIX.length).toLowerCase();
    // Accept the lowercased event name with or without the `on` prefix.
    return EVENTS_BY_LOWERCASE.get(lowercased) || EVENTS_BY_LOWERCASE.get(`on${lowercased}`) || null;
  }
  return null;
}

function handleEvent(payload) {
  const event = getEventName(payload);
  // Native: references at the top level. CloudEvents: nested in `data`.
  const references = payload.references || (payload.data && payload.data.references) || {};
  const tracking = references.tracking_number;

  switch (event) {
    case 'onCreated':
    case 'onUpdated':
      console.log(`Record ${event === 'onCreated' ? 'created' : 'updated'} for ${tracking}`);
      // Your code: sync the order/tracking record
      break;

    case 'onDispatch':
      console.log(`Shipment ${tracking} dispatched`);
      // Your code: mark the order as shipped
      break;

    case 'onScheduled':
      console.log(`Delivery scheduled for ${tracking}`);
      // Your code: store the announced delivery date or time window
      break;

    case 'onOutForDelivery':
      console.log(`Shipment ${tracking} is out for delivery`);
      break;

    case 'onDelay':
    case 'onInternalDelay':
    case 'onFailedAttempt':
      console.log(`Delivery problem (${event}) for ${tracking}`);
      // Your code: alert support or notify the customer
      break;

    case 'onPickupReady':
      console.log(`Shipment ${tracking} is ready for pickup`);
      break;

    case 'onDelivered':
      console.log(`Shipment ${tracking} delivered`);
      // Your code: mark the order as delivered
      break;

    case 'onReturn':
      console.log(`Shipment ${tracking} is being returned to the sender`);
      // Your code: start your returns flow
      break;

    default:
      console.log('Unhandled parcelLab event:', event || '(none)');
  }
}

// Read the body raw so the request is authenticated before anything is parsed,
// whatever Content-Type parcelLab uses (application/json or cloudevents+json).
app.post('/webhooks/parcellab', express.raw({ type: '*/*' }), (req, res) => {
  if (!verifyParcellabRequest(req.headers)) {
    return res.status(401).json({ error: 'Invalid or missing Basic credentials' });
  }

  let payload;
  try {
    const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
    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 {
    handleEvent(payload);
  } catch (err) {
    console.error('Error handling parcelLab 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.verifyParcellabRequest = verifyParcellabRequest;
module.exports.getEventName = getEventName;

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/parcellab`);
  });
}
nextjs/app/webhooks/parcellab/route.ts
typescript
// Generated with: parcellab-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { getEventName, verifyParcellabRequest } from '../../../lib/verify-parcellab';

function handleEvent(payload: Record<string, unknown>): void {
  const event = getEventName(payload);
  // Native: references at the top level. CloudEvents: nested in `data`.
  const data = (payload.data ?? {}) as Record<string, unknown>;
  const references = (payload.references ?? data.references ?? {}) as Record<string, unknown>;
  const tracking = references.tracking_number;

  switch (event) {
    case 'onCreated':
    case 'onUpdated':
      console.log(`Record ${event === 'onCreated' ? 'created' : 'updated'} for ${tracking}`);
      // Your code: sync the order/tracking record
      break;

    case 'onDispatch':
      console.log(`Shipment ${tracking} dispatched`);
      // Your code: mark the order as shipped
      break;

    case 'onScheduled':
      console.log(`Delivery scheduled for ${tracking}`);
      // Your code: store the announced delivery date or time window
      break;

    case 'onOutForDelivery':
      console.log(`Shipment ${tracking} is out for delivery`);
      break;

    case 'onDelay':
    case 'onInternalDelay':
    case 'onFailedAttempt':
      console.log(`Delivery problem (${event}) for ${tracking}`);
      // Your code: alert support or notify the customer
      break;

    case 'onPickupReady':
      console.log(`Shipment ${tracking} is ready for pickup`);
      break;

    case 'onDelivered':
      console.log(`Shipment ${tracking} delivered`);
      // Your code: mark the order as delivered
      break;

    case 'onReturn':
      console.log(`Shipment ${tracking} is being returned to the sender`);
      // Your code: start your returns flow
      break;

    default:
      console.log('Unhandled parcelLab event:', event || '(none)');
  }
}

export async function POST(request: NextRequest) {
  // Authenticate before reading or parsing the body.
  if (!verifyParcellabRequest(request.headers)) {
    return NextResponse.json({ error: 'Invalid or missing Basic credentials' }, { status: 401 });
  }

  let payload: unknown;
  try {
    // Read the raw text so any content type works.
    payload = JSON.parse(await request.text());
  } catch {
    return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
  }

  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
    return NextResponse.json({ error: 'Expected a JSON object' }, { status: 400 });
  }

  try {
    handleEvent(payload as Record<string, unknown>);
  } catch (err) {
    console.error('Error handling parcelLab webhook:', err);
    return NextResponse.json({ error: 'Handler error' }, { status: 500 });
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
# Generated with: parcellab-webhooks skill
# https://github.com/hookdeck/webhook-skills
import base64
import binascii
import hmac
import json
import os
import re

from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()

CLOUDEVENT_TYPE_PREFIX = "com.parcellab.tracking.event."
EVENTS = [
    "onCreated",
    "onUpdated",
    "onDispatch",
    "onScheduled",
    "onDelay",
    "onInternalDelay",
    "onOutForDelivery",
    "onFailedAttempt",
    "onPickupReady",
    "onDelivered",
    "onReturn",
]
EVENTS_BY_LOWERCASE = {name.lower(): name for name in EVENTS}

BASIC_RE = re.compile(r"^basic\s+([A-Za-z0-9+/]+={0,2})\s*$", re.IGNORECASE)


def verify_parcellab_request(headers, config=os.environ) -> bool:
    """parcelLab does not sign payloads. It sends the HTTP Basic credentials you gave it:
    `Authorization: Basic base64(username:password)`. Split on the FIRST colon (the
    password may contain colons), then compare username and password each in constant
    time. Both comparisons run before the decision, so there is no short-circuit.
    """
    username = config.get("PARCELLAB_WEBHOOK_USERNAME")
    password = config.get("PARCELLAB_WEBHOOK_PASSWORD")
    if not username or not password:
        return False  # never accept when unconfigured

    match = BASIC_RE.match(headers.get("authorization") or "")
    if not match:
        return False
    try:
        decoded = base64.b64decode(match.group(1), validate=True)
    except (binascii.Error, ValueError):
        return False

    received_user, sep, received_password = decoded.partition(b":")
    if not sep:
        return False

    # compare_digest needs bytes here: str raises TypeError on non-ASCII input.
    username_ok = hmac.compare_digest(received_user, username.encode("utf-8"))
    password_ok = hmac.compare_digest(received_password, password.encode("utf-8"))
    return username_ok and password_ok


def get_event_name(payload: dict):
    """Native payloads carry `event` (for example onDelivered). In CloudEvents format the
    `type` is com.parcellab.tracking.event.<lowercased event>, e.g. ...event.ondelivered."""
    event = payload.get("event")
    if isinstance(event, str):
        return event
    type_ = payload.get("type")
    if isinstance(type_, str) and type_.startswith(CLOUDEVENT_TYPE_PREFIX):
        lowercased = type_[len(CLOUDEVENT_TYPE_PREFIX):].lower()
        # Accept the lowercased event name with or without the `on` prefix.
        return EVENTS_BY_LOWERCASE.get(lowercased) or EVENTS_BY_LOWERCASE.get(f"on{lowercased}")
    return None


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


def handle_event(payload: dict) -> None:
    event = get_event_name(payload)
    # Native: references at the top level. CloudEvents: nested in `data`.
    data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
    references = payload.get("references") or data.get("references") or {}
    tracking = references.get("tracking_number")

    if event in ("onCreated", "onUpdated"):
        print(f"Record {'created' if event == 'onCreated' else 'updated'} for {tracking}")
        # Your code: sync the order/tracking record

    elif event == "onDispatch":
        print(f"Shipment {tracking} dispatched")
        # Your code: mark the order as shipped

    elif event == "onScheduled":
        print(f"Delivery scheduled for {tracking}")
        # Your code: store the announced delivery date or time window

    elif event == "onOutForDelivery":
        print(f"Shipment {tracking} is out for delivery")

    elif event in ("onDelay", "onInternalDelay", "onFailedAttempt"):
        print(f"Delivery problem ({event}) for {tracking}")
        # Your code: alert support or notify the customer

    elif event == "onPickupReady":
        print(f"Shipment {tracking} is ready for pickup")

    elif event == "onDelivered":
        print(f"Shipment {tracking} delivered")
        # Your code: mark the order as delivered

    elif event == "onReturn":
        print(f"Shipment {tracking} is being returned to the sender")
        # Your code: start your returns flow

    else:
        print(f"Unhandled parcelLab event: {event or '(none)'}")


@app.post("/webhooks/parcellab", dependencies=[Depends(require_parcellab_auth)])
async def parcellab_webhook(request: Request):
    # Read the raw body so any content type works.
    raw_body = await request.body()

    try:
        payload = json.loads(raw_body)
    except (json.JSONDecodeError, UnicodeDecodeError):
        raise HTTPException(status_code=400, detail="Invalid JSON body")

    if not isinstance(payload, dict):
        raise HTTPException(status_code=400, detail="Expected a JSON object")

    try:
        handle_event(payload)
    except Exception as err:  # noqa: BLE001
        print(f"Error handling parcelLab webhook: {err}")
        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)

From hookdeck/webhook-skills ↗

Or install the parcelLab webhooks skill:

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

Common failures

Webhook set up with another mechanism

With access token headers or an OAuth 2.0 access token, no Basic credentials arrive. Ask parcelLab which mechanism it configured.

Credentials missing from the first request

parcelLab doesn't say whether it sends Basic credentials up front or only after a 401 challenge. Log the headers of a first delivery, and ask parcelLab to confirm.

Credentials changed on one side

The docs describe no way to change them yourself, so agree new values with parcelLab and update your stored values at the same time.

Password split on the wrong colon

Decode the base64 and split on the first colon only, because a password can contain one.

From Hookdeck's parcelLab guide

Let Event Gateway check parcelLab's Basic credentials.

Event Gateway checks the Basic username and password on each parcelLab request before it reaches your service, then queues it and retries failures on your schedule.

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