Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import cartRoutes from "./modules/users/cart/cart.routes.js";
import { orderRouter, userOrderRouter } from "./modules/users/orders/order.routes.js";

import { errorHandler } from "./middlewares/errorHandler.js";
import { securityResponseLogger } from "./middlewares/security-log.middleware.js";
import { NotFoundError } from "./lib/errors.js";

import { setupSwagger } from "./config/swagger.config.js";
Expand Down Expand Up @@ -76,6 +77,7 @@ app.use((req, res, next) => {
app.use(morgan('dev'));
app.use(express.json());
app.use(cookieParser());
app.use(securityResponseLogger);

const allowedOrigins = process.env.CORS_ORIGIN
? process.env.CORS_ORIGIN.split(',').map(o => o.trim())
Expand Down
147 changes: 147 additions & 0 deletions src/lib/security-logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
const SENSITIVE_KEY_NAMES = [
"password",
"password_hash",
"token",
"user_token",
"authorization",
"cookie",
"cookies",
"secret",
"jwt",
"refresh_token",
"access_token",
];

const JWT_PATTERN = /eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g;
const BEARER_PATTERN = /Bearer\s+\S+/gi;
const CONTROL_CHARS_PATTERN = /[\u0000-\u001F\u007F]/g;
const MAX_LOG_LINE_LENGTH = 8192;

/**
* Normaliza nombres de clave (camelCase, kebab-case) a snake_case en minúsculas.
*/
export function normalizeKey(key) {
if (typeof key !== "string") return "";
return key
.replaceAll(/([a-z0-9])([A-Z])/g, "$1_$2")
.replaceAll("-", "_")
.toLowerCase();
}

const SENSITIVE_KEYS = new Set(SENSITIVE_KEY_NAMES.map(normalizeKey));

function isSensitiveKey(key) {
return SENSITIVE_KEYS.has(normalizeKey(key));
}

function sanitizeLogString(str) {
return str
.replaceAll(CONTROL_CHARS_PATTERN, "")
.replaceAll(JWT_PATTERN, "[REDACTED_JWT]")
.replaceAll(BEARER_PATTERN, "Bearer [REDACTED]");
}

/**
* Elimina datos sensibles antes de escribir en logs (tokens, passwords, etc.).
*/
export function sanitizeForLog(value, depth = 0) {
if (depth > 6) return "[MaxDepth]";
if (value == null) return value;

if (typeof value === "string") {
return sanitizeLogString(value);
}

if (typeof value === "number" || typeof value === "boolean") {
return value;
}

if (Array.isArray(value)) {
return value.map((item) => sanitizeForLog(item, depth + 1));
}

if (typeof value === "object") {
const sanitized = {};
for (const [key, val] of Object.entries(value)) {
if (isSensitiveKey(key)) {
sanitized[key] = "[REDACTED]";
} else {
sanitized[key] = sanitizeForLog(val, depth + 1);
}
}
return sanitized;
}

return String(value);
}

function stripReservedDetailKeys(details) {
if (details == null || typeof details !== "object" || Array.isArray(details)) {
return {};
}

const safe = { ...details };
delete safe.event;
delete safe.timestamp;
return safe;
}

/**
* Construye la línea JSON del evento tras sanitizar y validar el contenido.
*/
export function buildSecurityLogLine(eventType, details = {}) {
const payload = sanitizeForLog({
...stripReservedDetailKeys(details),
timestamp: new Date().toISOString(),
event: eventType,
});

return JSON.stringify(payload);
}

function isValidSecurityLogLine(line) {
if (typeof line !== "string" || line.length === 0 || line.length > MAX_LOG_LINE_LENGTH) {
return false;
}

if (CONTROL_CHARS_PATTERN.test(line)) {
return false;
}

try {
JSON.parse(line);
return true;
} catch {
return false;
}
}

function writeSecurityLogLine(line) {
process.stdout.write(`[SECURITY] ${line}\n`);
}

/**
* Registra un evento de seguridad en stdout (JSON). Nunca incluir passwords ni tokens.
* No lanza errores: fallos de logging no afectan el flujo de negocio.
*/
export function logSecurityEvent(eventType, details = {}) {
try {
if (typeof eventType !== "string" || eventType.length === 0) {
return;
}

const line = buildSecurityLogLine(eventType, details);
if (!isValidSecurityLogLine(line)) {
console.error("[SECURITY] Discarded invalid log line for event:", eventType);
return;
}

writeSecurityLogLine(line);
} catch (err) {
console.error(
"[SECURITY] Failed to log security event:",
eventType,
err?.message ?? err
);
}
}
23 changes: 23 additions & 0 deletions src/middlewares/security-log.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { logSecurityEvent } from "../lib/security-logger.js";

/**
* Registra respuestas HTTP 403 al finalizar la petición (cubre AppError y errores legacy en controllers).
*/
export const securityResponseLogger = (req, res, next) => {
res.on("finish", () => {
if (res.statusCode !== 403) return;

try {
logSecurityEvent("FORBIDDEN", {
method: req.method,
path: req.originalUrl || req.path,
userId: req.user?.id_user ?? null,
role: req.user?.role ?? null,
});
} catch (err) {
console.error("[SECURITY] Failed to log FORBIDDEN event:", err?.message ?? err);
}
});

next();
};
4 changes: 4 additions & 0 deletions src/middlewares/validate.middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@ export const validate =
return;
}

// Contrato por sección: query → req.validated; params → mutar req.params
// (misma referencia, merge de campos validados); body/otros → req[section].
if (section === "query") {
req.validated = result.data;
} else if (section === "params") {
Object.assign(req.params, result.data);
} else {
req[section] = result.data;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//delivery-assignments.service.js
import { prisma } from '../../../lib/prisma.js';
import { logSecurityEvent } from '../../../lib/security-logger.js';
import {
activePendingAssignmentWhere,
closePendingAndReassign,
Expand Down Expand Up @@ -90,6 +91,14 @@ export const createAssignmentService = async (data) => {
});
});

logSecurityEvent("ASSIGNMENT_STATUS_CHANGED", {
assignmentId: newDeliveryAssignment.id_delivery_assignment,
orderId: fk_order,
deliveryId: newDeliveryAssignment.fk_delivery,
previousStatus: null,
newStatus: newDeliveryAssignment.assignment_status ?? "PENDING",
});

return newDeliveryAssignment;
} catch (error) {
if (error?.code === 'P2002') {
Expand Down Expand Up @@ -257,7 +266,7 @@ export const getAcceptedAssignmentService = async (id_order) => {
export const completeAssignmentService = async (id_delivery_assignment, id_user) => {
const assignment = await prisma.deliveryAssignments.findUnique({
where: { id_delivery_assignment },
include: { delivery: true }
include: { delivery: true, order: true }
});

if (!assignment) {
Expand Down Expand Up @@ -286,6 +295,24 @@ export const completeAssignmentService = async (id_delivery_assignment, id_user)
return updatedAssignment;
});

logSecurityEvent("ASSIGNMENT_STATUS_CHANGED", {
assignmentId: id_delivery_assignment,
orderId: assignment.fk_order,
deliveryId: assignment.fk_delivery,
previousStatus: "ACCEPTED",
newStatus: "DELIVERED",
actorUserId: id_user,
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

logSecurityEvent("ORDER_STATUS_CHANGED", {
orderId: assignment.fk_order,
previousStatus: assignment.order?.order_status ?? null,
newStatus: "DELIVERED",
actorUserId: id_user,
actorRole: "DELIVERY",
source: "assignment_complete",
});

return updated;
};

Expand All @@ -295,7 +322,9 @@ export const respondToAssignmentService = async (orderId, userId, action) => {
throw { status: 400, message: "ID de orden inválido" };
}

return prisma.$transaction(async (tx) => {
const pendingAuditLogs = [];

const result = await prisma.$transaction(async (tx) => {
await expireStalePendingAssignments({ fk_order: parsedOrderId }, tx);

const assignment = await tx.deliveryAssignments.findFirst({
Expand Down Expand Up @@ -334,26 +363,84 @@ export const respondToAssignmentService = async (orderId, userId, action) => {
data: { order_status: "SHIPPED", delivery_unavailable: false }
});

pendingAuditLogs.push(
{
event: "ASSIGNMENT_STATUS_CHANGED",
details: {
assignmentId: assignment.id_delivery_assignment,
orderId: parsedOrderId,
deliveryId: assignment.fk_delivery,
previousStatus: "PENDING",
newStatus: "ACCEPTED",
actorUserId: userId,
},
},
{
event: "ORDER_STATUS_CHANGED",
details: {
orderId: parsedOrderId,
previousStatus: assignment.order?.order_status ?? null,
newStatus: "SHIPPED",
actorUserId: userId,
actorRole: "DELIVERY",
source: "assignment_accept",
},
}
);

return updated;
}

const outcome = await closePendingAndReassign(tx, assignment, "REJECTED", { reason: "reject" });

if (outcome.reassigned) {
pendingAuditLogs.push({
event: "ASSIGNMENT_STATUS_CHANGED",
details: {
assignmentId: assignment.id_delivery_assignment,
orderId: parsedOrderId,
deliveryId: assignment.fk_delivery,
previousStatus: "PENDING",
newStatus: "REJECTED",
actorUserId: userId,
reassigned: true,
newAssignmentId: outcome.assignment?.id_delivery_assignment ?? null,
},
});

return {
...outcome.assignment,
reassigned: true,
delivery_unavailable: false,
};
}

pendingAuditLogs.push({
event: "ASSIGNMENT_STATUS_CHANGED",
details: {
assignmentId: assignment.id_delivery_assignment,
orderId: parsedOrderId,
deliveryId: assignment.fk_delivery,
previousStatus: "PENDING",
newStatus: "REJECTED",
actorUserId: userId,
reassigned: false,
},
});

return {
assignment_status: "REJECTED",
fk_order: parsedOrderId,
reassigned: false,
delivery_unavailable: true,
};
});

for (const { event, details } of pendingAuditLogs) {
logSecurityEvent(event, details);
}

return result;
};

export const getDeliveryOrderHistoryService = async (deliveryId, authenticatedUserId, filters, pagination) => {
Expand Down
14 changes: 7 additions & 7 deletions src/modules/delivery/delivery/delivery.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const registerDelivery = async (req, res) => {
return res.status(400).json({
error: {
code: 400,
message: error.issues[0]?.message ?? "Datos inválidos",
message: "Datos inválidos",
details: error.issues,
},
});
Expand Down Expand Up @@ -91,9 +91,9 @@ export const updateDeliveryStatus = async (req, res) => {
return res.status(400).json({
error: {
code: 400,
message: error.issues[0].message,
details: error.issues
}
message: "Datos inválidos",
details: error.issues,
},
});
}
return res.status(error.status || 500).json({
Expand Down Expand Up @@ -172,9 +172,9 @@ export const updateDeliveryProfile = async (req, res) => {
return res.status(400).json({
error: {
code: 400,
message: error.issues[0].message,
details: error.issues
}
message: "Datos inválidos",
details: error.issues,
},
});
}
return res.status(error.status || 500).json({
Expand Down
2 changes: 1 addition & 1 deletion src/modules/delivery/delivery/delivery.validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { z } from 'zod';
import { DELIVERY_PHONE_MESSAGE, DELIVERY_PHONE_REGEX } from '../../../lib/phone.js';

const vehicleTypeSchema = z.enum(["CAR", "MOTORCYCLE", "BICYCLE", "ON_FOOT"], {
errorMap: () => ({ message: "vehicleType debe ser CAR, MOTORCYCLE, BICYCLE o ON_FOOT" })
message: "vehicleType debe ser CAR, MOTORCYCLE, BICYCLE o ON_FOOT",
});

const deliveryPhoneSchema = z
Expand Down
Loading
Loading