refactor: optimize configuration and tool implementations
- Standardized error handling across tool implementations - Improved return type consistency for tool execution results - Simplified configuration parsing and type definitions - Enhanced type safety for various configuration schemas - Cleaned up and normalized tool response structures - Updated SSE and event subscription tool implementations
This commit is contained in:
@@ -1,163 +1,203 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { validateRequest, sanitizeInput, errorHandler } from '../index';
|
||||
import { TokenManager } from '../../security/index';
|
||||
import { jest } from '@jest/globals';
|
||||
import { Request, Response } from "express";
|
||||
import { validateRequest, sanitizeInput, errorHandler } from "../index";
|
||||
import { TokenManager } from "../../security/index";
|
||||
import { jest } from "@jest/globals";
|
||||
|
||||
const TEST_SECRET = 'test-secret-that-is-long-enough-for-testing-purposes';
|
||||
const TEST_SECRET = "test-secret-that-is-long-enough-for-testing-purposes";
|
||||
|
||||
describe('Security Middleware', () => {
|
||||
let mockRequest: Partial<Request>;
|
||||
let mockResponse: Partial<Response>;
|
||||
let nextFunction: jest.Mock;
|
||||
describe("Security Middleware", () => {
|
||||
let mockRequest: Partial<Request>;
|
||||
let mockResponse: Partial<Response>;
|
||||
let nextFunction: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
process.env.JWT_SECRET = TEST_SECRET;
|
||||
mockRequest = {
|
||||
method: 'POST',
|
||||
headers: {},
|
||||
body: {},
|
||||
ip: '127.0.0.1'
|
||||
};
|
||||
beforeEach(() => {
|
||||
process.env.JWT_SECRET = TEST_SECRET;
|
||||
mockRequest = {
|
||||
method: "POST",
|
||||
headers: {},
|
||||
body: {},
|
||||
ip: "127.0.0.1",
|
||||
};
|
||||
|
||||
const mockJson = jest.fn().mockReturnThis();
|
||||
const mockStatus = jest.fn().mockReturnThis();
|
||||
const mockSetHeader = jest.fn().mockReturnThis();
|
||||
const mockRemoveHeader = jest.fn().mockReturnThis();
|
||||
const mockJson = jest.fn().mockReturnThis();
|
||||
const mockStatus = jest.fn().mockReturnThis();
|
||||
const mockSetHeader = jest.fn().mockReturnThis();
|
||||
const mockRemoveHeader = jest.fn().mockReturnThis();
|
||||
|
||||
mockResponse = {
|
||||
status: mockStatus as any,
|
||||
json: mockJson as any,
|
||||
setHeader: mockSetHeader as any,
|
||||
removeHeader: mockRemoveHeader as any
|
||||
};
|
||||
nextFunction = jest.fn();
|
||||
mockResponse = {
|
||||
status: mockStatus as any,
|
||||
json: mockJson as any,
|
||||
setHeader: mockSetHeader as any,
|
||||
removeHeader: mockRemoveHeader as any,
|
||||
};
|
||||
nextFunction = jest.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.JWT_SECRET;
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("Request Validation", () => {
|
||||
it("should pass valid requests", () => {
|
||||
mockRequest.headers = {
|
||||
authorization: "Bearer valid-token",
|
||||
"content-type": "application/json",
|
||||
};
|
||||
jest
|
||||
.spyOn(TokenManager, "validateToken")
|
||||
.mockReturnValue({ valid: true });
|
||||
|
||||
validateRequest(
|
||||
mockRequest as Request,
|
||||
mockResponse as Response,
|
||||
nextFunction,
|
||||
);
|
||||
expect(nextFunction).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.JWT_SECRET;
|
||||
jest.clearAllMocks();
|
||||
it("should reject requests without authorization header", () => {
|
||||
validateRequest(
|
||||
mockRequest as Request,
|
||||
mockResponse as Response,
|
||||
nextFunction,
|
||||
);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(401);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
message: "Unauthorized",
|
||||
error: "Missing or invalid authorization header",
|
||||
timestamp: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
describe('Request Validation', () => {
|
||||
it('should pass valid requests', () => {
|
||||
mockRequest.headers = {
|
||||
'authorization': 'Bearer valid-token',
|
||||
'content-type': 'application/json'
|
||||
};
|
||||
jest.spyOn(TokenManager, 'validateToken').mockReturnValue({ valid: true });
|
||||
|
||||
validateRequest(mockRequest as Request, mockResponse as Response, nextFunction);
|
||||
expect(nextFunction).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should reject requests without authorization header', () => {
|
||||
validateRequest(mockRequest as Request, mockResponse as Response, nextFunction);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(401);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
error: 'Missing or invalid authorization header',
|
||||
timestamp: expect.any(String)
|
||||
});
|
||||
});
|
||||
|
||||
it('should reject requests with invalid authorization format', () => {
|
||||
mockRequest.headers = {
|
||||
'authorization': 'invalid-format',
|
||||
'content-type': 'application/json'
|
||||
};
|
||||
validateRequest(mockRequest as Request, mockResponse as Response, nextFunction);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(401);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
error: 'Missing or invalid authorization header',
|
||||
timestamp: expect.any(String)
|
||||
});
|
||||
});
|
||||
|
||||
it('should reject oversized requests', () => {
|
||||
mockRequest.headers = {
|
||||
'authorization': 'Bearer valid-token',
|
||||
'content-type': 'application/json',
|
||||
'content-length': '1048577' // 1MB + 1 byte
|
||||
};
|
||||
validateRequest(mockRequest as Request, mockResponse as Response, nextFunction);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(413);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
message: 'Payload Too Large',
|
||||
error: 'Request body must not exceed 1048576 bytes',
|
||||
timestamp: expect.any(String)
|
||||
});
|
||||
});
|
||||
it("should reject requests with invalid authorization format", () => {
|
||||
mockRequest.headers = {
|
||||
authorization: "invalid-format",
|
||||
"content-type": "application/json",
|
||||
};
|
||||
validateRequest(
|
||||
mockRequest as Request,
|
||||
mockResponse as Response,
|
||||
nextFunction,
|
||||
);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(401);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
message: "Unauthorized",
|
||||
error: "Missing or invalid authorization header",
|
||||
timestamp: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
describe('Input Sanitization', () => {
|
||||
it('should sanitize HTML in request body', () => {
|
||||
mockRequest.body = {
|
||||
text: 'Test <script>alert("xss")</script>',
|
||||
nested: {
|
||||
html: '<img src="x" onerror="alert(1)">World'
|
||||
}
|
||||
};
|
||||
sanitizeInput(mockRequest as Request, mockResponse as Response, nextFunction);
|
||||
expect(mockRequest.body.text).toBe('Test ');
|
||||
expect(mockRequest.body.nested.html).toBe('World');
|
||||
expect(nextFunction).toHaveBeenCalled();
|
||||
});
|
||||
it("should reject oversized requests", () => {
|
||||
mockRequest.headers = {
|
||||
authorization: "Bearer valid-token",
|
||||
"content-type": "application/json",
|
||||
"content-length": "1048577", // 1MB + 1 byte
|
||||
};
|
||||
validateRequest(
|
||||
mockRequest as Request,
|
||||
mockResponse as Response,
|
||||
nextFunction,
|
||||
);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(413);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
message: "Payload Too Large",
|
||||
error: "Request body must not exceed 1048576 bytes",
|
||||
timestamp: expect.any(String),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle non-object bodies', () => {
|
||||
mockRequest.body = '<p>text</p>';
|
||||
sanitizeInput(mockRequest as Request, mockResponse as Response, nextFunction);
|
||||
expect(mockRequest.body).toBe('text');
|
||||
expect(nextFunction).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should preserve non-string values', () => {
|
||||
mockRequest.body = {
|
||||
number: 123,
|
||||
boolean: true,
|
||||
array: [1, 2, 3],
|
||||
nested: { value: 456 }
|
||||
};
|
||||
sanitizeInput(mockRequest as Request, mockResponse as Response, nextFunction);
|
||||
expect(mockRequest.body).toEqual({
|
||||
number: 123,
|
||||
boolean: true,
|
||||
array: [1, 2, 3],
|
||||
nested: { value: 456 }
|
||||
});
|
||||
expect(nextFunction).toHaveBeenCalled();
|
||||
});
|
||||
describe("Input Sanitization", () => {
|
||||
it("should sanitize HTML in request body", () => {
|
||||
mockRequest.body = {
|
||||
text: 'Test <script>alert("xss")</script>',
|
||||
nested: {
|
||||
html: '<img src="x" onerror="alert(1)">World',
|
||||
},
|
||||
};
|
||||
sanitizeInput(
|
||||
mockRequest as Request,
|
||||
mockResponse as Response,
|
||||
nextFunction,
|
||||
);
|
||||
expect(mockRequest.body.text).toBe("Test ");
|
||||
expect(mockRequest.body.nested.html).toBe("World");
|
||||
expect(nextFunction).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('Error Handler', () => {
|
||||
it('should handle errors in production mode', () => {
|
||||
process.env.NODE_ENV = 'production';
|
||||
const error = new Error('Test error');
|
||||
errorHandler(error, mockRequest as Request, mockResponse as Response, nextFunction);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(500);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
message: 'Internal Server Error',
|
||||
error: 'An unexpected error occurred',
|
||||
timestamp: expect.any(String)
|
||||
});
|
||||
});
|
||||
|
||||
it('should include error details in development mode', () => {
|
||||
process.env.NODE_ENV = 'development';
|
||||
const error = new Error('Test error');
|
||||
errorHandler(error, mockRequest as Request, mockResponse as Response, nextFunction);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(500);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
message: 'Internal Server Error',
|
||||
error: 'Test error',
|
||||
stack: expect.any(String),
|
||||
timestamp: expect.any(String)
|
||||
});
|
||||
});
|
||||
it("should handle non-object bodies", () => {
|
||||
mockRequest.body = "<p>text</p>";
|
||||
sanitizeInput(
|
||||
mockRequest as Request,
|
||||
mockResponse as Response,
|
||||
nextFunction,
|
||||
);
|
||||
expect(mockRequest.body).toBe("text");
|
||||
expect(nextFunction).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("should preserve non-string values", () => {
|
||||
mockRequest.body = {
|
||||
number: 123,
|
||||
boolean: true,
|
||||
array: [1, 2, 3],
|
||||
nested: { value: 456 },
|
||||
};
|
||||
sanitizeInput(
|
||||
mockRequest as Request,
|
||||
mockResponse as Response,
|
||||
nextFunction,
|
||||
);
|
||||
expect(mockRequest.body).toEqual({
|
||||
number: 123,
|
||||
boolean: true,
|
||||
array: [1, 2, 3],
|
||||
nested: { value: 456 },
|
||||
});
|
||||
expect(nextFunction).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Error Handler", () => {
|
||||
it("should handle errors in production mode", () => {
|
||||
process.env.NODE_ENV = "production";
|
||||
const error = new Error("Test error");
|
||||
errorHandler(
|
||||
error,
|
||||
mockRequest as Request,
|
||||
mockResponse as Response,
|
||||
nextFunction,
|
||||
);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(500);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
message: "Internal Server Error",
|
||||
error: "An unexpected error occurred",
|
||||
timestamp: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
it("should include error details in development mode", () => {
|
||||
process.env.NODE_ENV = "development";
|
||||
const error = new Error("Test error");
|
||||
errorHandler(
|
||||
error,
|
||||
mockRequest as Request,
|
||||
mockResponse as Response,
|
||||
nextFunction,
|
||||
);
|
||||
expect(mockResponse.status).toHaveBeenCalledWith(500);
|
||||
expect(mockResponse.json).toHaveBeenCalledWith({
|
||||
success: false,
|
||||
message: "Internal Server Error",
|
||||
error: "Test error",
|
||||
stack: expect.any(String),
|
||||
timestamp: expect.any(String),
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,256 +1,294 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { HASS_CONFIG, RATE_LIMIT_CONFIG } from '../config/index.js';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import { TokenManager } from '../security/index.js';
|
||||
import sanitizeHtml from 'sanitize-html';
|
||||
import helmet from 'helmet';
|
||||
import { SECURITY_CONFIG } from '../config/security.config.js';
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { HASS_CONFIG, RATE_LIMIT_CONFIG } from "../config/index.js";
|
||||
import rateLimit from "express-rate-limit";
|
||||
import { TokenManager } from "../security/index.js";
|
||||
import sanitizeHtml from "sanitize-html";
|
||||
import helmet from "helmet";
|
||||
import { SECURITY_CONFIG } from "../config/security.config.js";
|
||||
|
||||
// Rate limiter middleware with enhanced configuration
|
||||
export const rateLimiter = rateLimit({
|
||||
windowMs: SECURITY_CONFIG.RATE_LIMIT_WINDOW,
|
||||
max: SECURITY_CONFIG.RATE_LIMIT_MAX_REQUESTS,
|
||||
message: {
|
||||
success: false,
|
||||
message: 'Too Many Requests',
|
||||
error: 'Rate limit exceeded. Please try again later.',
|
||||
timestamp: new Date().toISOString()
|
||||
}
|
||||
windowMs: SECURITY_CONFIG.RATE_LIMIT_WINDOW,
|
||||
max: SECURITY_CONFIG.RATE_LIMIT_MAX_REQUESTS,
|
||||
message: {
|
||||
success: false,
|
||||
message: "Too Many Requests",
|
||||
error: "Rate limit exceeded. Please try again later.",
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
|
||||
// WebSocket rate limiter middleware with enhanced configuration
|
||||
export const wsRateLimiter = rateLimit({
|
||||
windowMs: 60 * 1000, // 1 minute
|
||||
max: RATE_LIMIT_CONFIG.WEBSOCKET,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
message: {
|
||||
success: false,
|
||||
message: 'Too many WebSocket connections, please try again later.',
|
||||
reset_time: new Date(Date.now() + 60 * 1000).toISOString()
|
||||
},
|
||||
skipSuccessfulRequests: false,
|
||||
keyGenerator: (req) => req.ip || req.socket.remoteAddress || 'unknown'
|
||||
windowMs: 60 * 1000, // 1 minute
|
||||
max: RATE_LIMIT_CONFIG.WEBSOCKET,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
message: {
|
||||
success: false,
|
||||
message: "Too many WebSocket connections, please try again later.",
|
||||
reset_time: new Date(Date.now() + 60 * 1000).toISOString(),
|
||||
},
|
||||
skipSuccessfulRequests: false,
|
||||
keyGenerator: (req) => req.ip || req.socket.remoteAddress || "unknown",
|
||||
});
|
||||
|
||||
// Authentication middleware with enhanced security
|
||||
export const authenticate = (req: Request, res: Response, next: NextFunction) => {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
error: 'Missing or invalid authorization header',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
export const authenticate = (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: "Unauthorized",
|
||||
error: "Missing or invalid authorization header",
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
const clientIp = req.ip || req.socket.remoteAddress || '';
|
||||
const token = authHeader.replace("Bearer ", "");
|
||||
const clientIp = req.ip || req.socket.remoteAddress || "";
|
||||
|
||||
const validationResult = TokenManager.validateToken(token, clientIp);
|
||||
const validationResult = TokenManager.validateToken(token, clientIp);
|
||||
|
||||
if (!validationResult.valid) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
error: validationResult.error || 'Invalid token',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
if (!validationResult.valid) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: "Unauthorized",
|
||||
error: validationResult.error || "Invalid token",
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
next();
|
||||
};
|
||||
|
||||
// Enhanced security headers middleware using helmet
|
||||
const helmetMiddleware = helmet({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: ["'self'", "'unsafe-inline'"],
|
||||
styleSrc: ["'self'", "'unsafe-inline'"],
|
||||
imgSrc: ["'self'", 'data:', 'https:'],
|
||||
connectSrc: ["'self'", 'wss:', 'https:'],
|
||||
frameSrc: ["'none'"],
|
||||
objectSrc: ["'none'"],
|
||||
baseUri: ["'self'"],
|
||||
formAction: ["'self'"],
|
||||
frameAncestors: ["'none'"]
|
||||
}
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: ["'self'", "'unsafe-inline'"],
|
||||
styleSrc: ["'self'", "'unsafe-inline'"],
|
||||
imgSrc: ["'self'", "data:", "https:"],
|
||||
connectSrc: ["'self'", "wss:", "https:"],
|
||||
frameSrc: ["'none'"],
|
||||
objectSrc: ["'none'"],
|
||||
baseUri: ["'self'"],
|
||||
formAction: ["'self'"],
|
||||
frameAncestors: ["'none'"],
|
||||
},
|
||||
crossOriginEmbedderPolicy: true,
|
||||
crossOriginOpenerPolicy: { policy: 'same-origin' },
|
||||
crossOriginResourcePolicy: { policy: 'same-origin' },
|
||||
dnsPrefetchControl: { allow: false },
|
||||
frameguard: { action: 'deny' },
|
||||
hidePoweredBy: true,
|
||||
hsts: {
|
||||
maxAge: 31536000,
|
||||
includeSubDomains: true,
|
||||
preload: true
|
||||
},
|
||||
ieNoOpen: true,
|
||||
noSniff: true,
|
||||
originAgentCluster: true,
|
||||
permittedCrossDomainPolicies: { permittedPolicies: 'none' },
|
||||
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
|
||||
xssFilter: true
|
||||
},
|
||||
crossOriginEmbedderPolicy: true,
|
||||
crossOriginOpenerPolicy: { policy: "same-origin" },
|
||||
crossOriginResourcePolicy: { policy: "same-origin" },
|
||||
dnsPrefetchControl: { allow: false },
|
||||
frameguard: { action: "deny" },
|
||||
hidePoweredBy: true,
|
||||
hsts: {
|
||||
maxAge: 31536000,
|
||||
includeSubDomains: true,
|
||||
preload: true,
|
||||
},
|
||||
ieNoOpen: true,
|
||||
noSniff: true,
|
||||
originAgentCluster: true,
|
||||
permittedCrossDomainPolicies: { permittedPolicies: "none" },
|
||||
referrerPolicy: { policy: "strict-origin-when-cross-origin" },
|
||||
xssFilter: true,
|
||||
});
|
||||
|
||||
// Wrapper for helmet middleware to handle mock responses in tests
|
||||
export const securityHeaders = (req: Request, res: Response, next: NextFunction): void => {
|
||||
// Basic security headers
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('X-Frame-Options', 'DENY');
|
||||
res.setHeader('X-XSS-Protection', '1; mode=block');
|
||||
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||
res.setHeader('X-Permitted-Cross-Domain-Policies', 'none');
|
||||
res.setHeader('X-Download-Options', 'noopen');
|
||||
export const securityHeaders = (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
): void => {
|
||||
// Basic security headers
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
res.setHeader("X-Frame-Options", "DENY");
|
||||
res.setHeader("X-XSS-Protection", "1; mode=block");
|
||||
res.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
|
||||
res.setHeader("X-Permitted-Cross-Domain-Policies", "none");
|
||||
res.setHeader("X-Download-Options", "noopen");
|
||||
|
||||
// Content Security Policy
|
||||
res.setHeader('Content-Security-Policy', [
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self'",
|
||||
"img-src 'self'",
|
||||
"font-src 'self'",
|
||||
"connect-src 'self'",
|
||||
"media-src 'self'",
|
||||
"object-src 'none'",
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'"
|
||||
].join('; '));
|
||||
// Content Security Policy
|
||||
res.setHeader(
|
||||
"Content-Security-Policy",
|
||||
[
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self'",
|
||||
"img-src 'self'",
|
||||
"font-src 'self'",
|
||||
"connect-src 'self'",
|
||||
"media-src 'self'",
|
||||
"object-src 'none'",
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
].join("; "),
|
||||
);
|
||||
|
||||
// HSTS (only in production)
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
|
||||
}
|
||||
// HSTS (only in production)
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
res.setHeader(
|
||||
"Strict-Transport-Security",
|
||||
"max-age=31536000; includeSubDomains; preload",
|
||||
);
|
||||
}
|
||||
|
||||
next();
|
||||
next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Validates incoming requests for proper authentication and content type
|
||||
*/
|
||||
export const validateRequest = (req: Request, res: Response, next: NextFunction): Response | void => {
|
||||
// Skip validation for health and MCP schema endpoints
|
||||
if (req.path === '/health' || req.path === '/mcp') {
|
||||
return next();
|
||||
}
|
||||
export const validateRequest = (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
): Response | void => {
|
||||
// Skip validation for health and MCP schema endpoints
|
||||
if (req.path === "/health" || req.path === "/mcp") {
|
||||
return next();
|
||||
}
|
||||
|
||||
// Validate content type for non-GET requests
|
||||
if (['POST', 'PUT', 'PATCH'].includes(req.method)) {
|
||||
const contentType = req.headers['content-type'] || '';
|
||||
if (!contentType.toLowerCase().includes('application/json')) {
|
||||
return res.status(415).json({
|
||||
success: false,
|
||||
message: 'Unsupported Media Type',
|
||||
error: 'Content-Type must be application/json',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
// Validate content type for non-GET requests
|
||||
if (["POST", "PUT", "PATCH"].includes(req.method)) {
|
||||
const contentType = req.headers["content-type"] || "";
|
||||
if (!contentType.toLowerCase().includes("application/json")) {
|
||||
return res.status(415).json({
|
||||
success: false,
|
||||
message: "Unsupported Media Type",
|
||||
error: "Content-Type must be application/json",
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Validate authorization header
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
error: 'Missing or invalid authorization header',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
// Validate authorization header
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: "Unauthorized",
|
||||
error: "Missing or invalid authorization header",
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
// Validate token
|
||||
const token = authHeader.replace("Bearer ", "");
|
||||
const validationResult = TokenManager.validateToken(token, req.ip);
|
||||
if (!validationResult.valid) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: "Unauthorized",
|
||||
error: validationResult.error || "Invalid token",
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
// Validate request body structure
|
||||
if (req.method !== "GET" && req.body) {
|
||||
if (typeof req.body !== "object" || Array.isArray(req.body)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: "Bad Request",
|
||||
error: "Invalid request body structure",
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Validate token
|
||||
const token = authHeader.replace('Bearer ', '');
|
||||
const validationResult = TokenManager.validateToken(token, req.ip);
|
||||
if (!validationResult.valid) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Unauthorized',
|
||||
error: validationResult.error || 'Invalid token',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
// Validate request body structure
|
||||
if (req.method !== 'GET' && req.body) {
|
||||
if (typeof req.body !== 'object' || Array.isArray(req.body)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Bad Request',
|
||||
error: 'Invalid request body structure',
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Sanitizes input data to prevent XSS attacks
|
||||
*/
|
||||
export const sanitizeInput = (req: Request, res: Response, next: NextFunction): void => {
|
||||
if (req.body && typeof req.body === 'object' && !Array.isArray(req.body)) {
|
||||
const sanitizeValue = (value: unknown): unknown => {
|
||||
if (typeof value === 'string') {
|
||||
let sanitized = value;
|
||||
// Remove script tags and their content
|
||||
sanitized = sanitized.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
|
||||
// Remove style tags and their content
|
||||
sanitized = sanitized.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '');
|
||||
// Remove remaining HTML tags
|
||||
sanitized = sanitized.replace(/<[^>]+>/g, '');
|
||||
// Remove javascript: protocol
|
||||
sanitized = sanitized.replace(/javascript:/gi, '');
|
||||
// Remove event handlers
|
||||
sanitized = sanitized.replace(/on\w+\s*=\s*(?:".*?"|'.*?'|[^"'>\s]+)/gi, '');
|
||||
// Trim whitespace
|
||||
return sanitized.trim();
|
||||
} else if (typeof value === 'object' && value !== null) {
|
||||
const result: Record<string, unknown> = {};
|
||||
Object.entries(value as Record<string, unknown>).forEach(([key, val]) => {
|
||||
result[key] = sanitizeValue(val);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
export const sanitizeInput = (
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
): void => {
|
||||
if (req.body && typeof req.body === "object" && !Array.isArray(req.body)) {
|
||||
const sanitizeValue = (value: unknown): unknown => {
|
||||
if (typeof value === "string") {
|
||||
let sanitized = value;
|
||||
// Remove script tags and their content
|
||||
sanitized = sanitized.replace(
|
||||
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
|
||||
"",
|
||||
);
|
||||
// Remove style tags and their content
|
||||
sanitized = sanitized.replace(
|
||||
/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi,
|
||||
"",
|
||||
);
|
||||
// Remove remaining HTML tags
|
||||
sanitized = sanitized.replace(/<[^>]+>/g, "");
|
||||
// Remove javascript: protocol
|
||||
sanitized = sanitized.replace(/javascript:/gi, "");
|
||||
// Remove event handlers
|
||||
sanitized = sanitized.replace(
|
||||
/on\w+\s*=\s*(?:".*?"|'.*?'|[^"'>\s]+)/gi,
|
||||
"",
|
||||
);
|
||||
// Trim whitespace
|
||||
return sanitized.trim();
|
||||
} else if (typeof value === "object" && value !== null) {
|
||||
const result: Record<string, unknown> = {};
|
||||
Object.entries(value as Record<string, unknown>).forEach(
|
||||
([key, val]) => {
|
||||
result[key] = sanitizeValue(val);
|
||||
},
|
||||
);
|
||||
return result;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
req.body = sanitizeValue(req.body) as Record<string, unknown>;
|
||||
}
|
||||
next();
|
||||
req.body = sanitizeValue(req.body) as Record<string, unknown>;
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Handles errors in a consistent way
|
||||
*/
|
||||
export const errorHandler = (err: Error, req: Request, res: Response, next: NextFunction): Response => {
|
||||
const isDevelopment = process.env.NODE_ENV === 'development';
|
||||
const response: Record<string, unknown> = {
|
||||
success: false,
|
||||
message: 'Internal Server Error',
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
export const errorHandler = (
|
||||
err: Error,
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
): Response => {
|
||||
const isDevelopment = process.env.NODE_ENV === "development";
|
||||
const response: Record<string, unknown> = {
|
||||
success: false,
|
||||
message: "Internal Server Error",
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
if (isDevelopment) {
|
||||
response.error = err.message;
|
||||
response.stack = err.stack;
|
||||
}
|
||||
if (isDevelopment) {
|
||||
response.error = err.message;
|
||||
response.stack = err.stack;
|
||||
}
|
||||
|
||||
return res.status(500).json(response);
|
||||
return res.status(500).json(response);
|
||||
};
|
||||
|
||||
// Export all middleware
|
||||
export const middleware = {
|
||||
rateLimiter,
|
||||
wsRateLimiter,
|
||||
securityHeaders,
|
||||
validateRequest,
|
||||
sanitizeInput,
|
||||
authenticate,
|
||||
errorHandler
|
||||
};
|
||||
rateLimiter,
|
||||
wsRateLimiter,
|
||||
securityHeaders,
|
||||
validateRequest,
|
||||
sanitizeInput,
|
||||
authenticate,
|
||||
errorHandler,
|
||||
};
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
/**
|
||||
* Logging Middleware
|
||||
*
|
||||
*
|
||||
* This middleware provides request logging functionality.
|
||||
* It logs incoming requests and their responses.
|
||||
*
|
||||
*
|
||||
* @module logging-middleware
|
||||
*/
|
||||
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { logger } from '../utils/logger.js';
|
||||
import { APP_CONFIG } from '../config/app.config.js';
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { logger } from "../utils/logger.js";
|
||||
import { APP_CONFIG } from "../config/app.config.js";
|
||||
|
||||
/**
|
||||
* Interface for extended request object with timing information
|
||||
*/
|
||||
interface TimedRequest extends Request {
|
||||
startTime?: number;
|
||||
startTime?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -24,10 +24,10 @@ interface TimedRequest extends Request {
|
||||
* @returns Response time in milliseconds
|
||||
*/
|
||||
const getResponseTime = (startTime: number): number => {
|
||||
const NS_PER_SEC = 1e9; // nanoseconds per second
|
||||
const NS_TO_MS = 1e6; // nanoseconds to milliseconds
|
||||
const diff = process.hrtime();
|
||||
return (diff[0] * NS_PER_SEC + diff[1]) / NS_TO_MS - startTime;
|
||||
const NS_PER_SEC = 1e9; // nanoseconds per second
|
||||
const NS_TO_MS = 1e6; // nanoseconds to milliseconds
|
||||
const diff = process.hrtime();
|
||||
return (diff[0] * NS_PER_SEC + diff[1]) / NS_TO_MS - startTime;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -36,11 +36,11 @@ const getResponseTime = (startTime: number): number => {
|
||||
* @returns Client IP address
|
||||
*/
|
||||
const getClientIp = (req: Request): string => {
|
||||
return (
|
||||
(req.headers['x-forwarded-for'] as string)?.split(',')[0] ||
|
||||
req.socket.remoteAddress ||
|
||||
'unknown'
|
||||
);
|
||||
return (
|
||||
(req.headers["x-forwarded-for"] as string)?.split(",")[0] ||
|
||||
req.socket.remoteAddress ||
|
||||
"unknown"
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -49,7 +49,7 @@ const getClientIp = (req: Request): string => {
|
||||
* @returns Formatted log message
|
||||
*/
|
||||
const formatRequestLog = (req: TimedRequest): string => {
|
||||
return `${req.method} ${req.originalUrl} - IP: ${getClientIp(req)}`;
|
||||
return `${req.method} ${req.originalUrl} - IP: ${getClientIp(req)}`;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -59,48 +59,64 @@ const formatRequestLog = (req: TimedRequest): string => {
|
||||
* @param time - Response time in milliseconds
|
||||
* @returns Formatted log message
|
||||
*/
|
||||
const formatResponseLog = (req: TimedRequest, res: Response, time: number): string => {
|
||||
return `${req.method} ${req.originalUrl} - ${res.statusCode} - ${time.toFixed(2)}ms`;
|
||||
const formatResponseLog = (
|
||||
req: TimedRequest,
|
||||
res: Response,
|
||||
time: number,
|
||||
): string => {
|
||||
return `${req.method} ${req.originalUrl} - ${res.statusCode} - ${time.toFixed(2)}ms`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Request logging middleware
|
||||
* Logs information about incoming requests and their responses
|
||||
*/
|
||||
export const requestLogger = (req: TimedRequest, res: Response, next: NextFunction): void => {
|
||||
if (!APP_CONFIG.LOGGING.LOG_REQUESTS) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
// Record start time
|
||||
req.startTime = Date.now();
|
||||
|
||||
// Log request
|
||||
logger.http(formatRequestLog(req));
|
||||
|
||||
// Log response
|
||||
res.on('finish', () => {
|
||||
const responseTime = Date.now() - (req.startTime || 0);
|
||||
const logLevel = res.statusCode >= 400 ? 'warn' : 'http';
|
||||
logger[logLevel](formatResponseLog(req, res, responseTime));
|
||||
});
|
||||
|
||||
export const requestLogger = (
|
||||
req: TimedRequest,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
): void => {
|
||||
if (!APP_CONFIG.LOGGING.LOG_REQUESTS) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
// Record start time
|
||||
req.startTime = Date.now();
|
||||
|
||||
// Log request
|
||||
logger.http(formatRequestLog(req));
|
||||
|
||||
// Log response
|
||||
res.on("finish", () => {
|
||||
const responseTime = Date.now() - (req.startTime || 0);
|
||||
const logLevel = res.statusCode >= 400 ? "warn" : "http";
|
||||
logger[logLevel](formatResponseLog(req, res, responseTime));
|
||||
});
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Error logging middleware
|
||||
* Logs errors that occur during request processing
|
||||
*/
|
||||
export const errorLogger = (err: Error, req: Request, res: Response, next: NextFunction): void => {
|
||||
logger.error(`Error processing ${req.method} ${req.originalUrl}: ${err.message}`, {
|
||||
error: err.stack,
|
||||
method: req.method,
|
||||
url: req.originalUrl,
|
||||
body: req.body,
|
||||
query: req.query,
|
||||
ip: getClientIp(req)
|
||||
});
|
||||
next(err);
|
||||
};
|
||||
export const errorLogger = (
|
||||
err: Error,
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
): void => {
|
||||
logger.error(
|
||||
`Error processing ${req.method} ${req.originalUrl}: ${err.message}`,
|
||||
{
|
||||
error: err.stack,
|
||||
method: req.method,
|
||||
url: req.originalUrl,
|
||||
body: req.body,
|
||||
query: req.query,
|
||||
ip: getClientIp(req),
|
||||
},
|
||||
);
|
||||
next(err);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user