UNPKG

header-middleware-next

Version:

A lightweight and flexible middleware utility for managing HTTP headers in Next.js applications. Supports header extraction, transformation, masking, and safe injection for Edge and API routes.

57 lines (51 loc) 1.98 kB
/** * Function to validate the HTTP method of an incoming request. * It classifies the method as dangerous, allowed, or unexpected, * providing a detailed status and metadata about the request method. * * @param {Object} req - The HTTP request object expected to have a 'method' property. * @returns {Object} - Result object including type, name, message, and meta with the HTTP method. */ export default async function checkMethod(req) { // Normalize the HTTP method to uppercase to ensure case-insensitive comparison. const method = req.method?.toUpperCase(); // Define a list of HTTP methods considered dangerous or insecure for general use. const dangerousMethods = ['TRACE', 'CONNECT', 'TRACK']; /** * Check if the HTTP method used is among the dangerous methods. * These methods can potentially be exploited for security vulnerabilities, * such as cross-site tracing attacks or proxy tunneling. */ if (dangerousMethods.includes(method)) { return { type: 'error', name: 'Method', message: `Dangerous HTTP method used: ${method}`, meta: { method } }; } // Define a whitelist of standard, commonly accepted HTTP methods. const allowedMethods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']; /** * If the method is not in the allowed list, classify it as unexpected. * This could indicate client errors, misconfigurations, or potential abuse. */ if (!allowedMethods.includes(method)) { return { type: 'warning', name: 'Method', message: `Unexpected HTTP method: ${method}`, meta: { method } }; } /** * If none of the above conditions apply, the HTTP method is considered valid and safe. * Return a success response with the detected method information. */ return { type: 'success', name: 'Method', message: 'Valid HTTP method', meta: { method } }; }