-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
255 lines (227 loc) · 9.31 KB
/
Copy pathserver.js
File metadata and controls
255 lines (227 loc) · 9.31 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import { Resend } from 'resend';
import rateLimit from 'express-rate-limit';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 8080;
// Trust reverse proxies (Dokploy / Docker / Traefik / Nginx / Cloudflare)
app.set('trust proxy', 1);
// Helper to escape HTML characters
function escapeHtml(string) {
return String(string)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Rate Limiter for Contact Form Submissions
const contactLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: process.env.RATE_LIMIT_MAX ? parseInt(process.env.RATE_LIMIT_MAX, 10) : 5, // 5 requests per 15 min per IP by default
standardHeaders: true,
legacyHeaders: false,
message: {
success: false,
error: 'Demasiadas solicitudes desde esta dirección IP. Por favor intente nuevamente en unos minutos.'
}
});
// Health Check Endpoint (useful for Dokploy / Docker health checks)
app.get(['/health', '/api/health'], (req, res) => {
res.status(200).json({
status: 'ok',
uptime: process.uptime(),
timestamp: new Date().toISOString()
});
});
// Public Configuration Endpoint (exposes client-safe keys like Turnstile Site Key)
app.get('/api/config', (req, res) => {
res.status(200).json({
turnstileSiteKey: process.env.TURNSTILE_SITE_KEY || '0x4AAAAAAE5gTqmPsHQzwMg9'
});
});
// Contact Form Submission Endpoint
app.post('/api/contact', contactLimiter, async (req, res) => {
try {
// 1. Honeypot Check (catches naive bots)
const honeypot = req.body._honey || req.body.website_url;
if (honeypot) {
console.warn(`[Spam Blocked]: Honeypot triggered from IP ${req.ip}`);
return res.status(200).json({ success: true, message: 'Mensaje enviado exitosamente.' });
}
// 2. Submission Time Trap (humans take >= 2.5s to fill 3 fields)
const formTime = parseInt(req.body.form_time, 10);
if (formTime) {
const elapsed = Date.now() - formTime;
if (elapsed < 2500) {
console.warn(`[Spam Blocked]: Form submitted suspiciously fast (${elapsed}ms) from IP ${req.ip}`);
return res.status(200).json({ success: true, message: 'Mensaje enviado exitosamente.' });
}
}
// 3. Cloudflare Turnstile Canonical Siteverify (if configured)
const turnstileSecret = process.env.TURNSTILE_SECRET || process.env.TURNSTILE_SECRET_KEY;
if (turnstileSecret) {
const expectedAction = 'contact';
const expectedHostnames = new Set(
(process.env.TURNSTILE_HOSTNAMES || 'solucioneshospedadas.com,localhost,127.0.0.1')
.split(',')
.map((h) => h.trim())
.filter(Boolean)
);
const token = req.body['cf-turnstile-response'];
if (
typeof token !== 'string' ||
token.length === 0 ||
token.length > 2048 ||
expectedHostnames.size === 0
) {
return res.status(403).json({
success: false,
error: 'Verificación de seguridad inválida o ausente (Turnstile).'
});
}
let result;
try {
const verifyRes = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
signal: AbortSignal.timeout(10_000),
body: new URLSearchParams({
secret: turnstileSecret,
response: token,
remoteip: req.ip || ''
})
});
result = await verifyRes.json();
} catch (verifyErr) {
console.error('[Turnstile Verify Error]:', verifyErr);
return res.status(403).json({
success: false,
error: 'Error al contactar el servicio de verificación de seguridad.'
});
}
if (
!result ||
!result.success ||
result.action !== expectedAction ||
!expectedHostnames.has(result.hostname)
) {
console.warn('[Spam Blocked]: Turnstile verification failed:', {
success: result?.success,
action: result?.action,
hostname: result?.hostname,
errors: result?.['error-codes']
});
return res.status(403).json({
success: false,
error: 'Fallo la verificación de seguridad (Turnstile).'
});
}
}
const name = (req.body.Nombre || req.body.nombre || req.body.name || '').trim();
const email = (req.body.Email || req.body.email || '').trim();
const message = (req.body.Mensaje || req.body.mensaje || req.body.message || '').trim();
if (!name || !email || !message) {
return res.status(400).json({
success: false,
error: 'Todos los campos son obligatorios / All fields are required.'
});
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return res.status(400).json({
success: false,
error: 'El formato de correo no es válido / Invalid email format.'
});
}
// 4. Heuristic Checks: Block if Name contains URL links
if (/https?:\/\/|www\./i.test(name)) {
console.warn(`[Spam Blocked]: Name field contains URL from IP ${req.ip}`);
return res.status(200).json({ success: true, message: 'Mensaje enviado exitosamente.' });
}
const apiKey = process.env.RESEND_API_KEY;
if (!apiKey) {
console.error('[Resend Error]: RESEND_API_KEY environment variable is not configured.');
return res.status(500).json({
success: false,
error: 'El servicio de correo no está configurado (falta RESEND_API_KEY).'
});
}
const resend = new Resend(apiKey);
const toEmail = process.env.DESTINATION_EMAIL || process.env.TO_EMAIL || 'contacto@solucioneshospedadas.com';
const fromEmail = process.env.FROM_EMAIL || 'Soluciones Hospedadas <onboarding@resend.dev>';
const { data, error } = await resend.emails.send({
from: fromEmail,
to: [toEmail],
replyTo: email,
subject: `Nuevo mensaje de contacto: ${name}`,
text: `Has recibido un nuevo mensaje de contacto desde solucioneshospedadas.com:\n\nNombre: ${name}\nEmail: ${email}\nMensaje:\n${message}\n`,
html: `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 24px; border: 1px solid #e2e8f0; border-radius: 12px; background-color: #ffffff;">
<div style="border-bottom: 2px solid #006591; padding-bottom: 12px; margin-bottom: 20px;">
<h2 style="color: #006591; margin: 0; font-size: 20px;">Soluciones Hospedadas</h2>
<p style="color: #64748b; font-size: 13px; margin: 4px 0 0;">Nuevo mensaje recibido desde el formulario web</p>
</div>
<table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
<tr>
<td style="padding: 8px 0; width: 130px; color: #64748b; font-size: 14px; font-weight: 600;">Nombre:</td>
<td style="padding: 8px 0; color: #1e293b; font-size: 14px; font-weight: 500;">${escapeHtml(name)}</td>
</tr>
<tr>
<td style="padding: 8px 0; color: #64748b; font-size: 14px; font-weight: 600;">Correo:</td>
<td style="padding: 8px 0; color: #1e293b; font-size: 14px;">
<a href="mailto:${escapeHtml(email)}" style="color: #006591; text-decoration: none;">${escapeHtml(email)}</a>
</td>
</tr>
<tr>
<td style="padding: 12px 0 4px; color: #64748b; font-size: 14px; font-weight: 600;" colspan="2">Mensaje:</td>
</tr>
<tr>
<td colspan="2" style="background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 14px; color: #334155; font-size: 14px; line-height: 1.6; white-space: pre-wrap;">${escapeHtml(message)}</td>
</tr>
</table>
<div style="border-top: 1px solid #e2e8f0; padding-top: 14px; font-size: 12px; color: #94a3b8; text-align: center;">
Puedes responder directamente a este correo para contestar a <strong>${escapeHtml(name)}</strong>.
</div>
</div>
`
});
if (error) {
console.error('[Resend API Error]:', error);
return res.status(500).json({
success: false,
error: error.message || 'Error al enviar el correo mediante Resend.'
});
}
return res.status(200).json({
success: true,
message: 'Mensaje enviado exitosamente.',
id: data?.id
});
} catch (err) {
console.error('[Server Error]:', err);
return res.status(500).json({
success: false,
error: 'Error interno del servidor al procesar la solicitud.'
});
}
});
// Serve static assets (HTML, images, CSS, etc.)
app.use(express.static(__dirname));
// Fallback to index.html for root or unknown static routes
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(PORT, () => {
console.log(`> Server running on port ${PORT}`);
});