Verify Smartsheet webhooks

Smartsheet signs each callback so you can confirm it came from Smartsheet and wasn't changed on the way. The Smartsheet-Hmac-SHA256 header holds a base-16 HMAC-SHA256 of the raw request body, keyed with the webhook's sharedSecret. Smartsheet calls this check optional and publishes no test vector. Its verification challenge is a separate step, which your endpoint answers before any callback arrives.

The facts

Signature header
Smartsheet-Hmac-SHA256

Format: <hex>

Scheme
HMAC-SHA256
Signed material
{raw body}

The request body exactly as sent, with no prefix or delimiter. The body's own timestamp and nonce fields are covered, but nothing outside the body is signed.

URL handshake
POST: echo the challenge

HTTP 200 with the challenge value echoed EITHER in a Smartsheet-Hook-Response response header OR as a JSON body attribute smartsheetHookResponse.

What to build
Recompute a digest over the raw body and compare
Key
shared secret

Smartsheet webhook secret

Smartsheet generates a random sharedSecret per webhook and returns it on the Webhook object (create, get); it can be rotated with the reset-shared-secret operation. It isn't your API access token. Keep it in an environment variable, not in source code.

  • From the API: POST /2.0/webhooks returns it as result.sharedSecret when you create the webhook.
  • One per webhook: each webhook gets its own random value, so a handler serving several webhooks needs the secret for the matching webhookId.
  • Rotating: POST /2.0/webhooks/{webhookId}/resetSharedSecret issues a new one. Smartsheet says you can do this at periodic intervals to improve security.

Source: Smartsheet docs ↗

Code

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

const app = express();

// Smartsheet-Hmac-SHA256 = hex HMAC-SHA256 of the raw body, keyed with the
// webhook's sharedSecret. Compare case-insensitively.
function verifySmartsheetSignature(rawBody, signatureHeader, secret) {
  if (!signatureHeader || !secret) return false;
  const expected = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
  const received = Buffer.from(signatureHeader.trim().toLowerCase());
  const expectedBuf = Buffer.from(expected);
  return received.length === expectedBuf.length && crypto.timingSafeEqual(received, expectedBuf);
}

function handleEvent(event) {
  switch (`${event.objectType}.${event.eventType}`) {
    case 'row.created':
      console.log('Row created:', event.id);
      // Your code: Fetch the row via the API (callbacks are "skinny") and process it
      break;
    case 'row.updated':
      console.log('Row updated:', event.id);
      break;
    case 'row.deleted':
      console.log('Row deleted:', event.id);
      break;
    case 'cell.updated':
      console.log('Cell updated: row', event.rowId, 'column', event.columnId);
      break;
    case 'sheet.updated':
      console.log('Sheet updated:', event.id);
      break;
    default:
      console.log(`Unhandled event: ${event.objectType}.${event.eventType}`);
  }
}

// express.raw({ type: '*/*' }) keeps the raw bytes whatever the Content-Type is
app.post('/webhooks/smartsheet', express.raw({ type: '*/*' }), (req, res) => {
  // 1. Verification handshake FIRST: Smartsheet sends it on enable and again
  //    about every 100 callbacks. Challenge requests may be unsigned, so echo
  //    the value before any signature check.
  const challenge = req.get('Smartsheet-Hook-Challenge');
  if (challenge) {
    res.set('Smartsheet-Hook-Response', challenge);
    return res.status(200).json({ smartsheetHookResponse: challenge });
  }

  // 2. Verify the signature over the raw body
  const signature = req.get('Smartsheet-Hmac-SHA256');
  if (!signature) {
    return res.status(400).send('Missing Smartsheet-Hmac-SHA256 header');
  }
  const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
  if (!verifySmartsheetSignature(rawBody, signature, process.env.SMARTSHEET_SHARED_SECRET)) {
    console.error('Smartsheet webhook signature verification failed');
    return res.status(400).send('Invalid signature');
  }

  // 3. Parse and dispatch
  let payload;
  try {
    payload = JSON.parse(rawBody.toString('utf8'));
  } catch {
    return res.status(400).send('Invalid JSON');
  }

  if (payload.newWebhookStatus) {
    // Status change callback (webhook automatically disabled or re-enabled)
    console.log('Webhook status changed:', payload.newWebhookStatus);
  }
  for (const event of payload.events || []) {
    handleEvent(event);
  }

  // Any 200 acknowledges the callback
  res.json({ received: true });
});

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

// Export app for testing
module.exports = app;

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

interface SmartsheetEvent {
  objectType: string;
  eventType: string;
  id?: number;
  rowId?: number;
  columnId?: number;
  userId?: number;
}

// Smartsheet-Hmac-SHA256 = hex HMAC-SHA256 of the raw body, keyed with the
// webhook's sharedSecret. Compare case-insensitively.
function verifySmartsheetSignature(
  rawBody: string,
  signatureHeader: string | null,
  secret: string | undefined
): boolean {
  if (!signatureHeader || !secret) return false;
  const expected = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
  const received = Buffer.from(signatureHeader.trim().toLowerCase());
  const expectedBuf = Buffer.from(expected);
  return received.length === expectedBuf.length && crypto.timingSafeEqual(received, expectedBuf);
}

function handleEvent(event: SmartsheetEvent) {
  switch (`${event.objectType}.${event.eventType}`) {
    case 'row.created':
      console.log('Row created:', event.id);
      // Your code: Fetch the row via the API (callbacks are "skinny") and process it
      break;
    case 'row.updated':
      console.log('Row updated:', event.id);
      break;
    case 'row.deleted':
      console.log('Row deleted:', event.id);
      break;
    case 'cell.updated':
      console.log('Cell updated: row', event.rowId, 'column', event.columnId);
      break;
    case 'sheet.updated':
      console.log('Sheet updated:', event.id);
      break;
    default:
      console.log(`Unhandled event: ${event.objectType}.${event.eventType}`);
  }
}

export async function POST(request: NextRequest) {
  // 1. Verification handshake FIRST: Smartsheet sends it on enable and again
  //    about every 100 callbacks. Challenge requests may be unsigned, so echo
  //    the value before any signature check.
  const challenge = request.headers.get('Smartsheet-Hook-Challenge');
  if (challenge) {
    return NextResponse.json(
      { smartsheetHookResponse: challenge },
      { status: 200, headers: { 'Smartsheet-Hook-Response': challenge } }
    );
  }

  // 2. Verify the signature over the raw body (text() before any JSON parsing)
  const signature = request.headers.get('Smartsheet-Hmac-SHA256');
  if (!signature) {
    return new NextResponse('Missing Smartsheet-Hmac-SHA256 header', { status: 400 });
  }
  const rawBody = await request.text();
  if (!verifySmartsheetSignature(rawBody, signature, process.env.SMARTSHEET_SHARED_SECRET)) {
    console.error('Smartsheet webhook signature verification failed');
    return new NextResponse('Invalid signature', { status: 400 });
  }

  // 3. Parse and dispatch
  let payload: { events?: SmartsheetEvent[]; newWebhookStatus?: string };
  try {
    payload = JSON.parse(rawBody);
  } catch {
    return new NextResponse('Invalid JSON', { status: 400 });
  }

  if (payload.newWebhookStatus) {
    // Status change callback (webhook automatically disabled or re-enabled)
    console.log('Webhook status changed:', payload.newWebhookStatus);
  }
  for (const event of payload.events ?? []) {
    handleEvent(event);
  }

  // Any 200 acknowledges the callback
  return NextResponse.json({ received: true });
}
fastapi/main.py
python
# Generated with: smartsheet-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import os

from dotenv import load_dotenv
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, PlainTextResponse

load_dotenv()

app = FastAPI()


def verify_smartsheet_signature(raw_body: bytes, signature_header: str | None, secret: str | None) -> bool:
    """Smartsheet-Hmac-SHA256 = hex HMAC-SHA256 of the raw body, keyed with the
    webhook's sharedSecret. Compare case-insensitively."""
    if not signature_header or not secret:
        return False
    expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature_header.strip().lower().encode(), expected.encode())


def handle_event(event: dict) -> None:
    kind = f"{event.get('objectType')}.{event.get('eventType')}"
    if kind == "row.created":
        print("Row created:", event.get("id"))
        # Your code: Fetch the row via the API (callbacks are "skinny") and process it
    elif kind == "row.updated":
        print("Row updated:", event.get("id"))
    elif kind == "row.deleted":
        print("Row deleted:", event.get("id"))
    elif kind == "cell.updated":
        print("Cell updated: row", event.get("rowId"), "column", event.get("columnId"))
    elif kind == "sheet.updated":
        print("Sheet updated:", event.get("id"))
    else:
        print(f"Unhandled event: {kind}")


@app.post("/webhooks/smartsheet")
async def smartsheet_webhook(request: Request):
    # 1. Verification handshake FIRST: Smartsheet sends it on enable and again
    #    about every 100 callbacks. Challenge requests may be unsigned, so echo
    #    the value before any signature check.
    challenge = request.headers.get("smartsheet-hook-challenge")
    if challenge:
        return JSONResponse(
            {"smartsheetHookResponse": challenge},
            status_code=200,
            headers={"Smartsheet-Hook-Response": challenge},
        )

    # 2. Verify the signature over the raw body (read bytes, don't use request.json())
    signature = request.headers.get("smartsheet-hmac-sha256")
    if not signature:
        return PlainTextResponse("Missing Smartsheet-Hmac-SHA256 header", status_code=400)
    raw_body = await request.body()
    if not verify_smartsheet_signature(raw_body, signature, os.getenv("SMARTSHEET_SHARED_SECRET")):
        return PlainTextResponse("Invalid signature", status_code=400)

    # 3. Parse and dispatch
    try:
        payload = json.loads(raw_body)
    except json.JSONDecodeError:
        return PlainTextResponse("Invalid JSON", status_code=400)

    if payload.get("newWebhookStatus"):
        # Status change callback (webhook automatically disabled or re-enabled)
        print("Webhook status changed:", payload["newWebhookStatus"])
    for event in payload.get("events", []):
        handle_event(event)

    # Any 200 acknowledges the callback
    return {"received": True}


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

From hookdeck/webhook-skills ↗

Or install the Smartsheet webhooks skill:

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

Common failures

The body was parsed first

The HMAC covers the request body as sent. Hash the raw bytes, because parsing and re-serializing the JSON can change them.

The secret belongs to another webhook

Each webhook has its own sharedSecret, and each watches one sheet or plan. A handler serving several webhooks needs the secret for the callback's webhookId.

The secret was reset

Resetting issues a new sharedSecret. Update your receiver at the same time, or valid callbacks stop matching.

The hex case differs

Smartsheet says base 16 but doesn't state the case and publishes no example, so lowercase the header before you compare.

From Hookdeck's Smartsheet guide

Let Event Gateway verify Smartsheet signatures.

Event Gateway verifies the signature on each Smartsheet delivery before it reaches your service, then queues it and retries failures on your schedule.

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