Verificacion

Verificar la firma HMAC de los webhooks.

Cada webhook incluye un header X-SouthGames-Signature con una firma HMAC-SHA256 del body usando tu secret.

Header

X-SouthGames-Signature: sha256=<hex_digest>

Verificacion en Node.js

import crypto from 'crypto';

function verifyWebhook(body, signature, secret) {
  const expected = 'sha256=' + crypto
    .createHmac('sha256', secret)
    .update(body)
    .digest('hex');

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}

// En tu handler
app.post('/webhooks/southgames', (req, res) => {
  const signature = req.headers['x-southgames-signature'];
  const isValid = verifyWebhook(
    JSON.stringify(req.body),
    signature,
    process.env.WEBHOOK_SECRET
  );

  if (!isValid) {
    return res.status(401).send('Invalid signature');
  }

  const { event, data } = req.body;
  // Procesar el evento...

  res.status(200).send('OK');
});

Verificacion en Python

import hmac
import hashlib

def verify_webhook(body: bytes, signature: str, secret: str) -> bool:
    expected = 'sha256=' + hmac.new(
        secret.encode(),
        body,
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(signature, expected)

Buenas practicas

  • Siempre verifica la firma antes de procesar el evento
  • Usa timingSafeEqual (Node.js) o compare_digest (Python) para evitar timing attacks
  • Responde con 200 lo antes posible — procesa asincrono si necesitas
  • Guarda el secret de forma segura (variables de entorno)