webhook-security
БесплатноБез исполняемых скриптовНе проверенVerifies webhook signatures, blocks replayed requests and deduplicates retries on a webhook receiver. Use when a user asks to verify webhook signatures…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Webhook Security
Overview
Webhooks deliver real-time data to your app, but an open endpoint is an attack surface. Without verification, anyone can POST fake events to your webhook URL. This skill covers signature verification, replay protection, idempotency, and reliable processing patterns.
Instructions
Step 1: Signature Verification
Every major provider signs webhook payloads with HMAC. Verify before processing.
// lib/webhooks/verify.ts — Generic HMAC verification
import crypto from 'crypto'
export function safeEqual(a: string, b: string): boolean {
const x = Buffer.from(a)
const y = Buffer.from(b)
// timingSafeEqual THROWS (ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH) when lengths differ
return x.length === y.length && crypto.timingSafeEqual(x, y)
}
export function verifyHmacSignature(
payload: string | Buffer,
signature: string,
secret: string,
algorithm: string = 'sha256'
): boolean {
const expected = crypto
.createHmac(algorithm, secret)
.update(payload)
.digest('hex')
return safeEqual(signature, expected)
}
Providers differ in header name, prefix (sha256=), encoding (hex or base64) and what is signed (body only, or timestamp + body). Read the provider's docs for each, and keep the secret in an environment variable.
Step 2: Stripe Webhook Verification
// routes/webhooks/stripe.ts — Stripe webhook handler
import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!) // current stripe-node: 23.x
export async function handleStripeWebhook(req: Request) {
const body = await req.text() // raw body, NOT parsed JSON
const sig = req.headers.get('stripe-signature')!
let event: Stripe.Event
try {
event = stripe.webhooks.constructEvent(
body,
sig,
process.env.STRIPE_WEBHOOK_SECRET!
)
} catch (err) {
console.error('Webhook signature verification failed:', (err as Error).message)
return new Response('Invalid signature', { status: 400 })
}
// Process event idempotently (see Step 3)
switch (event.type) {
case 'checkout.session.completed':
await handleCheckoutComplete(event.data.object)
break
case 'invoice.payment_failed':
await handlePaymentFailed(event.data.object)
break
case 'customer.subscription.deleted':
await handleSubscriptionCanceled(event.data.object)
break
}
return new Response('OK', { status: 200 })
}
constructEvent checks the t= timestamp in the header against a 5-minute tolerance by default. Never pass a tolerance of 0: that disables the recency check. On runtimes without Node's crypto sync API (Cloudflare Workers, Deno, browsers) use await stripe.webhooks.constructEventAsync(body, sig, secret). Each Stripe endpoint has its own whsec_ secret; the Stripe CLI prints a different one for stripe listen.
Step 3: Replay Protection and Idempotency
// lib/webhooks/idempotency.ts — Prevent duplicate processing
import { redis } from '../redis'
export async function processOnce(
eventId: string,
handler: () => Promise<void>
): Promise<boolean> {
// Set with NX (only if not exists) and a 3-day expiry (Stripe retries for up to 3 days)
const isNew = await redis.set(`webhook:${eventId}`, '1', 'NX', 'EX', 259200)
if (!isNew) {
console.log(`Duplicate webhook ${eventId}, skipping`)
return false
}
try {
await handler()
return true
} catch (err) {
// Remove key so retry can work
await redis.del(`webhook:${eventId}`)
throw err
}
}
// Usage: Stripe retries for up to three days, so the key must outlive a retry
// window you care about. Better still, make the handler itself idempotent.
await processOnce(event.id, async () => {
await db.order.update({ where: { stripeSessionId: session.id }, data: { status: 'paid' } })
})
Step 4: GitHub Webhook Verification
// routes/webhooks/github.ts — GitHub webhook handler
import crypto from 'crypto'
import { safeEqual } from '../../lib/webhooks/verify'
function verifyGitHubSignature(payload: string, signature: string, secret: string): boolean {
const expected = 'sha256=' + crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex')
return safeEqual(signature, expected) // from lib/webhooks/verify.ts
}
export async function handleGitHubWebhook(req: Request) {
const body = await req.text()
const sig = req.headers.get('x-hub-signature-256') ?? ''
const deliveryId = req.headers.get('x-github-delivery') // unique per delivery; use as the dedup key
if (!verifyGitHubSignature(body, sig, process.env.GITHUB_WEBHOOK_SECRET!)) {
return new Response('Invalid signature', { status: 401 })
}
const event = req.headers.get('x-github-event')
const payload = JSON.parse(body)
switch (event) {
case 'push':
await handlePush(payload)
break
case 'pull_request':
await handlePR(payload)
break
Установить webhook-security в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл webhook-security?
Verifies webhook signatures, blocks replayed requests and deduplicates retries on a webhook receiver. Use when a user asks to verify webhook signatures, prevent replay attacks, handle webhook retries, or build a secure webhook endpoint for Stripe, GitHub, Slack, or any HMAC-signing provider.
Как установить скилл webhook-security?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл webhook-security запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic