A guild can reroute a notification type to its own channel from SQLite, with the environment values as fallback, without editing the configuration or restarting the bot.
70 lines
2.5 KiB
JavaScript
70 lines
2.5 KiB
JavaScript
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
import { env } from '../config/env.js';
|
|
import { createLogger } from '../core/logger.js';
|
|
import { getDatabase } from '../database/index.js';
|
|
import { logEvent } from '../database/repositories/event-log-repository.js';
|
|
import { buildGiteaNotification } from '../services/notifications/gitea-notifications.js';
|
|
import { notify } from '../services/notifications/notification-service.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, deduplicates and publishes 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;
|
|
|
|
let payload;
|
|
try {
|
|
payload = JSON.parse(rawBody.toString('utf8'));
|
|
} catch {
|
|
log.warn('Rejected webhook with invalid JSON body', { deliveryId, event });
|
|
return 400;
|
|
}
|
|
|
|
log.info(`Received Gitea event ${event}`, {
|
|
deliveryId,
|
|
repository: payload.repository?.full_name,
|
|
});
|
|
|
|
const notification = buildGiteaNotification(event, payload);
|
|
if (!notification) {
|
|
log.debug(`No notification mapping for Gitea event ${event}`);
|
|
return 202;
|
|
}
|
|
|
|
logEvent({
|
|
guildId: env.discord.guildId || null,
|
|
type: `gitea.${event}`,
|
|
payload: { deliveryId, type: notification.type },
|
|
});
|
|
|
|
await notify(client, notification.type, {
|
|
embeds: [notification.embed],
|
|
content: payload.repository?.full_name ? `**${payload.repository.full_name}**` : undefined,
|
|
}).catch((error) => log.error('Could not publish the Gitea notification', error));
|
|
|
|
return 202;
|
|
}
|