Fastify rechazaba por defecto un POST sin body con Content-Type: application/json (400 FST_ERR_CTP_EMPTY_JSON_BODY), aunque es una petición válida. Eso hacía frágil al servidor ante cualquier cliente que declarara JSON sin mandar cuerpo: el frontend lo hacía en aprobar/baja/rechazar/logout, pero también le pasaría a scripts o apps futuras. Se reemplaza el parser de application/json para tratar el cuerpo vacío como "sin body" (undefined) en vez de error; un JSON malformado sigue dando 400. El parser es incondicional: no depende de NODE_ENV ni de ninguna env var, así que se comporta igual en dev y en producción. Verificado (contenedor NODE_ENV=production): POST sin body + Content-Type JSON → 200; JSON malformado → 400; body válido → 201.
158 lines
5.4 KiB
JavaScript
158 lines
5.4 KiB
JavaScript
import Fastify from 'fastify';
|
|
import cookie from '@fastify/cookie';
|
|
import cors from '@fastify/cors';
|
|
import rateLimit from '@fastify/rate-limit';
|
|
import { config } from './config.js';
|
|
import { db } from './db/client.js';
|
|
import { runMigrations, seedSupervisora } from './db/migrate.js';
|
|
import authRoutes from './routes/auth.js';
|
|
import becariosRoutes from './routes/becarios.js';
|
|
import dispositivosRoutes from './routes/dispositivos.js';
|
|
import jornadasRoutes from './routes/jornadas.js';
|
|
import ajustesRoutes from './routes/ajustes.js';
|
|
import becarioAuthRoutes from './routes/becario-auth.js';
|
|
import becarioPortalRoutes from './routes/becario-portal.js';
|
|
import entradaRoutes from './routes/entrada.js';
|
|
import checadasRoutes from './routes/checadas.js';
|
|
import configRoutes from './routes/config.js';
|
|
import solicitudesRoutes from './routes/solicitudes.js';
|
|
import mantenimientoRoutes from './routes/mantenimiento.js';
|
|
import { startTareas } from './services/tareas.js';
|
|
|
|
const fastify = Fastify({
|
|
// node vive detrás del nginx del propio container (y de Traefik en prod):
|
|
// sin esto req.ip sería siempre 127.0.0.1 y el rate limit del login
|
|
// compartiría un solo bucket para todos los clientes.
|
|
trustProxy: true,
|
|
logger: {
|
|
level: config.logLevel,
|
|
...(config.nodeEnv === 'development' && {
|
|
transport: {
|
|
target: 'pino-pretty',
|
|
options: {
|
|
translateTime: 'HH:MM:ss.l',
|
|
ignore: 'pid,hostname',
|
|
singleLine: false,
|
|
},
|
|
},
|
|
}),
|
|
},
|
|
});
|
|
|
|
// Fastify rechaza por defecto un cuerpo vacío cuando el Content-Type es JSON
|
|
// (FST_ERR_CTP_EMPTY_JSON_BODY → 400). Pero un POST sin body con ese header es
|
|
// una petición válida —aprobar/baja/rechazar/logout, y cualquier script o app
|
|
// futura— así que reemplazamos el parser de JSON para tratar el cuerpo vacío
|
|
// como "sin body" (undefined) en lugar de un error. Un JSON malformado sigue
|
|
// dando 400, igual que el parser por defecto. No depende de ninguna env var.
|
|
fastify.removeContentTypeParser('application/json');
|
|
fastify.addContentTypeParser(
|
|
'application/json',
|
|
{ parseAs: 'string' },
|
|
(req, body, done) => {
|
|
if (body === '' || body == null) return done(null, undefined);
|
|
try {
|
|
done(null, JSON.parse(body));
|
|
} catch (err) {
|
|
err.statusCode = 400;
|
|
done(err);
|
|
}
|
|
},
|
|
);
|
|
|
|
// ¿origen de localhost o de una IP privada (LAN)? Solo se usa en modo dev.
|
|
function esOrigenLanDev(origin) {
|
|
try {
|
|
const h = new URL(origin).hostname;
|
|
return (
|
|
h === 'localhost' ||
|
|
/^127\./.test(h) ||
|
|
/^10\./.test(h) ||
|
|
/^192\.168\./.test(h) ||
|
|
/^172\.(1[6-9]|2\d|3[01])\./.test(h)
|
|
);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
await fastify.register(cors, {
|
|
origin: (origin, cb) => {
|
|
if (!origin) return cb(null, true);
|
|
if (config.allowedOrigins.includes(origin)) return cb(null, true);
|
|
// Modo dev/LAN (COOKIE_INSECURE=true → cookieSecure=false): permite probar
|
|
// desde un celular en la red local sin listar cada IP. En producción
|
|
// (COOKIE_INSECURE ausente) esto queda apagado y solo vale ALLOWED_ORIGINS.
|
|
if (!config.session.cookieSecure && esOrigenLanDev(origin)) return cb(null, true);
|
|
cb(new Error(`Origen no permitido por CORS: ${origin}`), false);
|
|
},
|
|
methods: ['GET', 'POST', 'PATCH', 'DELETE'],
|
|
credentials: true,
|
|
});
|
|
|
|
// Cookies firmadas con HMAC (sesión de supervisora, §6)
|
|
await fastify.register(cookie, { secret: config.session.secret });
|
|
|
|
// global: false → solo limita rutas que lo pidan en su config (login)
|
|
await fastify.register(rateLimit, { global: false });
|
|
|
|
fastify.get('/api/health', async () => ({
|
|
status: 'ok',
|
|
timestamp: new Date().toISOString(),
|
|
uptime: process.uptime(),
|
|
}));
|
|
|
|
let tareasInterval = null;
|
|
|
|
const shutdown = async (signal) => {
|
|
fastify.log.info({ signal }, 'Graceful shutdown iniciado');
|
|
try {
|
|
if (tareasInterval) clearInterval(tareasInterval);
|
|
await fastify.close();
|
|
await db.end();
|
|
process.exit(0);
|
|
} catch (err) {
|
|
fastify.log.error(err, 'Error durante shutdown');
|
|
process.exit(1);
|
|
}
|
|
};
|
|
|
|
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
|
|
const dbOk = await db.testConnection();
|
|
if (!dbOk) {
|
|
fastify.log.fatal('DB connection failed — abortando arranque');
|
|
process.exit(1);
|
|
}
|
|
fastify.log.info('DB connection OK');
|
|
|
|
await runMigrations(db, fastify.log);
|
|
await seedSupervisora(db, fastify.log);
|
|
|
|
fastify.decorate('db', db);
|
|
|
|
await fastify.register(authRoutes, { prefix: '/api' });
|
|
await fastify.register(becariosRoutes, { prefix: '/api' });
|
|
await fastify.register(dispositivosRoutes, { prefix: '/api' });
|
|
await fastify.register(jornadasRoutes, { prefix: '/api' });
|
|
await fastify.register(ajustesRoutes, { prefix: '/api' });
|
|
await fastify.register(becarioAuthRoutes, { prefix: '/api' });
|
|
await fastify.register(becarioPortalRoutes, { prefix: '/api' });
|
|
await fastify.register(entradaRoutes, { prefix: '/e' });
|
|
await fastify.register(checadasRoutes, { prefix: '/api' });
|
|
await fastify.register(configRoutes, { prefix: '/api' });
|
|
await fastify.register(solicitudesRoutes, { prefix: '/api' });
|
|
await fastify.register(mantenimientoRoutes, { prefix: '/api' });
|
|
|
|
// Tareas internas: auto-cierre a revisión + limpieza de tokens (§6, §11.8).
|
|
tareasInterval = startTareas(db, fastify.log);
|
|
|
|
try {
|
|
const address = await fastify.listen({ port: config.apiPort, host: config.apiHost });
|
|
fastify.log.info(`Taboada API lista en ${address}`);
|
|
} catch (err) {
|
|
fastify.log.error(err);
|
|
process.exit(1);
|
|
}
|