Auth, rate limit y helmet (Fase 0 hardening)

- Login con contraseña validada en backend (ADMIN_PASSWORD env var, nunca
  en el bundle del frontend). Token de sesión HMAC sin estado firmado con
  SESSION_SECRET (generado efímeramente si no se define), TTL 7 días.
- Middleware requireAuth en /api/session, /api/extract, /api/reels (GET/
  POST/DELETE), /api/expedientes (GET/POST/DELETE) y /api/generar. Solo
  /api/health y /api/login quedan públicos.
- Rate limiting: login (10/15min), generar (10/5min), extract (20/5min).
- helmet() para cabeceras de seguridad. Eliminado cors() porque todo es
  same-origin vía el nginx del frontend.
- /api/health hace ping a Postgres (SELECT 1) y devuelve 503 si falla.
- docker-compose: healthcheck del backend + frontend espera service_healthy.
  Nuevas env vars ADMIN_PASSWORD y SESSION_SECRET (placeholders en
  .env.example, sin valores reales).
- Frontend: pantalla de login glassmorphism, gate de auth en App, botón
  "Salir", listener de 401 que vuelve al login.
- vite.config.js: proxy de dev (5173 → backend:3001) para probar en local.
This commit is contained in:
Jorem Juárez committed 2026-05-26 13:32:52 -06:00
1 parent 506de5e271
commit 2b2982eff4
6 files changed
+238 -20

No files matched your search

+9
View File
@@ -12,3 +12,12 @@ ANTHROPIC_MODEL=claude-opus-4-20250514
# Tokens máximos de salida del brief
MAX_TOKENS=4000
# Contraseña de acceso a la app (la pide la pantalla de login).
# Elige una larga y única; vive SOLO aquí, nunca en el bundle del frontend.
ADMIN_PASSWORD=cambia-esto-por-una-clave-larga
# Secreto para firmar los tokens de sesión (HMAC-SHA256).
# Genera uno con: openssl rand -hex 32
# Si lo dejas vacío, el backend genera uno efímero y las sesiones se invalidan al reiniciar.
SESSION_SECRET=
+2 -1
View File
@@ -9,8 +9,9 @@
},
"dependencies": {
"@anthropic-ai/sdk": "^0.32.1",
"cors": "^2.8.5",
"express": "^4.21.2",
"express-rate-limit": "^7.4.1",
"helmet": "^8.0.0",
"mammoth": "^1.8.0",
"multer": "^1.4.5-lts.1",
"pdf-parse": "^1.1.1",
+94 -12
View File
@@ -1,5 +1,4 @@
import express from "express";
import cors from "cors";
import multer from "multer";
import pkg from "pg";
import { readFileSync } from "fs";
@@ -8,6 +7,9 @@ import { dirname, join } from "path";
import mammoth from "mammoth";
import { createRequire } from "module";
import Anthropic from "@anthropic-ai/sdk";
import helmet from "helmet";
import rateLimit from "express-rate-limit";
import crypto from "crypto";
const require = createRequire(import.meta.url);
const pdfParse = require("pdf-parse");
@@ -17,13 +19,20 @@ const { Pool } = pkg;
// ── Config desde variables de entorno ──────────────────────────
const PORT = process.env.PORT || 3001;
const DATABASE_URL = process.env.DATABASE_URL; // la inyecta Coolify
const DATABASE_URL = process.env.DATABASE_URL;
const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
const MODEL = process.env.ANTHROPIC_MODEL || "claude-opus-4-20250514";
const MAX_TOKENS = parseInt(process.env.MAX_TOKENS || "4000", 10);
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD;
const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 días
// Si no se define SESSION_SECRET, generamos uno efímero: las sesiones no
// sobreviven a un reinicio del contenedor (aceptable, fail-safe).
const SESSION_SECRET = process.env.SESSION_SECRET || crypto.randomBytes(32).toString("hex");
if (!DATABASE_URL) { console.error("FALTA DATABASE_URL"); process.exit(1); }
if (!ADMIN_PASSWORD) { console.error("FALTA ADMIN_PASSWORD"); process.exit(1); }
if (!ANTHROPIC_API_KEY) console.warn("AVISO: falta ANTHROPIC_API_KEY; /api/generar fallará hasta configurarla.");
if (!process.env.SESSION_SECRET) console.warn("AVISO: SESSION_SECRET no definido; se generó uno efímero (sesiones se invalidan al reiniciar).");
const pool = new Pool({ connectionString: DATABASE_URL });
const anthropic = new Anthropic({ apiKey: ANTHROPIC_API_KEY });
@@ -35,18 +44,91 @@ async function initDB() {
console.log("Esquema verificado.");
}
// ── Sesiones: token HMAC sin estado ────────────────────────────
function signToken(exp) {
const mac = crypto.createHmac("sha256", SESSION_SECRET).update(String(exp)).digest("hex");
return `${exp}.${mac}`;
}
function verifyToken(token) {
if (typeof token !== "string") return false;
const dot = token.indexOf(".");
if (dot < 1) return false;
const exp = token.slice(0, dot);
const mac = token.slice(dot + 1);
if (!/^\d+$/.test(exp) || !/^[0-9a-f]+$/i.test(mac)) return false;
const expected = crypto.createHmac("sha256", SESSION_SECRET).update(exp).digest("hex");
const a = Buffer.from(mac, "hex");
const b = Buffer.from(expected, "hex");
if (a.length !== b.length) return false;
if (!crypto.timingSafeEqual(a, b)) return false;
return Number(exp) > Date.now();
}
function timingSafeEqualStr(a, b) {
const ab = Buffer.from(a, "utf8");
const bb = Buffer.from(b, "utf8");
if (ab.length !== bb.length) return false;
return crypto.timingSafeEqual(ab, bb);
}
// ── App ────────────────────────────────────────────────────────
const app = express();
app.use(cors());
app.set("trust proxy", 1); // detrás del nginx del frontend y del proxy de Coolify
app.use(helmet());
app.use(express.json({ limit: "5mb" }));
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 15 * 1024 * 1024 } });
const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
app.get("/api/health", (_req, res) => res.json({ ok: true, model: MODEL }));
// ── Rate limiters ──────────────────────────────────────────────
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, max: 10,
standardHeaders: true, legacyHeaders: false,
message: { error: "Demasiados intentos. Espera unos minutos." },
});
const generateLimiter = rateLimit({
windowMs: 5 * 60 * 1000, max: 10,
standardHeaders: true, legacyHeaders: false,
message: { error: "Demasiadas generaciones. Espera unos minutos." },
});
const extractLimiter = rateLimit({
windowMs: 5 * 60 * 1000, max: 20,
standardHeaders: true, legacyHeaders: false,
message: { error: "Demasiadas extracciones. Espera unos minutos." },
});
// ── Middleware de auth ─────────────────────────────────────────
function requireAuth(req, res, next) {
const h = req.headers.authorization || "";
const m = h.match(/^Bearer\s+(.+)$/);
if (!m || !verifyToken(m[1])) return res.status(401).json({ error: "No autorizado." });
next();
}
// ── Health (público, hace ping a DB) ───────────────────────────
app.get("/api/health", async (_req, res) => {
try {
await pool.query("SELECT 1");
res.json({ ok: true, model: MODEL });
} catch {
res.status(503).json({ ok: false, error: "db" });
}
});
// ── Login ──────────────────────────────────────────────────────
app.post("/api/login", loginLimiter, (req, res) => {
const password = req.body?.password;
if (typeof password !== "string" || !timingSafeEqualStr(password, ADMIN_PASSWORD)) {
return res.status(401).json({ error: "Contraseña incorrecta." });
}
const exp = Date.now() + SESSION_TTL_MS;
res.json({ token: signToken(exp), exp });
});
// Verifica sesión activa (lo usa el frontend al recargar)
app.get("/api/session", requireAuth, (_req, res) => res.json({ ok: true }));
// ── Extracción de texto de archivos subidos ────────────────────
app.post("/api/extract", upload.single("file"), async (req, res) => {
app.post("/api/extract", requireAuth, extractLimiter, upload.single("file"), async (req, res) => {
try {
if (!req.file) return res.status(400).json({ error: "No se recibió archivo." });
const name = req.file.originalname.toLowerCase();
@@ -72,11 +154,11 @@ app.post("/api/extract", upload.single("file"), async (req, res) => {
});
// ── CRUD Reels ─────────────────────────────────────────────────
app.get("/api/reels", async (_req, res) => {
app.get("/api/reels", requireAuth, async (_req, res) => {
const { rows } = await pool.query("SELECT * FROM reels ORDER BY created_at DESC");
res.json(rows);
});
app.post("/api/reels", async (req, res) => {
app.post("/api/reels", requireAuth, async (req, res) => {
const { titulo, hook = "", estructura = "", tono = "", formato = "", notas = "" } = req.body;
if (!titulo?.trim()) return res.status(400).json({ error: "El título es obligatorio." });
const id = uid();
@@ -87,17 +169,17 @@ app.post("/api/reels", async (req, res) => {
);
res.status(201).json(rows[0]);
});
app.delete("/api/reels/:id", async (req, res) => {
app.delete("/api/reels/:id", requireAuth, async (req, res) => {
await pool.query("DELETE FROM reels WHERE id=$1", [req.params.id]);
res.json({ deleted: req.params.id });
});
// ── CRUD Expedientes ───────────────────────────────────────────
app.get("/api/expedientes", async (_req, res) => {
app.get("/api/expedientes", requireAuth, async (_req, res) => {
const { rows } = await pool.query("SELECT * FROM expedientes ORDER BY created_at DESC");
res.json(rows);
});
app.post("/api/expedientes", async (req, res) => {
app.post("/api/expedientes", requireAuth, async (req, res) => {
const { titulo, contenido } = req.body;
if (!titulo?.trim() || !contenido?.trim())
return res.status(400).json({ error: "Título y contenido son obligatorios." });
@@ -108,13 +190,13 @@ app.post("/api/expedientes", async (req, res) => {
);
res.status(201).json(rows[0]);
});
app.delete("/api/expedientes/:id", async (req, res) => {
app.delete("/api/expedientes/:id", requireAuth, async (req, res) => {
await pool.query("DELETE FROM expedientes WHERE id=$1", [req.params.id]);
res.json({ deleted: req.params.id });
});
// ── Generación del brief (Anthropic) ───────────────────────────
app.post("/api/generar", async (req, res) => {
app.post("/api/generar", requireAuth, generateLimiter, async (req, res) => {
try {
const { reelId, expedienteId } = req.body;
const reelR = await pool.query("SELECT * FROM reels WHERE id=$1", [reelId]);
+10 -1
View File
@@ -8,15 +8,24 @@ services:
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
- ANTHROPIC_MODEL=${ANTHROPIC_MODEL:-claude-opus-4-20250514}
- MAX_TOKENS=${MAX_TOKENS:-4000}
- ADMIN_PASSWORD=${ADMIN_PASSWORD}
- SESSION_SECRET=${SESSION_SECRET}
- PORT=3001
expose:
- "3001"
healthcheck:
test: ["CMD", "node", "-e", "fetch('http://localhost:3001/api/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]
interval: 30s
timeout: 5s
retries: 3
start_period: 60s
frontend:
build: ./frontend
restart: unless-stopped
depends_on:
- backend
backend:
condition: service_healthy
environment:
# Coolify genera el dominio y el certificado a partir de esta variable.
# Déjala así: en el panel asignas reels.collinasystems.com.mx al servicio.
+116 -6
View File
@@ -1,13 +1,24 @@
import React, { useState, useEffect, useCallback, useRef } from "react";
import { Film, FileText, Sparkles, Trash2, Plus, Copy, Check, Loader2, Database, ChevronRight, UploadCloud, FileWarning } from "lucide-react";
import { Film, FileText, Sparkles, Trash2, Plus, Copy, Check, Loader2, Database, ChevronRight, UploadCloud, FileWarning, Lock, LogOut } from "lucide-react";
const API = import.meta.env.VITE_API_BASE || "/api";
const TOKEN_KEY = "adapter_token";
function getToken() { return localStorage.getItem(TOKEN_KEY); }
function setStoredToken(t) { if (t) localStorage.setItem(TOKEN_KEY, t); else localStorage.removeItem(TOKEN_KEY); }
async function api(path, opts = {}) {
const res = await fetch(API + path, {
headers: opts.body && !(opts.body instanceof FormData) ? { "Content-Type": "application/json" } : undefined,
...opts,
});
const headers = { ...(opts.headers || {}) };
if (opts.body && !(opts.body instanceof FormData) && !headers["Content-Type"]) {
headers["Content-Type"] = "application/json";
}
const t = getToken();
if (t) headers["Authorization"] = "Bearer " + t;
const res = await fetch(API + path, { ...opts, headers });
if (res.status === 401) {
setStoredToken(null);
window.dispatchEvent(new Event("adapter-unauth"));
}
if (!res.ok) {
let msg = "Error " + res.status;
try { msg = (await res.json()).error || msg; } catch {}
@@ -77,7 +88,102 @@ function DropBox({ onText, hint }) {
);
}
function Login({ onLogged }) {
const [pwd, setPwd] = useState("");
const [busy, setBusy] = useState(false);
const [err, setErr] = useState("");
const inputRef = useRef(null);
useEffect(() => { inputRef.current?.focus(); }, []);
const submit = async (e) => {
e?.preventDefault();
if (!pwd) return;
setBusy(true); setErr("");
try {
const { token } = await api("/login", { method: "POST", body: JSON.stringify({ password: pwd }) });
if (!token) throw new Error("Respuesta del servidor sin token.");
setStoredToken(token);
onLogged();
} catch (e2) {
setErr(e2.message);
setPwd("");
inputRef.current?.focus();
} finally { setBusy(false); }
};
return (
<div style={rootStyle}>
<style>{GLOBAL_CSS}</style>
<div style={{ position: "fixed", inset: 0, zIndex: 0, ...bgBlobs }} />
<div style={{ position: "relative", zIndex: 1, minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", padding: 24 }}>
<form onSubmit={submit} style={{ ...glassCard, width: "100%", maxWidth: 380, padding: 28 }}>
<div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
<Lock size={18} color="var(--accent)" />
<h1 style={{ ...h1Style, fontSize: 22 }}>Acceso</h1>
</div>
<p style={{ margin: "0 0 18px", color: "var(--muted)", fontSize: 13 }}>
Adaptador <span style={{ color: "var(--accent)" }}>Reels × Expedientes</span> · Collina Systems
</p>
<label style={{ display: "block", marginBottom: 14 }}>
<span style={lblStyle}>Contraseña</span>
<input
ref={inputRef}
type="password"
value={pwd}
onChange={(e) => setPwd(e.target.value)}
autoComplete="current-password"
disabled={busy}
style={inputStyle}
/>
</label>
<button type="submit" disabled={busy || !pwd} style={genBtn(busy || !pwd)}>
{busy ? <><Loader2 size={17} style={{ animation: "spin 1s linear infinite" }} /> Verificando…</>
: <><Lock size={16} /> Entrar</>}
</button>
{err && <p style={{ color: "var(--accent2)", fontSize: 13, marginTop: 12, marginBottom: 0 }}>{err}</p>}
</form>
</div>
</div>
);
}
export default function App() {
const [authed, setAuthed] = useState(() => !!getToken());
const [authChecking, setAuthChecking] = useState(() => !!getToken());
useEffect(() => {
const onUnauth = () => { setAuthed(false); setAuthChecking(false); };
window.addEventListener("adapter-unauth", onUnauth);
return () => window.removeEventListener("adapter-unauth", onUnauth);
}, []);
useEffect(() => {
if (!getToken()) { setAuthChecking(false); return; }
api("/session")
.then(() => { setAuthed(true); setAuthChecking(false); })
.catch(() => { setAuthed(false); setAuthChecking(false); });
}, []);
const logout = () => { setStoredToken(null); setAuthed(false); };
if (authChecking) {
return (
<div style={rootStyle}>
<style>{GLOBAL_CSS}</style>
<div style={{ position: "fixed", inset: 0, zIndex: 0, ...bgBlobs }} />
<div style={{ position: "relative", zIndex: 1, minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--muted)", fontSize: 13 }}>
<Loader2 size={18} style={{ animation: "spin 1s linear infinite", marginRight: 8 }} /> Verificando sesión…
</div>
</div>
);
}
if (!authed) return <Login onLogged={() => setAuthed(true)} />;
return <MainApp onLogout={logout} />;
}
function MainApp({ onLogout }) {
const [tab, setTab] = useState("generar");
const [reels, setReels] = useState([]);
const [exps, setExps] = useState([]);
@@ -152,7 +258,10 @@ export default function App() {
Genera un brief de producción con el guion adaptado al estilo del creador.
</p>
</div>
<div style={pill}><Database size={13} /> {loaded ? `${reels.length} reels · ${exps.length} exp.` : "cargando…"}</div>
<div style={{ display: "flex", alignItems: "center", gap: 10 }}>
<div style={pill}><Database size={13} /> {loaded ? `${reels.length} reels · ${exps.length} exp.` : "cargando…"}</div>
<button onClick={onLogout} title="Cerrar sesión" style={logoutBtn}><LogOut size={14} /> Salir</button>
</div>
</header>
{loadErr && <div style={{ ...glassCard, margin: "16px 24px 0", borderColor: "var(--accent2)", color: "var(--accent2)", fontSize: 13 }}>{loadErr}</div>}
@@ -303,6 +412,7 @@ const genBtn = (b) => ({ width: "100%", padding: "14px", borderRadius: 12, borde
const copyBtn = { display: "flex", alignItems: "center", gap: 6, padding: "7px 12px", background: "rgba(255,255,255,.08)", border: "1px solid rgba(255,255,255,.16)", borderRadius: 9, color: "var(--ink)", fontSize: 13 };
const addBtn = { width: "100%", marginTop: 6, padding: "12px", borderRadius: 11, border: "none", background: "var(--accent)", color: "#13123a", fontWeight: 700, fontSize: 14, display: "flex", alignItems: "center", justifyContent: "center", gap: 7 };
const delBtn = { flexShrink: 0, width: 34, height: 34, borderRadius: 9, border: "1px solid rgba(255,255,255,.16)", background: "rgba(255,255,255,.06)", color: "var(--accent2)", display: "flex", alignItems: "center", justifyContent: "center" };
const logoutBtn = { display: "flex", alignItems: "center", gap: 6, padding: "6px 12px", fontSize: 12, color: "var(--muted)", border: "1px solid rgba(255,255,255,.16)", background: "rgba(255,255,255,.06)", backdropFilter: "blur(10px)", borderRadius: 20 };
const selItem = (a) => ({ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, textAlign: "left", padding: "10px 12px", borderRadius: 10, background: a ? "rgba(156,255,143,.12)" : "rgba(255,255,255,.05)", border: `1px solid ${a ? "var(--accent)" : "rgba(255,255,255,.14)"}`, color: "var(--ink)", fontSize: 13.5, fontWeight: 500 });
const GLOBAL_CSS = `@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Syne:wght@700;800&display=swap');
*::-webkit-scrollbar{width:8px;height:8px}*::-webkit-scrollbar-thumb{background:rgba(255,255,255,.18);border-radius:8px}
+7
View File
@@ -4,4 +4,11 @@ import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
build: { outDir: "dist" },
// Proxy SOLO para `vite dev` (puerto 5173 por defecto). En producción nginx
// del propio frontend hace de proxy; este bloque no afecta a `vite build`.
server: {
proxy: {
"/api": { target: "http://localhost:3001", changeOrigin: true },
},
},
});