import { describe, expect, it } from "vitest"; import { origenesConfiables } from "@/lib/auth/origins"; import { extraerTexto, PREFIJO_TRANSCRIPCION, textoTranscrito, transcribirAudio, whisperConfig } from "@/server/ai/whisper"; import { estadoVentana } from "@/lib/ventana-meta"; import { puedeSimular } from "@/server/inbox/simular-entrante"; import { nombreDelRespaldo, tablasDeLaOrganizacion } from "@/server/backups"; /** orígenes confiables, Whisper, ventana de Meta, simulación y respaldos. */ function headers(h: Record) { return new Headers(h); } describe("orígenes confiables del login", () => { it("APP_BASE_URL en http y https, con los puertos 3000 y 3003", () => { const o = origenesConfiables("https://crm.empresa.com", null); for (const u of [ "https://crm.empresa.com", "http://crm.empresa.com", "http://crm.empresa.com:3003", "https://crm.empresa.com:3000", ]) { expect(o).toContain(u); } }); it("confía en host y x-forwarded-host (detrás de un proxy o por IP)", () => { const o = origenesConfiables("http://localhost:3003", headers({ host: "10.0.0.5:3003", "x-forwarded-host": "crm.local" })); expect(o).toContain("http://10.0.0.5:3003"); expect(o).toContain("https://crm.local"); }); it("un origin ajeno NO se vuelve confiable (CSRF)", () => { const o = origenesConfiables( "https://crm.empresa.com", headers({ host: "crm.empresa.com", origin: "https://atacante.example", referer: "https://atacante.example/x" }) ); expect(o.some((u) => u.includes("atacante"))).toBe(false); }); it("un origin del mismo host con otro puerto sí", () => { const o = origenesConfiables("https://crm.empresa.com", headers({ origin: "http://crm.empresa.com:8080" })); expect(o).toContain("http://crm.empresa.com:8080"); }); }); describe("Whisper (opcional)", () => { it("apagado sin proveedor, sin llave o con placeholder", () => { expect(whisperConfig({})).toBeNull(); expect(whisperConfig({ WHISPER_PROVIDER: "groq" })).toBeNull(); expect(whisperConfig({ WHISPER_PROVIDER: "groq", WHISPER_API_KEY: "REEMPLAZA_x" })).toBeNull(); expect(whisperConfig({ WHISPER_PROVIDER: "otro", WHISPER_API_KEY: "k" })).toBeNull(); }); it("defaults por proveedor y español", () => { const c = whisperConfig({ WHISPER_PROVIDER: "Groq", WHISPER_API_KEY: "gsk_1" }); expect(c?.baseUrl).toBe("https://api.groq.com/openai/v1"); expect(c?.model).toBe("whisper-large-v3-turbo"); expect(c?.language).toBe("es"); expect(whisperConfig({ WHISPER_PROVIDER: "openai", WHISPER_API_KEY: "sk", WHISPER_BASE_URL: "https://x/v1/" })?.baseUrl).toBe( "https://x/v1" ); }); it("el texto guardado lleva el prefijo y conserva el pie de foto", () => { expect(textoTranscrito(' hola "mundo" ')).toBe(`${PREFIJO_TRANSCRIPCION} "hola ”mundo”"`); expect(textoTranscrito("hola", "pie")).toBe(`pie\n${PREFIJO_TRANSCRIPCION} "hola"`); }); it("extrae el texto con tolerancia", () => { expect(extraerTexto({ text: " hola " })).toBe("hola"); expect(extraerTexto({ text: "" })).toBeNull(); expect(extraerTexto("basura")).toBeNull(); }); it("reintenta un hipo y no insiste con llave inválida", async () => { const cfg = whisperConfig({ WHISPER_PROVIDER: "openai", WHISPER_API_KEY: "sk" })!; let n = 0; const flaky = (async () => { n++; return n === 1 ? new Response("x", { status: 500 }) : Response.json({ text: "listo" }); }) as typeof fetch; expect(await transcribirAudio(cfg, Buffer.from("a"), "audio/ogg", "a.ogg", flaky)).toBe("listo"); let m = 0; const noAuth = (async () => { m++; return new Response("no", { status: 401 }); }) as typeof fetch; expect(await transcribirAudio(cfg, Buffer.from("a"), "audio/ogg", "a.ogg", noAuth)).toBeNull(); expect(m).toBe(1); }); }); describe("ventana de Meta", () => { it("24h abierta con lo que le queda; ámbar con ≤ 2 h", () => { const v = estadoVentana({ windowOpen: true, windowRemainingMs: 5 * 3_600_000 + 20 * 60_000, humanWindow: null }); expect(v.tipo).toBe("abierta"); expect(v.texto).toBe("24h abierta · quedan 5h 20m"); expect(v.tono).toBe("ok"); expect(estadoVentana({ windowOpen: true, windowRemainingMs: 30 * 60_000, humanWindow: null }).tono).toBe("warn"); }); it("ventana humana 7d en Instagram/Messenger", () => { const v = estadoVentana({ windowOpen: false, windowRemainingMs: 0, humanWindow: { open: true, remainingMs: 3 * 86_400_000 + 4 * 3_600_000 }, }); expect(v.tipo).toBe("humana"); expect(v.texto).toBe("Ventana humana 7d · quedan 3d 4h"); }); it("cerrada", () => { expect(estadoVentana({ windowOpen: false, windowRemainingMs: 0, humanWindow: { open: false, remainingMs: 0 } }).tipo).toBe( "cerrada" ); }); }); describe("simular cliente", () => { it("solo en conversaciones de prueba, o con los mocks encendidos", () => { expect(puedeSimular({ isTest: true }, false)).toBe(true); expect(puedeSimular({ isTest: false }, false)).toBe(false); expect(puedeSimular({ isTest: false }, true)).toBe(true); }); }); describe("respaldos", () => { it("incluyen las tablas de dominio de la organización, también las de servicios y campos", () => { const nombres = tablasDeLaOrganizacion().map((t) => t.nombre); for (const t of ["contact", "conversation", "message", "service_item", "custom_field", "custom_field_value"]) { expect(nombres, t).toContain(t); } }); it("nombre del archivo con fecha y .json.gz", () => { expect(nombreDelRespaldo(new Date("2026-12-04T15:07:00Z"), "Mi CRM")).toMatch( /^mi-crm-respaldo-2026-12-04-\d{4}\.json\.gz$/ ); }); });