Webhooks et événements Groq

VérifiéSûr

Gérez de manière sécurisée les webhooks Groq avec validation de signature et protection contre la rejeu. Idéal pour configurer des endpoints webhook et la gestion d'événements.

Spar Skills Guide Bot
DeveloppementIntermédiaire
26/07/2026
Claude CodeCursorWindsurfCopilotCodex
#webhooks#signature-verification#event-handling#idempotency#groq

Recommandé pour

Synthèse automatique

Cette compétence décrit la mise en place d'un point de terminaison de webhook Groq avec vérification de signature HMAC, protection contre le rejeu, distribution des événements par type et idempotence via Redis.

Points forts

  • Fournit un exemple Express complet qui utilise express.raw pour conserver le corps brut indispensable à la vérification de signature.
  • Applique une comparaison à temps constant (crypto.timingSafeEqual) et rejette les horodatages de plus de cinq minutes.
  • Propose un patron de routage des événements par type avec propagation des erreurs afin de déclencher les relivraisons.
  • Donne des commandes concrètes de test via le CLI Groq ou webhook.site.

Limites

  • Les noms d'en-têtes (x-groq-signature, x-groq-timestamp), le format de signature et les types d'événements sont des exemples génériques à confirmer dans la documentation officielle Groq.
  • La fonction isEventProcessed est définie mais jamais appelée dans le gestionnaire d'exemple, l'idempotence reste donc à câbler soi-même.
  • Le code suppose Node/Express et Redis (ioredis) alors que l'idempotence est présentée comme facultative.
Quand l'utiliser

À utiliser lorsqu'il faut exposer un point de terminaison sécurisé qui reçoit et traite les notifications d'événements Groq.

Quand l'éviter

À éviter si vous cherchez seulement à appeler l'API Groq en sortie ou à intégrer le SDK de complétion, sans réception de webhooks.

Analyse de sécurité

Sûr
Score qualité85/100

The skill provides educational code and instructions for setting up secure webhook endpoints with signature validation, replay protection, and idempotency. It uses curl for legitimate testing and does not instruct destructive, exfiltrating, or obfuscated actions.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Express webhook endpoint
Add a /webhooks/groq Express endpoint that verifies the Groq signature with HMAC-SHA256 using express.raw, rejects timestamps older than 5 minutes, and dispatches each event to a typed handler.
Replay protection
Show me how to protect my Groq webhook handler against replay attacks using the x-groq-timestamp header and a timing-safe signature comparison.
Idempotent event handling
Make my Groq webhook handler idempotent with Redis so duplicate resource.created events are processed only once, using a 7-day TTL.

name: groq-webhooks-events description: | Implement Groq webhook signature validation and event handling. Use when setting up webhook endpoints, implementing signature verification, or handling Groq event notifications securely. Trigger with phrases like "groq webhook", "groq events", "groq webhook signature", "handle groq events", "groq notifications". allowed-tools: Read, Write, Edit, Bash(curl:*) version: 1.0.0 license: MIT author: Jeremy Longshore jeremy@intentsolutions.io

Groq Webhooks & Events

Overview

Securely handle Groq webhooks with signature validation and replay protection.

Prerequisites

  • Groq webhook secret configured
  • HTTPS endpoint accessible from internet
  • Understanding of cryptographic signatures
  • Redis or database for idempotency (optional)

Webhook Endpoint Setup

Express.js

import express from 'express';
import crypto from 'crypto';

const app = express();

// IMPORTANT: Raw body needed for signature verification
app.post('/webhooks/groq',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const signature = req.headers['x-groq-signature'] as string;
    const timestamp = req.headers['x-groq-timestamp'] as string;

    if (!verifyGroqSignature(req.body, signature, timestamp)) {
      return res.status(401).json({ error: 'Invalid signature' });
    }

    const event = JSON.parse(req.body.toString());
    await handleGroqEvent(event);

    res.status(200).json({ received: true });
  }
);

Signature Verification

function verifyGroqSignature(
  payload: Buffer,
  signature: string,
  timestamp: string
): boolean {
  const secret = process.env.GROQ_WEBHOOK_SECRET!;

  // Reject old timestamps (replay attack protection)
  const timestampAge = Date.now() - parseInt(timestamp) * 1000;
  if (timestampAge > 300000) { // 5 minutes
    console.error('Webhook timestamp too old');
    return false;
  }

  // Compute expected signature
  const signedPayload = `${timestamp}.${payload.toString()}`;
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(signedPayload)
    .digest('hex');

  // Timing-safe comparison
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  );
}

Event Handler Pattern

type GroqEventType = 'resource.created' | 'resource.updated' | 'resource.deleted';

interface GroqEvent {
  id: string;
  type: GroqEventType;
  data: Record<string, any>;
  created: string;
}

const eventHandlers: Record<GroqEventType, (data: any) => Promise<void>> = {
  'resource.created': async (data) => { /* handle */ },
  'resource.updated': async (data) => { /* handle */ },
  'resource.deleted': async (data) => { /* handle */ }
};

async function handleGroqEvent(event: GroqEvent): Promise<void> {
  const handler = eventHandlers[event.type];

  if (!handler) {
    console.log(`Unhandled event type: ${event.type}`);
    return;
  }

  try {
    await handler(event.data);
    console.log(`Processed ${event.type}: ${event.id}`);
  } catch (error) {
    console.error(`Failed to process ${event.type}: ${event.id}`, error);
    throw error; // Rethrow to trigger retry
  }
}

Idempotency Handling

import { Redis } from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

async function isEventProcessed(eventId: string): Promise<boolean> {
  const key = `groq:event:${eventId}`;
  const exists = await redis.exists(key);
  return exists === 1;
}

async function markEventProcessed(eventId: string): Promise<void> {
  const key = `groq:event:${eventId}`;
  await redis.set(key, '1', 'EX', 86400 * 7); // 7 days TTL
}

Webhook Testing

# Use Groq CLI to send test events
groq webhooks trigger resource.created --url http://localhost:3000/webhooks/groq

# Or use webhook.site for debugging
curl -X POST https://webhook.site/your-uuid \
  -H "Content-Type: application/json" \
  -d '{"type": "resource.created", "data": {}}'

Instructions

Step 1: Register Webhook Endpoint

Configure your webhook URL in the Groq dashboard.

Step 2: Implement Signature Verification

Use the signature verification code to validate incoming webhooks.

Step 3: Handle Events

Implement handlers for each event type your application needs.

Step 4: Add Idempotency

Prevent duplicate processing with event ID tracking.

Output

  • Secure webhook endpoint
  • Signature validation enabled
  • Event handlers implemented
  • Replay attack protection active

Error Handling

| Issue | Cause | Solution | |-------|-------|----------| | Invalid signature | Wrong secret | Verify webhook secret | | Timestamp rejected | Clock drift | Check server time sync | | Duplicate events | Missing idempotency | Implement event ID tracking | | Handler timeout | Slow processing | Use async queue |

Examples

Testing Webhooks Locally

# Use ngrok to expose local server
ngrok http 3000

# Send test webhook
curl -X POST https://your-ngrok-url/webhooks/groq \
  -H "Content-Type: application/json" \
  -d '{"type": "test", "data": {}}'

Resources

Next Steps

For performance optimization, see groq-performance-tuning.

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/groq-webhooks-events-ms1aw5hf/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/groq-webhooks-events-ms1aw5hf' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/groq-webhooks-events-ms1aw5hf/download' --output '.skill-downloads/groq-webhooks-events-ms1aw5hf/SKILL.md.part' && mv '.skill-downloads/groq-webhooks-events-ms1aw5hf/SKILL.md.part' '.skill-downloads/groq-webhooks-events-ms1aw5hf/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Outils déclarés par l’auteur (à vérifier dans votre agent) : Read, Write, Edit, Bash(curl:*)

Extrait original : Prerequisites
  • Groq webhook secret configured
  • HTTPS endpoint accessible from internet
  • Understanding of cryptographic signatures
  • Redis or database for idempotency (optional)

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/groq-webhooks-events-ms1aw5hf/SKILL.md' && test -s '.skill-downloads/groq-webhooks-events-ms1aw5hf/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/groq-webhooks-events' && cp -R '.skill-downloads/groq-webhooks-events-ms1aw5hf' '.claude/skills/groq-webhooks-events'

Cursor
test -f '.skill-downloads/groq-webhooks-events-ms1aw5hf/SKILL.md' && test -s '.skill-downloads/groq-webhooks-events-ms1aw5hf/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/groq-webhooks-events' && cp -R '.skill-downloads/groq-webhooks-events-ms1aw5hf' '.cursor/skills/groq-webhooks-events'

Codex
test -f '.skill-downloads/groq-webhooks-events-ms1aw5hf/SKILL.md' && test -s '.skill-downloads/groq-webhooks-events-ms1aw5hf/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/groq-webhooks-events' && cp -R '.skill-downloads/groq-webhooks-events-ms1aw5hf' '.agents/skills/groq-webhooks-events'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/groq-webhooks-events-ms1aw5hf'

openskills read 'groq-webhooks-events-ms1aw5hf'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/groq-webhooks-events-ms1aw5hf/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires