http-proxy-middleware
Version:
The one-liner node.js proxy middleware for connect, express, next.js and more
49 lines (48 loc) • 2.37 kB
JavaScript
import { HttpProxyMiddlewareError } from '../../errors.js';
const CR_OR_LF = /[\r\n]/;
// RFC 2046 §5.1.1: boundary := 0*69<bchars> bcharsnospace (bchars minus trailing space).
const BOUNDARY_RE = /^[0-9A-Za-z'()+_,\-./:=? ]{0,69}[0-9A-Za-z'()+_,\-./:=?]$/;
/**
* HPM_ERR_INVALID_MULTIPART prefixed error code will be used in
* [status-code.ts]({@link ../../status-code.ts}) to return status code 400.
*/
export const HPM_ERR_INVALID_MULTIPART = 'HPM_ERR_INVALID_MULTIPART';
/**
* stringify FormData data
* @param contentType
* @param data
* @returns
*/
export function stringifyFormData(contentType, data) {
const boundary = getMultipartBoundary(contentType);
let str = '';
for (const [key, value] of Object.entries(data)) {
const normalizedKey = String(key);
const normalizedValue = String(value);
// Reject potentially dangerous sequences to prevent multipart header/body injection.
validateMultipartField(normalizedKey, normalizedValue, boundary);
str += `--${boundary}\r\nContent-Disposition: form-data; name="${escapeMultipartFieldName(normalizedKey)}"\r\n\r\n${normalizedValue}\r\n`;
}
str += `--${boundary}--\r\n`; // close-delimiter per RFC 2046 §5.1.1
return str;
}
function getMultipartBoundary(contentType) {
const boundaryMatch = /(?:^|;)\s*boundary=(?:"([^"]+)"|([^;\s]+))\s*(?=;|$)/i.exec(contentType);
const boundary = boundaryMatch?.[1] ?? boundaryMatch?.[2] ?? '';
if (!boundary || CR_OR_LF.test(boundary) || !BOUNDARY_RE.test(boundary)) {
throw new HttpProxyMiddlewareError('[HPM] invalid multipart boundary detected.', `${HPM_ERR_INVALID_MULTIPART}_BOUNDARY`);
}
return boundary;
}
function validateMultipartField(fieldName, fieldValue, boundary) {
const boundaryDelimiter = `--${boundary}`;
if (CR_OR_LF.test(fieldName)) {
throw new HttpProxyMiddlewareError(`[HPM] invalid multipart field name "${fieldName}" detected.`, `${HPM_ERR_INVALID_MULTIPART}_FIELD_NAME`);
}
if (CR_OR_LF.test(fieldValue) || fieldValue.includes(boundaryDelimiter)) {
throw new HttpProxyMiddlewareError(`[HPM] invalid multipart field value for "${fieldName}" detected.`, `${HPM_ERR_INVALID_MULTIPART}_FIELD_VALUE`);
}
}
function escapeMultipartFieldName(fieldName) {
return fieldName.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}