feat(webhooks): validate and deduplicate gitea webhook events
Refs: #75 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 file changed
+40
@@ -0,0 +1,40 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto';
|
||||
import { env } from '../config/env.js';
|
||||
import { createLogger } from '../core/logger.js';
|
||||
import { getDatabase } from '../database/index.js';
|
||||
|
||||
const log = createLogger('webhooks');
|
||||
|
||||
export function isValidSignature(rawBody, signature, secret = env.webhook.secret) {
|
||||
if (!secret || !signature) return false;
|
||||
const expected = Buffer.from(createHmac('sha256', secret).update(rawBody).digest('hex'));
|
||||
const received = Buffer.from(signature);
|
||||
return expected.length === received.length && timingSafeEqual(expected, received);
|
||||
}
|
||||
|
||||
/** Returns true the first time a delivery id is seen (M9-T08). */
|
||||
function markDelivered(deliveryId, event) {
|
||||
const result = getDatabase()
|
||||
.prepare('INSERT OR IGNORE INTO webhook_deliveries (delivery_id, event) VALUES (?, ?)')
|
||||
.run(deliveryId, event);
|
||||
return result.changes > 0;
|
||||
}
|
||||
|
||||
/** Validates and dispatches a Gitea webhook. Returns the HTTP status code. */
|
||||
export async function handleGiteaWebhook(_client, headers, rawBody) {
|
||||
if (!isValidSignature(rawBody, headers['x-gitea-signature'])) {
|
||||
log.warn('Rejected webhook with invalid signature');
|
||||
return 401;
|
||||
}
|
||||
|
||||
const event = headers['x-gitea-event'];
|
||||
const deliveryId = headers['x-gitea-delivery'];
|
||||
if (!event || !deliveryId) return 400;
|
||||
if (!markDelivered(deliveryId, event)) return 200;
|
||||
|
||||
const payload = JSON.parse(rawBody.toString('utf8'));
|
||||
log.info(`Received Gitea event ${event}`, { deliveryId, repository: payload.repository?.full_name });
|
||||
|
||||
// TODO(M9-T03..T07): filter events and publish embeds through notification-service.
|
||||
return 202;
|
||||
}
|
||||
Reference in new issue
Block a user