Sage Infrastructure Solutions Group IncSage Infrastructure Solutions Group IncLoading…

Sage Infrastructure Solutions Group Inc

Webhook examples

Webhook examples

Three small, working receivers for FathomWatch webhooks: Python, Go and Node.js, each using only its standard library. Each one:

  • verifies X-FathomWatch-Signature against the raw body, in constant time, and answers 401 if it doesn't match;
  • answers 204 straight away, then handles the event;
  • ignores repeated deliveries of the same message;
  • prints a line for each event — replace handle with your own automation (open a ticket, page someone, call your SIEM).

Run one behind HTTPS (a reverse proxy or your platform's load balancer) at a URL FathomWatch can reach, then point a webhook at it and select Send test.

[!NOTE] The duplicate check keeps fingerprints in memory, so it forgets them on restart. In production, store them in your database or Redis with an expiry of a day or so.

Python

Python 3.9 or newer. Set CHAT_WEBHOOK_URL to a Slack or Microsoft Teams incoming-webhook URL to post every new exposure to a channel as well.

FATHOMWATCH_WEBHOOK_SECRET='<signing secret>' PORT=8080 python3 receiver.py
#!/usr/bin/env python3
"""FathomWatch webhook receiver — Python 3.9+, standard library only.

    FATHOMWATCH_WEBHOOK_SECRET='<signing secret>' python3 receiver.py

Optional: CHAT_WEBHOOK_URL=<Slack or Microsoft Teams incoming-webhook URL>
posts every new exposure to that channel.
"""
import hashlib
import hmac
import json
import os
import threading
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

SECRET = os.environ["FATHOMWATCH_WEBHOOK_SECRET"].encode()  # used as-is, not decoded
CHAT_WEBHOOK_URL = os.environ.get("CHAT_WEBHOOK_URL", "")
PORT = int(os.environ.get("PORT", "8080"))
MAX_BODY = 5 * 1024 * 1024

_seen = set()  # delivery fingerprints; use a database or Redis in production
_seen_lock = threading.Lock()


def valid_signature(body: bytes, header: str) -> bool:
    """X-FathomWatch-Signature is "sha256=" + hex HMAC-SHA256(secret, raw body)."""
    if not header.startswith("sha256="):
        return False
    expected = hmac.new(SECRET, body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header[len("sha256="):])


def first_delivery(body: bytes) -> bool:
    """Retries resend the identical body, so its hash identifies a delivery."""
    fingerprint = hashlib.sha256(body).hexdigest()
    with _seen_lock:
        if fingerprint in _seen:
            return False
        _seen.add(fingerprint)
        return True


def post_to_chat(text: str) -> None:
    if not CHAT_WEBHOOK_URL:
        return
    req = urllib.request.Request(
        CHAT_WEBHOOK_URL,
        data=json.dumps({"text": text}).encode(),
        headers={"Content-Type": "application/json"},
    )
    try:
        urllib.request.urlopen(req, timeout=10).close()
    except OSError as err:
        print("chat post failed:", err)


def handle(event: dict) -> None:
    kind = event["event"]
    leak = event.get("leak", {})
    if kind == "new_leak":
        lines = [f"New {leak['leak_type']} exposure ({leak['credential_count']} credential(s)): {leak['url']}"]
        for cred in event.get("credentials", []):
            lines.append(f"- {cred['account']} on {cred['url']} (password starts {cred['password_masked']})")
        print("\n".join(lines))
        post_to_chat("\n".join(lines))
    elif kind == "status_changed":
        print(f"{leak['id']}: {event['from_status']} -> {event['to_status']} by {event['actor']}")
    elif kind == "recurrence_seen":
        print(f"{leak['id']}: {leak['recurrences']} already-reported credential(s) seen again")
    elif kind == "test":
        print("Test delivery received:", event.get("message"))


class Receiver(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get("Content-Length") or 0)
        if length <= 0 or length > MAX_BODY:
            return self.reply(400)
        body = self.rfile.read(length)
        if not valid_signature(body, self.headers.get("X-FathomWatch-Signature", "")):
            return self.reply(401)
        self.reply(204)  # answer quickly; FathomWatch waits at most 10 seconds
        if first_delivery(body):
            handle(json.loads(body))

    def reply(self, code: int) -> None:
        self.send_response(code)
        self.send_header("Content-Length", "0")
        self.end_headers()

    def log_message(self, *args) -> None:
        pass


if __name__ == "__main__":
    print(f"Listening on :{PORT}")
    ThreadingHTTPServer(("", PORT), Receiver).serve_forever()

Go

Go 1.21 or newer.

FATHOMWATCH_WEBHOOK_SECRET='<signing secret>' PORT=8080 go run .
// FathomWatch webhook receiver — Go, standard library only.
//
//	FATHOMWATCH_WEBHOOK_SECRET='<signing secret>' go run .
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
	"sync"
)

// Event is the JSON FathomWatch posts. Fields present depend on Event.
type Event struct {
	Event      string `json:"event"` // new_leak | status_changed | recurrence_seen | test
	OccurredAt string `json:"occurred_at"`
	OrgID      string `json:"org_id"`
	Leak       struct {
		ID              string `json:"id"`
		LeakType        string `json:"leak_type"`
		Status          string `json:"status"`
		Source          string `json:"source"`
		ItemID          string `json:"item_id"`
		ReceivedAt      string `json:"received_at"`
		CredentialCount int    `json:"credential_count"`
		Recurrences     int    `json:"recurrences"`
		URL             string `json:"url"`
		Part            int    `json:"part"`
		Parts           int    `json:"parts"`
	} `json:"leak"`
	Credentials []struct {
		Account        string `json:"account"`
		URL            string `json:"url"`
		PasswordMasked string `json:"password_masked"`
		SHA1           string `json:"sha1"`
		TimesSeen      int    `json:"times_seen"`
	} `json:"credentials"`
	FromStatus string `json:"from_status"`
	ToStatus   string `json:"to_status"`
	Note       string `json:"note"`
	Actor      string `json:"actor"`
	Message    string `json:"message"`
}

var (
	secret = []byte(os.Getenv("FATHOMWATCH_WEBHOOK_SECRET")) // used as-is, not decoded
	seenMu sync.Mutex
	seen   = map[string]bool{} // delivery fingerprints; use a database in production
)

// validSignature checks X-FathomWatch-Signature: "sha256=" + hex HMAC-SHA256(secret, body).
func validSignature(body []byte, header string) bool {
	got, ok := strings.CutPrefix(header, "sha256=")
	if !ok {
		return false
	}
	want, err := hex.DecodeString(got)
	if err != nil {
		return false
	}
	mac := hmac.New(sha256.New, secret)
	mac.Write(body)
	return hmac.Equal(want, mac.Sum(nil))
}

// firstDelivery: retries resend the identical body, so its hash identifies a delivery.
func firstDelivery(body []byte) bool {
	sum := sha256.Sum256(body)
	key := hex.EncodeToString(sum[:])
	seenMu.Lock()
	defer seenMu.Unlock()
	if seen[key] {
		return false
	}
	seen[key] = true
	return true
}

func handle(ev Event) {
	switch ev.Event {
	case "new_leak":
		log.Printf("New %s exposure (%d credential(s)): %s", ev.Leak.LeakType, ev.Leak.CredentialCount, ev.Leak.URL)
		for _, c := range ev.Credentials {
			log.Printf("- %s on %s (password starts %s)", c.Account, c.URL, c.PasswordMasked)
		}
	case "status_changed":
		log.Printf("%s: %s -> %s by %s", ev.Leak.ID, ev.FromStatus, ev.ToStatus, ev.Actor)
	case "recurrence_seen":
		log.Printf("%s: %d already-reported credential(s) seen again", ev.Leak.ID, ev.Leak.Recurrences)
	case "test":
		log.Printf("Test delivery received: %s", ev.Message)
	}
}

func webhook(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 5<<20))
	if err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}
	if !validSignature(body, r.Header.Get("X-FathomWatch-Signature")) {
		http.Error(w, "invalid signature", http.StatusUnauthorized)
		return
	}
	var ev Event
	if err := json.Unmarshal(body, &ev); err != nil {
		http.Error(w, "bad json", http.StatusBadRequest)
		return
	}
	w.WriteHeader(http.StatusNoContent) // answer quickly; FathomWatch waits at most 10 seconds
	if firstDelivery(body) {
		go handle(ev)
	}
}

func main() {
	if len(secret) == 0 {
		log.Fatal("set FATHOMWATCH_WEBHOOK_SECRET")
	}
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	http.HandleFunc("/", webhook)
	log.Printf("Listening on :%s", port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}

Node.js

Node.js 18 or newer.

FATHOMWATCH_WEBHOOK_SECRET='<signing secret>' PORT=8080 node receiver.mjs
// FathomWatch webhook receiver — Node.js 18+, standard library only.
//
//   FATHOMWATCH_WEBHOOK_SECRET='<signing secret>' node receiver.mjs
import { createHash, createHmac, timingSafeEqual } from 'node:crypto'
import { createServer } from 'node:http'

const SECRET = process.env.FATHOMWATCH_WEBHOOK_SECRET // used as-is, not decoded
if (!SECRET) throw new Error('set FATHOMWATCH_WEBHOOK_SECRET')
const PORT = Number(process.env.PORT || 8080)
const MAX_BODY = 5 * 1024 * 1024
const seen = new Set() // delivery fingerprints; use a database or Redis in production

// X-FathomWatch-Signature is "sha256=" + hex HMAC-SHA256(secret, raw body).
function validSignature(body, header = '') {
  if (!header.startsWith('sha256=')) return false
  const expected = createHmac('sha256', SECRET).update(body).digest()
  const got = Buffer.from(header.slice('sha256='.length), 'hex')
  return got.length === expected.length && timingSafeEqual(got, expected)
}

function handle(event) {
  const leak = event.leak ?? {}
  switch (event.event) {
    case 'new_leak':
      console.log(`New ${leak.leak_type} exposure (${leak.credential_count} credential(s)): ${leak.url}`)
      for (const c of event.credentials ?? []) console.log(`- ${c.account} on ${c.url} (password starts ${c.password_masked})`)
      break
    case 'status_changed':
      console.log(`${leak.id}: ${event.from_status} -> ${event.to_status} by ${event.actor}`)
      break
    case 'recurrence_seen':
      console.log(`${leak.id}: ${leak.recurrences} already-reported credential(s) seen again`)
      break
    case 'test':
      console.log('Test delivery received:', event.message)
      break
  }
}

createServer((req, res) => {
  if (req.method !== 'POST') return res.writeHead(405).end()
  const chunks = []
  let size = 0
  req.on('data', (c) => {
    size += c.length
    if (size > MAX_BODY) req.destroy()
    else chunks.push(c)
  })
  req.on('end', () => {
    const body = Buffer.concat(chunks)
    if (!validSignature(body, req.headers['x-fathomwatch-signature'])) return res.writeHead(401).end()
    let event
    try {
      event = JSON.parse(body)
    } catch {
      return res.writeHead(400).end()
    }
    res.writeHead(204).end() // answer quickly; FathomWatch waits at most 10 seconds
    // Retries resend the identical body, so its hash identifies a delivery.
    const fingerprint = createHash('sha256').update(body).digest('hex')
    if (seen.has(fingerprint)) return
    seen.add(fingerprint)
    handle(event)
  })
}).listen(PORT, () => console.log(`Listening on :${PORT}`))

Test without FathomWatch

Sign a sample message yourself and send it to your receiver:

SECRET='<signing secret>'
BODY='{"event":"test","occurred_at":"2026-10-03T14:00:00Z","org_id":"organizations:abc123","message":"Hello"}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.* //')
curl -si -X POST http://localhost:8080/ \
  -H 'Content-Type: application/json' \
  -H 'X-FathomWatch-Event: test' \
  -H "X-FathomWatch-Signature: sha256=$SIG" \
  --data "$BODY"

Expect HTTP/1.1 204. Change one character of the body or the secret and you should get 401.