fix: seguridad del webhook de soporte, pagos en contabilidad y Telegram para tareas

- soporte: el webhook de correo entrante era público sin ninguna validación;
  ahora exige una API key (query ?key= o header) comparada en tiempo constante.
  Además evita tickets duplicados por reintentos del proveedor (dedup por
  Message-Id) y enhebra respuestas del mismo remitente en vez de abrir un
  ticket nuevo por cada correo.
- contabilidad: marcar una cuenta por cobrar/pagar como pagada ahora crea y
  vincula la Transaccion correspondiente (antes el dashboard de ingresos/
  egresos nunca reflejaba esos pagos). Se corrige además que actualizar una
  cuenta por cobrar borraba su transaccion_id en cada PUT.
- tareas: se activa por defecto el canal Telegram para tarea_asignada (estaba
  apagado desde el seed original) y se agrega un flujo real de vinculación de
  Telegram para el staff interno (código temporal + verificación), igual al
  que ya existía para los usuarios del portal — sin esto el chat_id de cada
  usuario había que pegarlo a mano y la notificación nunca llegaba.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Lizandro GD
2026-08-03 01:25:17 +00:00
co-authored by Claude Sonnet 5
parent 1127d944c7
commit d2bf699b60
14 changed files with 612 additions and 100 deletions
@@ -174,7 +174,7 @@ function cobroApp() {
async doPagar(){
this.saving=true;
try {
await axios.put(`/app/contabilidad/cuentas-cobro/${this.pagarId}`, {estado:'pagado',fecha_pago:this.pagoFecha});
await axios.post(`/app/contabilidad/cuentas-cobro/${this.pagarId}/pagar`, {fecha_pago:this.pagoFecha});
this.showPagarModal=false; await this.load();
} catch(e){ this.error=e.response?.data?.error||'Error'; }
finally{ this.saving=false; }
+109
View File
@@ -76,6 +76,69 @@
</button>
</div>
</form>
<!-- Telegram -->
<div class="mt-6 pt-6 border-t border-slate-100">
<h2 class="text-sm font-semibold text-slate-700 mb-1">Notificaciones por Telegram</h2>
<p class="text-xs text-slate-500 mb-4">Vincula tu Telegram para recibir avisos de tareas asignadas y otras notificaciones personales.</p>
<div x-show="tg.linked" class="flex items-center gap-3 p-3 bg-green-50 border border-green-200 rounded-lg">
<svg class="w-5 h-5 text-green-500 flex-shrink-0" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
<div>
<p class="text-sm font-semibold text-green-800">Telegram vinculado</p>
<p class="text-xs text-green-600">Chat ID: <span class="font-mono" x-text="tg.chat_id"></span></p>
</div>
</div>
<div x-show="!tg.linked" class="space-y-3">
<div class="flex gap-3">
<span class="flex-shrink-0 w-6 h-6 rounded-full text-white flex items-center justify-center text-xs font-bold" style="background-color:#8eb02f">1</span>
<div class="flex-1">
<p class="text-sm text-slate-700 font-medium">Genera tu código</p>
<button @click="tgGenerarCodigo()" :disabled="tg.generando"
class="mt-1.5 inline-flex items-center gap-1.5 px-3 py-1.5 text-white text-xs font-semibold rounded-lg transition-colors disabled:opacity-60"
style="background-color:#8eb02f">
<span x-show="!tg.generando">Generar código</span>
<span x-show="tg.generando">Generando…</span>
</button>
</div>
</div>
<div x-show="tg.token" class="ml-9 p-3 bg-slate-800 rounded-lg">
<p class="text-xs text-slate-400 mb-1">Tu código de vinculación:</p>
<p class="text-2xl font-mono font-bold text-white tracking-widest" x-text="tg.token"></p>
</div>
<div x-show="tg.token" class="flex gap-3">
<span class="flex-shrink-0 w-6 h-6 rounded-full text-white flex items-center justify-center text-xs font-bold" style="background-color:#8eb02f">2</span>
<div class="flex-1">
<p class="text-sm text-slate-700 font-medium">Envía el código al bot</p>
<div class="flex items-center gap-2 p-2 bg-slate-100 rounded-lg mt-1">
<code class="text-sm font-mono text-slate-800" x-text="'/vincular ' + tg.token"></code>
</div>
<template x-if="tg.bot_username">
<a :href="tg.bot_link" target="_blank" class="inline-flex items-center gap-1 mt-2 text-xs font-semibold hover:underline" style="color:#8eb02f">
Abrir @<span x-text="tg.bot_username"></span>
</a>
</template>
</div>
</div>
<div x-show="tg.token" class="flex gap-3">
<span class="flex-shrink-0 w-6 h-6 rounded-full text-white flex items-center justify-center text-xs font-bold" style="background-color:#8eb02f">3</span>
<div class="flex-1">
<p class="text-sm text-slate-700 font-medium">Verifica la vinculación</p>
<button @click="tgVerificar()" :disabled="tg.verificando"
class="mt-1.5 inline-flex items-center gap-1.5 px-3 py-1.5 border text-xs font-semibold rounded-lg transition-colors disabled:opacity-60"
style="border-color:#8eb02f;color:#8eb02f">
<span x-show="!tg.verificando">Verificar vinculación</span>
<span x-show="tg.verificando">Verificando…</span>
</button>
<p x-show="tg.verMsg" x-text="tg.verMsg" :class="tg.verOk ? 'text-green-600' : 'text-red-500'" class="text-xs mt-2"></p>
</div>
</div>
</div>
</div>
</div>
<!-- Modal cambiar contraseña -->
<div x-cloak x-show="showPasswordModal"
@@ -148,9 +211,55 @@
Id: null,
isLoading: false,
usuarioID: '{{ .user.ID }}', // Inicializar directamente en el Alpine.js
tg: { linked: false, chat_id: '', token: '', bot_username: '', bot_link: '', generando: false, verificando: false, verMsg: '', verOk: false },
init() {
this.loadRegister();
this.loadTelegramStatus();
},
async loadTelegramStatus() {
try {
const r = await axios.get('/app/profile/telegram-status');
this.tg.linked = r.data.linked;
this.tg.chat_id = r.data.chat_id;
} catch (e) {}
},
async tgGenerarCodigo() {
this.tg.generando = true;
this.tg.token = '';
this.tg.verMsg = '';
try {
const r = await axios.post('/app/profile/telegram-init');
this.tg.token = r.data.token;
this.tg.bot_username = r.data.bot_username || '';
this.tg.bot_link = r.data.bot_link || '';
} catch (e) {
this.tg.verMsg = 'No se pudo generar el código. Intenta de nuevo.';
this.tg.verOk = false;
} finally { this.tg.generando = false; }
},
async tgVerificar() {
this.tg.verificando = true;
this.tg.verMsg = '';
try {
const r = await axios.post('/app/profile/telegram-validar');
if (r.data.ok) {
this.tg.linked = true;
this.tg.chat_id = r.data.chat_id;
this.tg.token = '';
this.tg.verMsg = '✅ ¡Telegram vinculado correctamente!';
this.tg.verOk = true;
} else {
this.tg.verMsg = r.data.error || 'No se encontró el mensaje.';
this.tg.verOk = false;
}
} catch (e) {
this.tg.verMsg = e.response?.data?.error || 'Error al verificar. Intenta de nuevo.';
this.tg.verOk = false;
} finally { this.tg.verificando = false; }
},
loadRegister() {
+25 -8
View File
@@ -21,9 +21,15 @@
<div>
<label class="block text-sm font-medium text-slate-700 mb-1">API Key / Secreto</label>
<input x-model="cfg.api_key" type="text" placeholder="opcional para validación"
class="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm outline-none">
<p class="text-xs text-slate-400 mt-1">Si el proveedor envía un token de verificación, pégalo aquí.</p>
<div class="flex gap-2">
<input x-model="cfg.api_key" type="text" placeholder="requerido para validar el webhook"
class="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm outline-none">
<button type="button" @click="cfg.api_key = generarClave()"
class="px-3 py-2 rounded-lg text-xs font-medium border border-slate-200 text-slate-600 hover:bg-slate-50 whitespace-nowrap">
Generar
</button>
</div>
<p class="text-xs text-slate-400 mt-1">Obligatoria: las peticiones sin esta clave (como <code>?key=...</code>) son rechazadas. Configúrala también en el proveedor si soporta enviarla como parámetro/header.</p>
</div>
<div class="flex items-center gap-3">
@@ -113,10 +119,10 @@
</button>
</div>
<div x-show="webhookUrl" class="bg-slate-50 border border-slate-200 rounded-lg p-4 mt-4">
<div class="bg-slate-50 border border-slate-200 rounded-lg p-4 mt-4">
<p class="text-xs font-medium text-slate-600 mb-1">URL del webhook</p>
<p class="text-sm text-slate-800 font-mono break-all" x-text="webhookUrl"></p>
<p class="text-xs text-slate-400 mt-1">Configura esta URL en el proveedor de correo para enviar los emails entrantes.</p>
<p class="text-sm text-slate-800 font-mono break-all" x-text="webhookUrl()"></p>
<p class="text-xs text-slate-400 mt-1">Configura esta URL exacta (con la clave incluida) en el proveedor de correo para enviar los emails entrantes.</p>
</div>
</div>
</div>
@@ -142,7 +148,6 @@ function soporteWebhook() {
smtp_from_name: '',
},
admins: [],
webhookUrl: '',
async init() {
try {
@@ -156,7 +161,19 @@ function soporteWebhook() {
const r = await axios.get('/app/tickets/admins');
this.admins = r.data || [];
} catch {}
this.webhookUrl = window.location.origin + '/webhooks/soporte/' + this.cfg.provider;
if (!this.cfg.api_key) {
this.cfg.api_key = this.generarClave();
}
},
generarClave() {
if (window.crypto && crypto.randomUUID) return crypto.randomUUID().replace(/-/g, '');
return Array.from(crypto.getRandomValues(new Uint8Array(24))).map(b => b.toString(16).padStart(2, '0')).join('');
},
webhookUrl() {
const base = window.location.origin + '/webhooks/soporte/' + this.cfg.provider;
return this.cfg.api_key ? `${base}?key=${this.cfg.api_key}` : base;
},
async guardar() {