### Install hppx with npm Source: https://github.com/hiprax/hppx/blob/main/README.md Install the hppx package using npm. This is the standard installation command for adding hppx to a Node.js project. ```bash npm install hppx ``` -------------------------------- ### DEFAULT_SOURCES usage example Source: https://github.com/hiprax/hppx Shows importing DEFAULT_SOURCES and DEFAULT_STRATEGY and assigning DEFAULT_SOURCES to a readonly RequestSource array. ```typescript import { DEFAULT_SOURCES, DEFAULT_STRATEGY } from "hppx"; import type { RequestSource } from "hppx"; const sources: readonly RequestSource[] = DEFAULT_SOURCES; // ["query", "body", "params"] ``` -------------------------------- ### DEFAULT_STRATEGY usage example Source: https://github.com/hiprax/hppx Shows using DEFAULT_STRATEGY with sanitize() to explicitly set the merge strategy, equivalent to calling sanitize without it. ```typescript import { DEFAULT_STRATEGY, sanitize } from "hppx"; // Equivalent to sanitize({ q: ["1", "2"] }) — resolves to keepLast const clean = sanitize({ q: ["1", "2"] }, { mergeStrategy: DEFAULT_STRATEGY }); // clean.q === "2" ``` -------------------------------- ### Exclude specific paths from hppx Source: https://github.com/hiprax/hppx/blob/main/README.md Use `excludePaths` to skip hppx processing for matching paths. The example excludes `/public` and paths starting with `/assets`. ```typescript app.use(hppx({ excludePaths: ["/public", "/assets*"] })); ``` -------------------------------- ### __resetPathSegmentCache usage example Source: https://github.com/hiprax/hppx Shows importing and calling __resetPathSegmentCache, intended only for tests that need a clean cache between cases. ```typescript import { __resetPathSegmentCache } from "hppx"; // Only meaningful in tests that need a clean cache between cases: __resetPathSegmentCache(); ``` -------------------------------- ### Basic hppx usage with Express Source: https://github.com/hiprax/hppx Sets up hppx middleware with a whitelist, mergeStrategy 'keepLast', and sources 'query' and 'body'. The /search route returns query and body objects along with their polluted counterparts. Requires express and hppx installed. ```typescript import express from "express"; import hppx from "hppx"; const app = express(); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use( hppx({ whitelist: ["tags", "user.roles", "ids"], mergeStrategy: "keepLast", sources: ["query", "body"], }), ); app.get("/search", (req, res) => { res.json({ query: req.query, queryPolluted: req.queryPolluted ?? {}, body: req.body ?? {}, bodyPolluted: req.bodyPolluted ?? {}, }); }); app.listen(3000); ``` -------------------------------- ### Footgun Example: Strict Mode Ignored on Subsequent Middleware Source: https://github.com/hiprax/hppx/blob/main/README.md Illustrates a common pitfall: when a global hppx instance already processes a source, a later instance's options like 'strict' are silently ignored for that source. Here, strict mode on the route-level middleware will NOT trigger a 400 response because the source was already cleaned. ```typescript // Global middleware — keepLast strategy, no strict mode app.use(hppx({ mergeStrategy: "keepLast" })); // Route-level middleware — strict mode, but it's TOO LATE app.use( "/api/admin", hppx({ strict: true }), // SILENTLY IGNORED — the source was already // cleaned by the global middleware, so strict // mode here will NOT cause a 400 response. ); ``` -------------------------------- ### DANGEROUS_KEYS usage example Source: https://github.com/hiprax/hppx Shows inspecting DANGEROUS_KEYS and that calling add throws a TypeError because the set is read-only. ```typescript import { DANGEROUS_KEYS } from "hppx"; console.log([...DANGEROUS_KEYS]); // ["__proto__", "prototype", "constructor"] console.log(DANGEROUS_KEYS.has("constructor")); // true try { DANGEROUS_KEYS.add("evil"); // own .add throws -> TypeError } catch (err) { console.error(err); // TypeError: DANGEROUS_KEYS is read-only } ``` -------------------------------- ### sanitize() usage with CommonJS require Source: https://github.com/hiprax/hppx/blob/main/README.md Example of using sanitize() with CommonJS require. It cleans the payload object, applying whitelist and mergeStrategy options. Only SanitizeOptions are accepted; middleware-only options are ignored. ```javascript const { sanitize } = require("hppx"); const clean = sanitize(payload, { whitelist: ["user.tags"], mergeStrategy: "keepFirst", }); ``` -------------------------------- ### sanitize() usage with ESM import Source: https://github.com/hiprax/hppx/blob/main/README.md Example of using sanitize() with ES module import. It cleans the payload object, applying whitelist and mergeStrategy options. Only SanitizeOptions are accepted; middleware-only options are ignored. ```typescript import { sanitize } from "hppx"; const clean = sanitize(payload, { whitelist: ["user.tags"], mergeStrategy: "keepFirst", }); ``` -------------------------------- ### Module augmentation for Express Request (express-serve-static-core) Source: https://github.com/hiprax/hppx Declares optional polluted-tree fields on Express Request so consumers get typed access without extra imports. Fields are non-enumerable and record pre-reduction multi-value trees for query, body, and params. ```typescript declare module "express-serve-static-core" { interface Request { queryPolluted?: Record; bodyPolluted?: Record; paramsPolluted?: Record; } } ``` -------------------------------- ### Handle hppx limit errors with Express error handler Source: https://github.com/hiprax/hppx/blob/main/README.md hppx passes errors to `next(err)` when a request exceeds `maxDepth` or `maxKeys`, and for other processing failures. These are plain `Error` objects without a `status`, so Express answers 500 unless your handler maps them. The example maps limit errors to a 400 response. Invalid options throw a `TypeError` when `hppx()` is called. ```typescript import type { ErrorRequestHandler } from "express"; const hppLimitErrors: ErrorRequestHandler = (err, _req, res, next) => { if ( err instanceof Error && /^Maximum (object depth|key count) \([^)]*\) exceeded$/.test(err.message) ) { res.status(400).json({ error: "Bad Request" }); return; } next(err); }; app.use(hppx({ maxDepth: 10, maxKeys: 500 })); // ... routes ... app.use(hppLimitErrors); ``` -------------------------------- ### Multi-Middleware Stacking with Incremental Whitelisting Source: https://github.com/hiprax/hppx/blob/main/README.md Shows how to stack hppx middleware globally and at route level to incrementally whitelist parameters. The global middleware whitelists 'a', the route-level middleware adds 'b' and 'c', so on the '/data' route all three are allowed as arrays. ```typescript // Global middleware — whitelist "a" app.use(hppx({ whitelist: ["a"] })); // Route-level middleware — additionally whitelist "b" and "c" const router = express.Router(); router.use(hppx({ whitelist: ["b", "c"] })); // On this route, "a", "b", and "c" are all allowed as arrays router.get("/data", (req, res) => { res.json({ query: req.query }); }); app.use("/api", router); ``` -------------------------------- ### hppx(options?: HppxOptions) Source: https://github.com/hiprax/hppx/blob/main/README.md Creates an Express-compatible middleware that sanitizes selected request sources and exposes `*.Polluted` objects on the request. Invalid options throw a `TypeError` at middleware creation time. ```APIDOC ## hppx(options?: HppxOptions) ### Description Creates an Express-compatible middleware. Applies sanitization to each selected source and exposes `*.Polluted` objects on the request. Invalid options throw a `TypeError` at middleware creation time, not at request time. ### Method N/A (Middleware factory) ### Endpoint N/A ### Parameters #### Options **Whitelist & Strategy:** | Option | Type | Default | Description | | --------------- | ---------------------------------------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `whitelist` | `string[] \| string` | `[]` | Keys allowed to remain as arrays. Supports exact dot-notation (`"user.tags"`), leaf matching (`"tags"` matches any path ending in `tags`), and prefix/subtree matching (`"user"` whitelists every key under the `user.*` subtree). | | `mergeStrategy` | `'keepFirst' \| 'keepLast' \| 'combine'` | `'keepLast'` | How to reduce duplicate/array parameters when not whitelisted. `keepFirst` takes the first value, `keepLast` takes the last, `combine` flattens all values into a single array. | **Source Selection:** | Option | Type | Default | Description | | ---------------------- | -------------------------------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `sources` | `Array<'query' \| 'body' \| 'params'>` | `['query', 'body', 'params']` | Which request parts to sanitize. | | `checkBodyContentType` | `'urlencoded' \| 'any' \| 'none'` | `'urlencoded'` | When to process `req.body`. `urlencoded` only processes URL-encoded bodies, `any` processes all content types, `none` skips body processing entirely. | | `excludePaths` | `string[]` | `[]` | Paths to exclude from sanitization. Supports `*` wildcard suffix (e.g., `"/assets*"`). | **Security Limits (DoS Protection):** | Option | Type | Default | Range | Description | | ---------------- | -------- | ------- | -------- | ------------------------------------------------------------------------------------- | | `maxDepth` | `number` | `20` | 1 - 100 | Maximum object nesting depth. Exceeding this throws an error passed to `next()`. | | `maxKeys` | `number` | `5000` | >= 1 | Maximum number of keys to process. Exceeding this throws an error passed to `next()`. | | `maxArrayLength` | `number` | `1000` | >= 1 | Maximum array length. Arrays are truncated before processing. | | `maxKeyLength` | `number` | `200` | 1 - 1000 | Maximum key string length. Longer keys are silently dropped. | ### Response N/A (Middleware) ### Notes - Invalid options throw a `TypeError` at middleware creation time. - Options are captured at creation time; later changes to arrays or `DEFAULT_SOURCES` do not affect the middleware. - A limit outside its range, a non-number value, or `NaN` throws a `TypeError` when the middleware is created. - `Infinity` is accepted for `maxKeys` and `maxArrayLength`. - Sources are processed in order and committed in-place; errors are forwarded to `next()` immediately, but earlier sources remain sanitized. ``` -------------------------------- ### sanitize(input, options?) Source: https://github.com/hiprax/hppx/blob/main/README.md Sanitizes a plain object using the same rules as the hppx middleware. Returns only the cleaned object, discarding polluted-tree data. Accepts only SanitizeOptions; middleware-only options are silently ignored. ```APIDOC ## sanitize(input, options?) ### Description Sanitizes a plain object using the same rules as the hppx middleware. Returns only the cleaned object, discarding polluted-tree data. Accepts only SanitizeOptions; middleware-only options are silently ignored. ### Signature ```typescript function sanitize>(input: T, options?: SanitizeOptions): T; ``` ### Parameters #### input (T) - Required - The plain object to sanitize. #### options (SanitizeOptions) - Optional - Configuration options. Accepted fields: `whitelist`, `mergeStrategy`, `maxDepth`, `maxKeys`, `maxArrayLength`, `maxKeyLength`, `trimValues`, `preserveNull`. Middleware-only options (`sources`, `excludePaths`, `strict`, `onPollutionDetected`, `logger`, `logPollution`, `checkBodyContentType`) are silently ignored. ### Return Value Returns the cleaned object with the same shape as `input`, with arrays reduced according to the chosen merge strategy. Does not return the internal `SanitizedResult`. ### Request Example ```typescript import { sanitize } from "hppx"; const clean = sanitize(payload, { whitelist: ["user.tags"], mergeStrategy: "keepFirst", }); ``` ```javascript const { sanitize } = require("hppx"); const clean = sanitize(payload, { whitelist: ["user.tags"], mergeStrategy: "keepFirst", }); ``` ``` -------------------------------- ### hppx() Middleware Source: https://github.com/hiprax/hppx/blob/main/README.md Creates an Express middleware that protects against HTTP Parameter Pollution. Accepts options to configure strict mode, body content type checking, path exclusions, logging, and security limits. ```APIDOC ## hppx(options?) ### Description Creates an Express middleware that protects against HTTP Parameter Pollution. Accepts options to configure strict mode, body content type checking, path exclusions, logging, and security limits. ### Parameters #### Options (object) - Optional - **strict** (boolean) - Optional - When true, respond with 400 on pollution. - **checkBodyContentType** (string) - Optional - Set to "any" to process JSON bodies too. - **excludePaths** (string[]) - Optional - Paths to exclude from protection. - **logger** (function) - Optional - Custom logger for pollution warnings and errors. - **logPollution** (boolean) - Optional - Set to false to disable automatic pollution logging. - **maxDepth** (number) - Optional - Maximum object depth. - **maxKeys** (number) - Optional - Maximum key count. ### Returns Express middleware function. ### Example ```typescript app.use(hppx({ strict: true })); ``` ``` -------------------------------- ### hppx middleware production configuration Source: https://github.com/hiprax/hppx/blob/main/README.md Configure hppx with security limits and pollution detection. Sets maxDepth, maxKeys, maxArrayLength, maxKeyLength, strict mode, and an onPollutionDetected callback that logs warnings with request and pollution details. ```TypeScript app.use( hppx({ maxDepth: 10, maxKeys: 1000, maxArrayLength: 100, maxKeyLength: 100, strict: true, onPollutionDetected: (req, info) => { securityLogger.warn("HPP detected", { ip: req.ip, path: req.path, source: info.source, pollutedKeys: info.pollutedKeys, }); }, }), ); ``` -------------------------------- ### sanitize() with advanced options and error handling Source: https://github.com/hiprax/hppx Demonstrates sanitize() with keepFirst strategy, trimming, preserveNull=false, and tight limits. Shows trimming of strings, removal of null values, and array truncation. Includes try/catch for potential TypeErrors or depth/key count errors. ```typescript import { sanitize } from "hppx"; // keepFirst + trim + preserveNull=false + tight limits try { const clean = sanitize( { user: { name: " alice ", roles: null }, list: [1, 2, 3] }, { mergeStrategy: "keepFirst", trimValues: true, preserveNull: false, maxKeyLength: 50, maxArrayLength: 2, }, ); // clean.user.name === "alice" (trimmed) // "roles" key dropped (null removed, preserveNull=false) // clean.list === [1, 2] (truncated to maxArrayLength) } catch (err) { // e.g. a TypeError from invalid options, or // "Maximum object depth (..) exceeded" / "Maximum key count (..) exceeded" console.error(err instanceof Error ? err.message : err); } ``` -------------------------------- ### CommonJS usage with Express Source: https://github.com/hiprax/hppx/blob/main/README.md Sets up hppx middleware in an Express app using CommonJS. Configures whitelist, mergeStrategy, and sources, then defines a /search route that returns cleaned and polluted request data. ```javascript const express = require("express"); const hppx = require("hppx"); const app = express(); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use( hppx({ whitelist: ["tags", "user.roles", "ids"], mergeStrategy: "keepLast", sources: ["query", "body"], }), ); app.get("/search", (req, res) => { res.json({ query: req.query, queryPolluted: req.queryPolluted ?? {}, body: req.body ?? {}, bodyPolluted: req.bodyPolluted ?? {}, params: req.params, paramsPolluted: req.paramsPolluted ?? {}, }); }); ``` -------------------------------- ### Pollution Detection Callback with onPollutionDetected Source: https://github.com/hiprax/hppx/blob/main/README.md Configures the onPollutionDetected callback to log when HPP is detected. The callback is invoked once per polluted source (query, body, params) and receives an info object with 'source' and 'pollutedKeys' properties. ```typescript app.use( hppx({ onPollutionDetected: (req, info) => { // Called once per polluted source (query, body, params) securityLogger.warn("HPP detected", { source: info.source, pollutedKeys: info.pollutedKeys, }); }, }), ); ``` -------------------------------- ### ESM usage with Express Source: https://github.com/hiprax/hppx/blob/main/README.md Sets up hppx middleware in an Express app using ES modules. Configures whitelist, mergeStrategy, and sources, then defines a /search route that returns cleaned and polluted request data. ```typescript import express from "express"; import hppx from "hppx"; const app = express(); app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use( hppx({ whitelist: ["tags", "user.roles", "ids"], mergeStrategy: "keepLast", sources: ["query", "body"], }), ); app.get("/search", (req, res) => { res.json({ query: req.query, queryPolluted: req.queryPolluted ?? {}, body: req.body ?? {}, bodyPolluted: req.bodyPolluted ?? {}, params: req.params, paramsPolluted: req.paramsPolluted ?? {}, }); }); ``` -------------------------------- ### Custom logging with hppx logger option Source: https://github.com/hiprax/hppx/blob/main/README.md Provide a custom `logger` to receive pollution warnings (string messages) and errors (non-string values). Disable automatic pollution logging with `logPollution: false`. ```typescript // Use your application's logger app.use( hppx({ logger: (msg) => { if (typeof msg === "string") { myLogger.warn(msg); // Pollution warnings } else { myLogger.error(msg); // Errors } }, }), ); // Disable automatic pollution logging app.use(hppx({ logPollution: false })); ``` -------------------------------- ### DANGEROUS_KEYS Source: https://github.com/hiprax/hppx ReadonlySet constant containing dangerous keys that are considered for prototype pollution detection. ```APIDOC ## DANGEROUS_KEYS ### Description ReadonlySet constant containing dangerous keys that are considered for prototype pollution detection. ### Method N/A (constant) ### Endpoint N/A ### Parameters None ### Response Returns a ReadonlySet of dangerous keys. ### Request Example ```typescript import { DANGEROUS_KEYS } from 'hppx'; console.log(DANGEROUS_KEYS); // Set { '__proto__', 'constructor', 'prototype' } ``` ### Response Example ```typescript // Set { '__proto__', 'constructor', 'prototype' } ``` ``` -------------------------------- ### Import hppx exported constants Source: https://github.com/hiprax/hppx/blob/main/README.md Imports the exported constants `DANGEROUS_KEYS`, `DEFAULT_SOURCES`, and `DEFAULT_STRATEGY`. `DANGEROUS_KEYS` is a copy of the keys hppx blocks; its own `add`, `delete`, and `clear` throw a `TypeError`, but direct `Set.prototype.delete` or `add` calls still change the copy. Treat it as information and do not build security checks on it. ```typescript import { DANGEROUS_KEYS, DEFAULT_SOURCES, DEFAULT_STRATEGY } from "hppx"; DANGEROUS_KEYS; // ReadonlySet: "__proto__", "prototype", "constructor" (a copy for inspection) DEFAULT_SOURCES; // ["query", "body", "params"] DEFAULT_STRATEGY; // "keepLast" ``` -------------------------------- ### DEFAULT_SOURCES Source: https://github.com/hiprax/hppx The default request sources used when the 'sources' option is omitted. It is an array of RequestSource values. ```APIDOC ## DEFAULT_SOURCES ### Description The default request sources used when the 'sources' option is omitted. It is an array of RequestSource values. ### Type `RequestSource[]` where `RequestSource = "query" | "body" | "params"` ### Example ```typescript import { DEFAULT_SOURCES, DEFAULT_STRATEGY } from "hppx"; import type { RequestSource } from "hppx"; const sources: readonly RequestSource[] = DEFAULT_SOURCES; // ["query", "body", "params"] ``` ``` -------------------------------- ### Basic sanitize() call with whitelist and keepLast Source: https://github.com/hiprax/hppx Shows a basic usage of sanitize() with a payload containing duplicate parameters, a dangerous __proto__ key, and whitelisted tags. The mergeStrategy 'keepLast' reduces duplicate arrays, dangerous keys are dropped, and whitelisted keys are preserved as arrays. ```typescript import { sanitize } from "hppx"; const payload = { q: ["red", "green", "blue"], // duplicate parameter -> reduced by keepLast "__proto__": { injected: true }, // blocked dangerous key -> dropped tags: ["a", "b"], // whitelisted -> preserved as array }; const clean = sanitize(payload, { whitelist: ["tags"], mergeStrategy: "keepLast", }); // clean.q === "blue" // clean.tags === ["a", "b"] // "__proto__" is absent from clean ``` -------------------------------- ### hppxMiddleware function signature Source: https://github.com/hiprax/hppx Returned middleware function signature. Calls next() to continue, next(error) to forward errors, and short-circuits with res.status(400).json(...) when strict: true and pollution is detected. ```typescript function hppxMiddleware(req: any, res: any, next: ExpressLikeNext): void // where ExpressLikeNext = (err?: unknown) => void // (internal type alias, src/index.ts:937) ``` -------------------------------- ### DANGEROUS_KEYS Source: https://github.com/hiprax/hppx A read-only set containing the dangerous keys '__proto__', 'prototype', and 'constructor'. It is a copy for inspection only and does not affect hppx's internal guards. ```APIDOC ## DANGEROUS_KEYS ### Description A read-only set containing the dangerous keys '__proto__', 'prototype', and 'constructor'. It is a copy for inspection only and does not affect hppx's internal guards. ### Type `ReadonlySet` ### Example ```typescript import { DANGEROUS_KEYS } from "hppx"; console.log([...DANGEROUS_KEYS]); // ["__proto__", "prototype", "constructor"] console.log(DANGEROUS_KEYS.has("constructor")); // true try { DANGEROUS_KEYS.add("evil"); // own .add throws -> TypeError } catch (err) { console.error(err); // TypeError: DANGEROUS_KEYS is read-only } ``` ``` -------------------------------- ### Exported Constants Source: https://github.com/hiprax/hppx/blob/main/README.md Constants exported by hppx for inspection and configuration. ```APIDOC ## Exported Constants ### Description Constants exported by hppx for inspection and configuration. ### Constants - **DANGEROUS_KEYS** (ReadonlySet) - "__proto__", "prototype", "constructor" (a copy for inspection) - **DEFAULT_SOURCES** (string[]) - ["query", "body", "params"] - **DEFAULT_STRATEGY** (string) - "keepLast" ### Example ```typescript import { DANGEROUS_KEYS, DEFAULT_SOURCES, DEFAULT_STRATEGY } from "hppx"; ``` ``` -------------------------------- ### DEFAULT_SOURCES Source: https://github.com/hiprax/hppx RequestSource[] constant representing the default request sources to sanitize (e.g., ['query', 'body', 'params']). ```APIDOC ## DEFAULT_SOURCES ### Description RequestSource[] constant representing the default request sources to sanitize (e.g., ['query', 'body', 'params']). ### Method N/A (constant) ### Endpoint N/A ### Parameters None ### Response Returns a RequestSource[] array. ### Request Example ```typescript import { DEFAULT_SOURCES } from 'hppx'; console.log(DEFAULT_SOURCES); // ['query', 'body', 'params'] ``` ### Response Example ```typescript // ['query', 'body', 'params'] ``` ``` -------------------------------- ### DEFAULT_STRATEGY Source: https://github.com/hiprax/hppx MergeStrategy constant representing the default merge strategy for handling polluted keys. ```APIDOC ## DEFAULT_STRATEGY ### Description MergeStrategy constant representing the default merge strategy for handling polluted keys. ### Method N/A (constant) ### Endpoint N/A ### Parameters None ### Response Returns a MergeStrategy value. ### Request Example ```typescript import { DEFAULT_STRATEGY } from 'hppx'; console.log(DEFAULT_STRATEGY); // 'safe' ``` ### Response Example ```typescript // 'safe' ``` ``` -------------------------------- ### HppxOptions interface Source: https://github.com/hiprax/hppx Configuration interface extending SanitizeOptions. Includes sources, checkBodyContentType, excludePaths, strict, onPollutionDetected, logger, and logPollution. ```typescript export interface HppxOptions extends SanitizeOptions { sources?: RequestSource[]; checkBodyContentType?: "urlencoded" | "any" | "none"; excludePaths?: string[]; strict?: boolean; onPollutionDetected?: ( req: Record, info: { source: RequestSource; pollutedKeys: string[] }, ) => void; logger?: (err: Error | unknown) => void; logPollution?: boolean; } ``` -------------------------------- ### Strict-mode 400 response JSON Source: https://github.com/hiprax/hppx Returned by the middleware when strict: true detects HTTP Parameter Pollution. The response includes the error message, the polluted parameters (e.g., query.x), and the code HPP_DETECTED. ```json { "error": "Bad Request", "message": "HTTP Parameter Pollution detected", "pollutedParameters": ["query.x"], "code": "HPP_DETECTED" } ``` -------------------------------- ### sanitize(input, options?) Source: https://github.com/hiprax/hppx Standalone sanitizer that applies the same reduction/cleaning rules as the middleware factory but operates on a plain object directly. It returns only the cleaned object, not the internal SanitizedResult shape. ```APIDOC ## sanitize(input, options?) ### Description Standalone sanitizer that applies the same reduction/cleaning rules as the middleware factory but operates on a plain object directly. It returns only the cleaned object, not the internal SanitizedResult shape. ### Import ```js import { sanitize } from "hppx" ``` ```js const { sanitize } = require("hppx") ``` ### Parameters - **input** (object) - Required - The plain object to sanitize. - **options** (object) - Optional - Options for the sanitizer. ### Returns - **cleaned object** (object) - The sanitized object, without the internal `SanitizedResult` shape. ``` -------------------------------- ### __resetPathSegmentCache Source: https://github.com/hiprax/hppx Named function (test-only) that resets the internal path segment cache. Not intended for production use. ```APIDOC ## __resetPathSegmentCache ### Description Named function (test-only) that resets the internal path segment cache. Not intended for production use. ### Method N/A (function) ### Endpoint N/A ### Parameters None ### Response No return value. ### Request Example ```typescript import { __resetPathSegmentCache } from 'hppx'; __resetPathSegmentCache(); ``` ### Response Example ```typescript // No output ``` ``` -------------------------------- ### hppx(options?) Source: https://github.com/hiprax/hppx Factory function that creates an Express-compatible middleware for HTTP Parameter Pollution protection. It sanitizes req.query, req.body, and req.params, blocks prototype-pollution keys, and exposes original polluted values on req. ```APIDOC ## hppx(options?) ### Description Creates an Express-compatible middleware for HTTP Parameter Pollution (HPP) protection. It sanitizes `req.query`, `req.body`, and `req.params`, blocks prototype-pollution keys, and exposes original polluted values on `req` as `req.queryPolluted` / `req.bodyPolluted` / `req.paramsPolluted`. ### Method Factory function (returns middleware) ### Signature ```typescript export default function hppx(options: HppxOptions = {}): (req: any, res: any, next: ExpressLikeNext) => void ``` ### Parameters - `options` (HppxOptions) - Optional - Middleware configuration. Defaults to `{}`. ### Return Returns an Express-compatible middleware function with signature `(req, res, next) => void`. It calls `next()` to continue, `next(error)` to forward errors, and short-circuits with `res.status(400).json(...)` when `strict: true` and pollution is detected. ### Throws - `TypeError` - Thrown synchronously at middleware creation time when an option is invalid. ### Behavior Notes - Validation runs once at construction; `sources` and `excludePaths` are snapshotted into frozen arrays. - Sources must be one of `"query" | "body" | "params"`. - Excluded paths (exact or `*`-suffixed prefix) call `next()` untouched. - Processing order: `query`, then `body`, then `params`. - Body processing is skipped based on `checkBodyContentType` and Content-Type. - Sets a tamper-resistant flag `__hppxProcessed_` to support stacked middleware. - Errors are logged (if `logger` set) and forwarded via `next(error)`. ``` -------------------------------- ### sanitize() Function Source: https://github.com/hiprax/hppx/blob/main/README.md Sanitizes an object against HTTP Parameter Pollution. Returns a SanitizedResult containing the cleaned object, polluted tree, and polluted keys. ```APIDOC ## sanitize(input, options?) ### Description Sanitizes an object against HTTP Parameter Pollution. Returns a SanitizedResult containing the cleaned object, polluted tree, and polluted keys. ### Parameters - **input** (object) - Required - The object to sanitize. - **options** (SanitizeOptions) - Optional - Options for sanitization. ### Returns SanitizedResult: { cleaned, pollutedTree, pollutedKeys } ``` -------------------------------- ### DEFAULT_STRATEGY Source: https://github.com/hiprax/hppx The default merge strategy used when neither hppx() nor sanitize() supplies one. It is a MergeStrategy value. ```APIDOC ## DEFAULT_STRATEGY ### Description The default merge strategy used when neither hppx() nor sanitize() supplies one. It is a MergeStrategy value. ### Type `MergeStrategy = "keepFirst" | "keepLast" | "combine"` ### Example ```typescript import { DEFAULT_STRATEGY, sanitize } from "hppx"; // Equivalent to sanitize({ q: ["1", "2"] }) — resolves to keepLast const clean = sanitize({ q: ["1", "2"] }, { mergeStrategy: DEFAULT_STRATEGY }); // clean.q === "2" ``` ``` -------------------------------- ### Import hppx TypeScript types Source: https://github.com/hiprax/hppx/blob/main/README.md Imports the exported types for ESM and CommonJS consumers. CommonJS projects on TypeScript 7 need hppx 0.5.0 or later; earlier declarations failed named imports like `import { sanitize } from "hppx"`. ```typescript import type { RequestSource, // "query" | "body" | "params" MergeStrategy, // "keepFirst" | "keepLast" | "combine" SanitizeOptions, // Options for sanitize() HppxOptions, // Full middleware options (extends SanitizeOptions) SanitizedResult, // { cleaned, pollutedTree, pollutedKeys } } from "hppx"; ``` -------------------------------- ### Process JSON bodies with checkBodyContentType Source: https://github.com/hiprax/hppx/blob/main/README.md Use `express.json()` before `hppx({ checkBodyContentType: "any" })` to also process JSON request bodies. ```typescript app.use(express.json()); app.use(hppx({ checkBodyContentType: "any" })); ``` -------------------------------- ### hppx (default export) Source: https://github.com/hiprax/hppx Middleware factory function that creates Express middleware to sanitize request query, body, and params against prototype pollution. It returns an Express middleware function. ```APIDOC ## hppx (default export) ### Description Middleware factory function that creates Express middleware to sanitize request query, body, and params against prototype pollution. It returns an Express middleware function. ### Method N/A (function) ### Endpoint N/A ### Parameters #### Options (HppxOptions) - **sources** (RequestSource[]) - Optional - List of request sources to sanitize (e.g., 'query', 'body', 'params'). - **strategy** (MergeStrategy) - Optional - Merge strategy for handling polluted keys. - **whitelist** (string[]) - Optional - Paths to whitelist from sanitization. - **sanitize** (SanitizeOptions) - Optional - Options for sanitization behavior. ### Response Returns an Express middleware function. ### Request Example ```typescript import hppx from 'hppx'; const middleware = hppx({ sources: ['query', 'body'], strategy: 'safe' }); ``` ### Response Example ```typescript // Returns a middleware function (req, res, next) => void ``` ``` -------------------------------- ### hppx factory function signature Source: https://github.com/hiprax/hppx Default export of the hppx package. Accepts optional HppxOptions and returns an Express-compatible middleware function. ```typescript export default function hppx(options: HppxOptions = {}) { ``` -------------------------------- ### DEFAULT_SOURCES definition Source: https://github.com/hiprax/hppx Definition of DEFAULT_SOURCES as an array of RequestSource values. Used as the default for the sources option when hppx() is called without one. ```typescript const DEFAULT_SOURCES: RequestSource[] = ["query", "body", "params"]; ``` -------------------------------- ### hppx(options) Source: https://github.com/hiprax/hppx The default export middleware factory. Accepts an HppxOptions object as its sole parameter and returns an HTTP middleware that sanitizes request sources (query, body, params) against prototype pollution. ```APIDOC ## hppx(options) ### Description The default export middleware factory. Accepts an `HppxOptions` object as its sole parameter and returns an HTTP middleware that sanitizes request sources (query, body, params) against prototype pollution. ### Parameters #### Options (HppxOptions) - **sources** (`RequestSource[]`) - Optional - Default: `["query", "body", "params"]` - Which request parts to sanitize; each entry must be `"query" | "body" | "params"`. - **checkBodyContentType** (`"urlencoded" | "any" | "none"`) - Optional - Default: `"urlencoded"` - When to process `req.body`. `urlencoded` → only `application/x-www-form-urlencoded` bodies; `any` → all content types; `none` → never. - **excludePaths** (`string[]`) - Optional - Default: `[]` - Paths excluded from sanitization; supports a `*` wildcard **suffix** (`"/assets*"` matches any path prefixed by `"/assets"`). - **strict** (`boolean`) - Optional - Default: `false` - When `true` and pollution is detected, immediately respond `400` (see [index.md](api-reference/index.md) for body shape). - **onPollutionDetected** (`(req, info) => void`) - Optional - Default: — - Called **once per polluted source**. `info = { source: RequestSource, pollutedKeys: string[] }`. Invoked only when the post-restoration polluted tree for that source is non-empty; errors in the callback are ignored. - **logger** (`(err: Error | unknown) => void`) - Optional - Default: — - Receives `string` pollution warnings and `Error` caught errors; falls back to `console.warn` / `console.error` if the logger throws. - **logPollution** (`boolean`) - Optional - Default: `true` - Enable automatic logging (`console.warn` or `logger`) when pollution is detected. ### Notes - Inherits every field of `SanitizeOptions`. ``` -------------------------------- ### Enable strict mode to respond 400 on pollution Source: https://github.com/hiprax/hppx/blob/main/README.md When `strict: true`, polluted requests receive a 400 response with the shown JSON body. The response includes `error`, `message`, `pollutedParameters`, and `code` fields. ```typescript app.use(hppx({ strict: true })); // Polluted requests receive: // { // "error": "Bad Request", // "message": "HTTP Parameter Pollution detected", // "pollutedParameters": ["query.x"], // "code": "HPP_DETECTED" // } ``` -------------------------------- ### sanitize(input, options) Source: https://github.com/hiprax/hppx Sanitizes a plain object by reducing duplicate/array parameters according to a merge strategy, removing dangerous keys, preserving whitelisted keys as arrays, and optionally trimming strings. Returns a new object with the same shape as the input. ```APIDOC ## sanitize(input, options) ### Description Sanitizes a plain object by reducing duplicate/array parameters according to a merge strategy, removing dangerous keys, preserving whitelisted keys as arrays, and optionally trimming strings. Returns a new object with the same shape as the input. ### Signature ```typescript export function sanitize>( input: T, options: SanitizeOptions = {}, ): T ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `input` | `T extends Record` | yes | — | A plain object to sanitize (e.g. a parsed payload). Non-plain objects pass through unchanged in other cases; see Behavior notes. | | `options` | [`SanitizeOptions`](../types.md#sanitizeoptions) | no | `{}` | Only `SanitizeOptions` are honored. Middleware-only options are silently ignored (see note). | ### Return type `T` — a new object with the same shape, with duplicate/array parameters reduced according to the chosen `mergeStrategy`, dangerous keys removed, whitelisted keys preserved as arrays, and (optionally) strings trimmed. ### Throws | Error type | Condition | |-----------|-----------| | `TypeError` | Invalid `options` (delegates to `validateSanitizeOptions`, `src/index.ts:939`). | | `Error` (`Maximum object depth (N) exceeded`) | Input nesting exceeds `maxDepth` (`expandObjectPaths` / `safeDeepClone`, `src/index.ts:382`, `src/index.ts:544`). | | `Error` (`Maximum key count (N) exceeded`) | Input key count exceeds `maxKeys` (`src/index.ts:877`). | | `RangeError` (propagated) | A cycle planted in the polluted tree by other in-process code surfaces during whitelist restoration (`trimStringsDeep` / `moveWhitelistedFromPolluted`). | Error messages and exact trigger conditions are catalogued in [errors.md](../errors.md). ### Behavior notes (evidence from source, `src/index.ts:898-935`) 1. **Validation first:** `validateSanitizeOptions(options)` runs and throws `TypeError` on invalid values. 2. **Key expansion:** if `input` is a plain object, `expandObjectPaths` (`src/index.ts:373`) converts dotted/bracketed keys (`a[b][c]`, `a.b.c`) into nested objects using `maxKeyLength` (default `200`) and `maxDepth` (default `20`). Keys whose expansion would create a `$`-prefixed segment are dropped (`hasOperatorSegment`, `src/index.ts:369`). 3. **Defaults:** `mergeStrategy = DEFAULT_STRATEGY` (`"keepLast"`), `maxDepth = 20`, `maxKeys = 5000`, `maxArrayLength = 1000`, `trimValues = false`, `preserveNull = true` (`src/index.ts:911-918`). 4. **Reduction & detection:** `detectAndReduce` (`src/index.ts:782`) deep-clones via `safeDeepClone`, truncates arrays to `maxArrayLength`, reduces arrays per strategy, and collects a polluted tree + polluted key paths. `cleaned` and `pollutedTree` are **taken** from this result; `pollutedKeys` is discarded — `sanitize()` returns only `cleaned`. 5. **Whitelist restore:** `moveWhitelistedFromPolluted` (`src/index.ts:750`) moves whitelisted entries from the polluted tree back into the cleaned object (trimmed when `trimValues` is on), then returns the cleaned object. ### Note — middleware-only options ignored Only `SanitizeOptions` fields — `whitelist`, `mergeStrategy`, `maxDepth`, `maxKeys`, `maxArrayLength`, `maxKeyLength`, `trimValues`, `preserveNull` — are read. The middleware-only options (`sources`, `excludePaths`, `strict`, `onPollutionDetected`, `logger`, `logPollution`, `checkBodyContentType`) are silently ignored if passed to `sanitize()`. Use the default export `hppx()` for those features. ### Request Example ```typescript import { sanitize } from "hppx"; const payload = { q: ["red", "green", "blue"], // duplicate parameter -> reduced by keepLast "__proto__": { injected: true }, // blocked dangerous key -> dropped tags: ["a", "b"], // whitelisted -> preserved as array }; const clean = sanitize(payload, { whitelist: ["tags"], mergeStrategy: "keepLast", }); // clean.q === "blue" // clean.tags === ["a", "b"] // "__proto__" is absent from clean ``` ### Request Example ```typescript import { sanitize } from "hppx"; // keepFirst + trim + preserveNull=false + tight limits try { const clean = sanitize( { user: { name: " alice ", roles: null }, list: [1, 2, 3] }, { mergeStrategy: "keepFirst", trimValues: true, preserveNull: false, maxKeyLength: 50, maxArrayLength: 2, }, ); // clean.user.name === "alice" (trimmed) // "roles" key dropped (null removed, preserveNull=false) // clean.list === [1, 2] (truncated to maxArrayLength) } catch (err) { // e.g. a TypeError from invalid options, or // "Maximum object depth (..) exceeded" / "Maximum key count (..) exceeded" console.error(err instanceof Error ? err.message : err); } ``` `sanitize()` is what the `hppx()` middleware calls internally per source after key expansion (`src/index.ts` — the middleware uses `detectAndReduce` directly at `src/index.ts:1179`, but the option-validation and defaults are identical). ``` -------------------------------- ### Request module augmentation Source: https://github.com/hiprax/hppx Augments the Express Request interface with polluted-tree fields for typed access to original multi-value trees. ```APIDOC ## Request module augmentation ### Description Augments the Express Request interface with polluted-tree fields for typed access to original multi-value trees. ### Method N/A (module augmentation) ### Endpoint N/A ### Parameters None ### Response Adds the following properties to the Express Request interface: - `req.queryPolluted` (Record | undefined) - Original (pre-reduction) multi-value tree for `query` polluted keys, non-enumerable. - `req.bodyPolluted` (Record | undefined) - Same for `body`. - `req.paramsPolluted` (Record | undefined) - Same for `params`. ### Request Example ```typescript import express from 'express'; const app = express(); app.use((req, res, next) => { console.log(req.queryPolluted); // typed access next(); }); ``` ### Response Example ```typescript // No direct response; properties are available on the request object. ``` ``` -------------------------------- ### __resetPathSegmentCache signature Source: https://github.com/hiprax/hppx Signature of the test-only function __resetPathSegmentCache that returns void. It resets the internal pathSegmentCache for testing cache eviction. ```typescript export function __resetPathSegmentCache(): void ``` -------------------------------- ### DEFAULT_STRATEGY definition Source: https://github.com/hiprax/hppx Definition of DEFAULT_STRATEGY as the string 'keepLast'. Used as the default mergeStrategy when neither hppx() nor sanitize() supplies one. ```typescript const DEFAULT_STRATEGY: MergeStrategy = "keepLast"; ``` -------------------------------- ### __resetPathSegmentCache Source: https://github.com/hiprax/hppx A test-only function that resets the internal path segment cache. It is marked @internal and should not be used by public callers. ```APIDOC ## __resetPathSegmentCache ### Description A test-only function that resets the internal path segment cache. It is marked @internal and should not be used by public callers. ### Signature ```typescript export function __resetPathSegmentCache(): void ``` ### Return `void` ### Example ```typescript import { __resetPathSegmentCache } from "hppx"; // Only meaningful in tests that need a clean cache between cases: __resetPathSegmentCache(); ``` ``` -------------------------------- ### MergeStrategy type definition Source: https://github.com/hiprax/hppx Defines the merge strategies for handling duplicate or array parameters: keepFirst, keepLast (default), or combine. All strategies still record pollution into the polluted tree, pollutedKeys, and the onPollutionDetected/logPollution signals. ```typescript export type MergeStrategy = "keepFirst" | "keepLast" | "combine"; ```