Loading...
Loading...
Compare original and translation side by side
const crypto = require('crypto');
function verifyGitHubWebhook(rawBody, signatureHeader, secret) {
if (!signatureHeader || !secret) return false;
// GitHub sends: sha256=xxxx
const [algorithm, signature] = signatureHeader.split('=');
if (algorithm !== 'sha256') return false;
const expected = crypto
.createHmac('sha256', secret)
.update(rawBody)
.digest('hex');
try {
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
} catch {
return false;
}
}const crypto = require('crypto');
function verifyGitHubWebhook(rawBody, signatureHeader, secret) {
if (!signatureHeader || !secret) return false;
// GitHub sends: sha256=xxxx
const [algorithm, signature] = signatureHeader.split('=');
if (algorithm !== 'sha256') return false;
const expected = crypto
.createHmac('sha256', secret)
.update(rawBody)
.digest('hex');
try {
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
} catch {
return false;
}
}const express = require('express');
const app = express();
// CRITICAL: Use express.raw() - GitHub requires raw body for signature verification
app.post('/webhooks/github',
express.raw({ type: 'application/json' }),
(req, res) => {
const signature = req.headers['x-hub-signature-256']; // Use sha256, not sha1
const event = req.headers['x-github-event'];
const delivery = req.headers['x-github-delivery'];
// Verify signature
if (!verifyGitHubWebhook(req.body, signature, process.env.GITHUB_WEBHOOK_SECRET)) {
console.error('GitHub signature verification failed');
return res.status(401).send('Invalid signature');
}
// Parse payload after verification
const payload = JSON.parse(req.body.toString());
console.log(`Received ${event} (delivery: ${delivery})`);
// Handle by event type
switch (event) {
case 'push':
console.log(`Push to ${payload.ref}:`, payload.head_commit?.message);
break;
case 'pull_request':
console.log(`PR #${payload.number} ${payload.action}:`, payload.pull_request?.title);
break;
case 'issues':
console.log(`Issue #${payload.issue?.number} ${payload.action}:`, payload.issue?.title);
break;
case 'ping':
console.log('Ping:', payload.zen);
break;
default:
console.log('Received event:', event);
}
res.json({ received: true });
}
);const express = require('express');
const app = express();
// CRITICAL: Use express.raw() - GitHub requires raw body for signature verification
app.post('/webhooks/github',
express.raw({ type: 'application/json' }),
(req, res) => {
const signature = req.headers['x-hub-signature-256']; // Use sha256, not sha1
const event = req.headers['x-github-event'];
const delivery = req.headers['x-github-delivery'];
// Verify signature
if (!verifyGitHubWebhook(req.body, signature, process.env.GITHUB_WEBHOOK_SECRET)) {
console.error('GitHub signature verification failed');
return res.status(401).send('Invalid signature');
}
// Parse payload after verification
const payload = JSON.parse(req.body.toString());
console.log(`Received ${event} (delivery: ${delivery})`);
// Handle by event type
switch (event) {
case 'push':
console.log(`Push to ${payload.ref}:`, payload.head_commit?.message);
break;
case 'pull_request':
console.log(`PR #${payload.number} ${payload.action}:`, payload.pull_request?.title);
break;
case 'issues':
console.log(`Issue #${payload.issue?.number} ${payload.action}:`, payload.issue?.title);
break;
case 'ping':
console.log('Ping:', payload.zen);
break;
default:
console.log('Received event:', event);
}
res.json({ received: true });
}
);import hmac
import hashlib
def verify_github_webhook(raw_body: bytes, signature_header: str, secret: str) -> bool:
if not signature_header or not secret:
return False
# GitHub sends: sha256=xxxx
try:
algorithm, signature = signature_header.split('=')
if algorithm != 'sha256':
return False
except ValueError:
return False
expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(signature, expected)For complete working examples with tests, see:
- examples/express/ - Full Express implementation
- examples/nextjs/ - Next.js App Router implementation
- examples/fastapi/ - Python FastAPI implementation
import hmac
import hashlib
def verify_github_webhook(raw_body: bytes, signature_header: str, secret: str) -> bool:
if not signature_header or not secret:
return False
# GitHub sends: sha256=xxxx
try:
algorithm, signature = signature_header.split('=')
if algorithm != 'sha256':
return False
except ValueError:
return False
expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(signature, expected)如需带测试的完整可运行示例,请查看:
- examples/express/ - 完整Express实现
- examples/nextjs/ - Next.js App Router实现
- examples/fastapi/ - Python FastAPI实现
| Event | Description |
|---|---|
| Commits pushed to branch |
| PR opened, closed, merged, etc. |
| Issue opened, closed, labeled, etc. |
| Release published |
| GitHub Actions workflow completed |
| Test event when webhook created |
For full event reference, see GitHub Webhook Events
| 事件 | 描述 |
|---|---|
| 代码提交推送到分支 |
| PR被打开、关闭、合并等 |
| Issue被打开、关闭、添加标签等 |
| 发布版本已发布 |
| GitHub Actions工作流完成 |
| 创建Webhook时的测试事件 |
如需完整事件参考,请查看GitHub Webhook Events
| Header | Description |
|---|---|
| HMAC SHA-256 signature (use this, not sha1) |
| Event type (push, pull_request, etc.) |
| Unique delivery ID |
| 请求头 | 描述 |
|---|---|
| HMAC SHA-256签名(请使用这个,不要用sha1) |
| 事件类型(push、pull_request等) |
| 唯一交付ID |
GITHUB_WEBHOOK_SECRET=your_webhook_secret # Set when creating webhook in GitHubGITHUB_WEBHOOK_SECRET=your_webhook_secret # 在GitHub创建Webhook时设置undefinedundefinedundefinedundefined// Generated with: github-webhooks skill
// https://github.com/hookdeck/webhook-skills// Generated with: github-webhooks skill
// https://github.com/hookdeck/webhook-skills