-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
171 lines (143 loc) · 5.39 KB
/
server.js
File metadata and controls
171 lines (143 loc) · 5.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js');
const app = express();
const PORT = process.env.PORT || 3000;
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages]
});
const errorLogLimit = rateLimit({
windowMs: 1 * 60 * 1000,
max: 10,
message: {
error: 'Demasiados reportes de error. Intenta más tarde.',
code: 'RATE_LIMIT_EXCEEDED'
},
standardHeaders: true,
legacyHeaders: false,
});
app.use(helmet());
app.use(cors({
origin: process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : '*',
credentials: true
}));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
app.use('/api/error', errorLogLimit);
const recentErrors = new Map();
const ERROR_COOLDOWN = 5 * 60 * 1000;
function createErrorHash(error) {
return `${error.message}-${error.filename}-${error.lineno}-${error.colno}`;
}
function createErrorEmbed(errorData, userAgent, ip) {
const embed = new EmbedBuilder()
.setColor('#FF0000')
.setTitle('🚨 Error Detectado')
.setTimestamp()
.addFields(
{ name: '📝 Mensaje', value: `\`\`\`${errorData.message || 'Error desconocido'}\`\`\``, inline: false },
{ name: '📍 Ubicación', value: `**Archivo:** ${errorData.filename || 'Desconocido'}\n**Línea:** ${errorData.lineno || 'N/A'}\n**Columna:** ${errorData.colno || 'N/A'}`, inline: true },
{ name: '🌐 Página', value: `**URL:** ${errorData.url || 'Desconocida'}\n**Navegador:** ${userAgent ? userAgent.substring(0, 100) + '...' : 'Desconocido'}`, inline: true }
);
if (errorData.stack) {
embed.addFields({ name: '📚 Stack Trace', value: `\`\`\`${errorData.stack.substring(0, 1000)}${errorData.stack.length > 1000 ? '...' : ''}\`\`\``, inline: false });
}
if (errorData.userInfo) {
embed.addFields({ name: '👤 Info Usuario', value: `\`\`\`json\n${JSON.stringify(errorData.userInfo, null, 2).substring(0, 500)}\`\`\``, inline: false });
}
embed.setFooter({ text: `IP: ${ip} | Error Logger v1.0` });
return embed;
}
app.post('/api/error', async (req, res) => {
try {
const errorData = req.body;
const userAgent = req.get('User-Agent');
const ip = req.ip || req.connection.remoteAddress;
if (!errorData.message && !errorData.error) {
return res.status(400).json({
success: false,
error: 'Mensaje de error requerido'
});
}
const errorHash = createErrorHash(errorData);
const now = Date.now();
if (recentErrors.has(errorHash)) {
const lastReported = recentErrors.get(errorHash);
if (now - lastReported < ERROR_COOLDOWN) {
return res.status(200).json({
success: true,
message: 'Error ya reportado recientemente'
});
}
}
recentErrors.set(errorHash, now);
if (recentErrors.size > 1000) {
const oldEntries = Array.from(recentErrors.entries())
.filter(([, timestamp]) => now - timestamp > ERROR_COOLDOWN);
oldEntries.forEach(([hash]) => recentErrors.delete(hash));
}
const channel = await client.channels.fetch(process.env.DISCORD_CHANNEL_ID);
if (channel) {
const embed = createErrorEmbed(errorData, userAgent, ip);
await channel.send({ embeds: [embed] });
}
res.status(200).json({
success: true,
message: 'Error registrado exitosamente'
});
} catch (error) {
console.error('Error procesando log:', error);
res.status(500).json({
success: false,
error: 'Error interno del servidor'
});
}
});
app.get('/api/health', (req, res) => {
res.json({
status: 'OK',
timestamp: new Date().toISOString(),
discord: client.isReady() ? 'Conectado' : 'Desconectado'
});
});
app.get('/', (req, res) => {
res.json({
name: 'Discord Error Logger',
version: '1.0.0',
description: 'Bot de Discord para recibir errores de frontend',
endpoints: {
'POST /api/error': 'Enviar logs de error',
'GET /api/health': 'Estado del servidor',
'GET /': 'Esta información'
}
});
});
client.once('ready', () => {
console.log(`✅ Bot conectado como ${client.user.tag}`);
console.log(`📡 Canal de monitoreo: ${process.env.DISCORD_CHANNEL_ID}`);
});
client.on('error', (error) => {
console.error('❌ Error del bot:', error);
});
app.listen(PORT, () => {
console.log(`🚀 Servidor corriendo en puerto ${PORT}`);
console.log(`🔗 Estado: http://localhost:${PORT}/api/health`);
if (process.env.DISCORD_BOT_TOKEN) {
client.login(process.env.DISCORD_BOT_TOKEN);
} else {
console.error('❌ DISCORD_BOT_TOKEN no encontrado');
}
});
process.on('SIGINT', () => {
console.log('\n🛑 Cerrando servidor...');
client.destroy();
process.exit(0);
});
process.on('SIGTERM', () => {
console.log('\n🛑 Cerrando servidor...');
client.destroy();
process.exit(0);
});