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.
87 lines (75 loc) • 2.73 kB
JavaScript
/**
* Function to evaluate the length and content of HTTP request headers.
* It leverages an external helper to analyze headers and returns
* categorized results based on length thresholds and suspicious header fields.
*
* @param {Object} req - The HTTP request object containing headers.
* @returns {Object} - An object describing the result with type, name, message, and meta info.
*/
import { analyzeHeaders } from '../lib/helper.js';
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
export default async function checkHeadersLength(req) {
// Invoke the helper function to analyze headers for length and suspicious fields.
const analysis = await analyzeHeaders(req);
if (analysis instanceof NextResponse) {
return analysis;
}
// Immediately return a warning if the analysis flags a warning condition.
if (analysis.warning) {
return {
type: 'warning',
name: 'Headers-Length',
message: analysis.message
};
}
// Destructure useful analysis details for further conditional checks.
const { totalLength, headerCount, suspiciousFields } = analysis;
// Prepare a base result object with meta details to reuse across return statements.
const result = {
name: 'Headers-Length',
meta: {
totalLength,
headerCount,
suspiciousFields
}
};
// Check if no headers are present (length zero) and return an error.
if (totalLength === 1) {
return {
...result,
type: 'error',
message: 'No headers present in the request (length = 0)'
};
}
// Warn if the total headers length is suspiciously short, possibly indicating incomplete or malformed headers.
if (totalLength < 100) {
return {
...result,
type: 'warning',
message: `Unusually short header size: ${totalLength} bytes`
};
}
// Flag an error if the header length exceeds common maximum allowed size (8 KB), which can indicate abuse or misconfiguration.
if (totalLength > 8192) {
return {
...result,
type: 'error',
message: `Excessive header size: ${totalLength} bytes`
};
}
// Issue a warning if any suspicious headers were detected by the helper function.
if (suspiciousFields.length > 0) {
return {
...result,
type: 'warning',
message: `Suspicious content detected in ${suspiciousFields.length} header(s)`
};
}
// Default case: return success indicating header length is within acceptable bounds.
return {
...result,
type: 'success',
message: `Header length is within acceptable range (${totalLength} bytes)`
};
}