Files
MC_Report/backend/webhook.js
canglan 8c5ce78fd0 chore: add AGPLv3 copyright header to all source files
- 52 JS files (backend + public/js): header with
  Copyright (C) 2026 Sea Network Technology Studio
  Author: CangLan <admin@sea-studio.top>
  + AGPLv3 notice
- idempotent (skips if header present), all syntax-checked
2026-08-19 20:27:05 +08:00

78 lines
4.4 KiB
JavaScript

/*
* MC Report System
* Copyright (C) 2026 Sea Network Technology Studio
* Author: CangLan <admin@sea-studio.top>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
const { query, getRow } = require('./db');
const { logSystem } = require('./logger');
const EVENT_LABELS = { ticket_created:'工单创建', ticket_claimed:'工单认领', ticket_transferred:'工单转交', ticket_updated:'工单更新' };
const dns = require('dns').promises;
const { URL } = require('url');
async function isPrivateUrl(urlStr) {
try {
const u = new URL(urlStr);
if (u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '0.0.0.0') return true;
if (u.hostname.startsWith('192.168.') || u.hostname.startsWith('10.') || u.hostname.startsWith('172.16.')) return true;
const addrs = await dns.resolve4(u.hostname).catch(() => []);
for (const addr of addrs) {
if (addr === '127.0.0.1' || addr.startsWith('192.168.') || addr.startsWith('10.') || addr.startsWith('172.16.') || addr.startsWith('0.')) return true;
}
return false;
} catch { return true; }
}
async function sendWebhook(event, data) {
try {
const configs = await query("SELECT * FROM notification_configs WHERE type = 'webhook' AND active = 1");
for (const cfg of configs) {
const events = cfg.events || 'all';
if (events !== 'all' && !events.split(',').map(s=>s.trim()).includes(event)) continue;
if (cfg.webhook_url && await isPrivateUrl(cfg.webhook_url)) { console.error('[Webhook] blocked internal URL:', cfg.name); await logSystem('warn', 'webhook', `拦截内网地址: ${cfg.name}`, { url: cfg.webhook_url }); continue; }
const embed = buildEmbed(event, data);
try {
const ctl = new AbortController();
const t = setTimeout(() => ctl.abort(), 10000);
const resp = await fetch(cfg.webhook_url, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(embed), signal: ctl.signal });
clearTimeout(t);
if (resp.status < 200 || resp.status >= 300) {
await logSystem('warn', 'webhook', `Webhook ${cfg.name} 返回 ${resp.status}`, { event, url: cfg.webhook_url });
}
} catch (e) {
console.error('[Webhook]', cfg.name, e.message);
await logSystem('error', 'webhook', `Webhook ${cfg.name} 发送失败: ${e.message}`, { event, url: cfg.webhook_url });
}
}
} catch {}
}
function buildEmbed(event, data) {
const row = data._siteName ? { v: data._siteName } : null;
const siteName = row?.v || 'MC举报系统';
const colors = { ticket_created:0x4f46e5, ticket_claimed:0x10b981, ticket_transferred:0xf59e0b, ticket_updated:0x3b82f6 };
const embed = { username: siteName, embeds:[{ title:EVENT_LABELS[event]||event, color:colors[event]||0x4f46e5, timestamp:new Date().toISOString(), fields:[] }] };
if (event==='ticket_created') { embed.embeds[0].description=`**#${data.ticket_id}** - ${data.ticket_title||''}`; embed.embeds[0].fields.push({name:'类型',value:data.ticket_type||data.type||'?',inline:true},{name:'提交者',value:`${data.reporter_game_name||'?'} (UID:${data.reporter_game_uid||'?'})`,inline:true}); }
else if (event==='ticket_claimed') { embed.embeds[0].description=`**#${data.ticket_id}** - ${data.ticket_title}`; embed.embeds[0].fields.push({name:'认领人',value:data.assigned_to||'?',inline:true}); }
else if (event==='ticket_transferred') { embed.embeds[0].description=`**#${data.ticket_id}** - ${data.ticket_title}`; embed.embeds[0].fields.push({name:'转出',value:data.from_user||'?',inline:true},{name:'转入',value:data.to_user||'?',inline:true}); }
else if (event==='ticket_updated') { embed.embeds[0].description=`**#${data.ticket_id}** - ${data.ticket_title}`; if(data.new_status)embed.embeds[0].fields.push({name:'新状态',value:data.new_status,inline:true}); }
return embed;
}
module.exports = { sendWebhook };