Security-focused string escaping utilities for HTML, JSON, RegExp, and HTTP header contexts to prevent injection attacks and ensure safe string usage in various contexts.
Escapes string for usage in HTML by converting dangerous characters to their HTML entity equivalents.
/**
* Escape string for usage in HTML
* @param string - The string to be escaped
* @returns The escaped string safe for HTML contexts
*/
function escapeHtml(string: string): string;The following characters are escaped:
& → &< → <> → >" → "' → '` → `Usage Examples:
import { escapeHtml } from "@hapi/hoek";
// Basic HTML escaping
const userInput = '<script>alert("XSS")</script>';
const safe = escapeHtml(userInput);
// Result: '<script>alert("XSS")</script>'
// Escaping quotes and other characters
const mixed = `<div class="test" onclick='alert("click")'>Content & more</div>`;
const escapedMixed = escapeHtml(mixed);
// Result: '<div class="test" onclick='alert("click")'>Content & more</div>'
// Template literals with backticks
const template = '`${userInput}`';
const escapedTemplate = escapeHtml(template);
// Result: '`${userInput}`'
// Safe for HTML insertion
const safeContent = `<p>${escapeHtml(userInput)}</p>`;
// Safely renders the escaped content in HTMLUnicode escapes the characters <, >, and & to prevent MIME-sniffing attacks in older browsers and escapes line/paragraph separators for JSONP and script contexts.
/**
* Escape string for usage in JSON to prevent MIME-sniffing and script injection
* @param string - The string to be escaped
* @returns The escaped string safe for JSON contexts
*/
function escapeJson(string: string): string;Usage Examples:
import { escapeJson } from "@hapi/hoek";
// Prevent MIME-sniffing attacks
const jsonContent = 'I said <script>confirm(&)';
const safeJson = escapeJson(jsonContent);
// Result: 'I said \\u003cscript\\u003econfirm(\\u0026)'
// Line separator escaping for JSONP
const lineSeparator = String.fromCharCode(0x2028);
const paragraphSeparator = String.fromCharCode(0x2029);
const multiLine = `Line 1${lineSeparator}Line 2${paragraphSeparator}Line 3`;
const escapedMultiLine = escapeJson(multiLine);
// Result: 'Line 1\\u2028Line 2\\u2029Line 3'
// Safe for JSONP callbacks
const jsonpData = { message: escapeJson('<script>alert("xss")</script>') };
const jsonpResponse = `callback(${JSON.stringify(jsonpData)})`;
// Safe for script tag insertion
// Mixed dangerous characters
const dangerous = '<div> </div>' + String.fromCharCode(0x2028);
const safeDangerous = escapeJson(dangerous);
// Result: '\\u003cdiv\\u003e \\u003c/div\\u003e\\u2028'Escapes string for RegExp construction by prefixing all reserved RegExp characters with backslashes.
/**
* Escape string for Regex construction by prefixing all reserved characters with a backslash
* @param string - The string to be escaped
* @returns The escaped string safe for RegExp construction
*/
function escapeRegex(string: string): string;Usage Examples:
import { escapeRegex } from "@hapi/hoek";
// Basic regex escaping
const userPattern = '4^f$s.4*5+-_?%=#!:@|~\\/`"(>)[<]d{}s,';
const escapedPattern = escapeRegex(userPattern);
// Result: '4\\^f\\$s\\.4\\*5\\+\\-_\\?%\\=#\\!\\:@\\|~\\\\\\/`"\\(>\\)\\[<\\]d\\{\\}s\\,'
// Use in RegExp construction
const searchTerm = 'user@domain.com';
const escapedTerm = escapeRegex(searchTerm);
const regex = new RegExp(escapedTerm, 'gi');
// Safely matches literal "user@domain.com" instead of treating @ and . as regex metacharacters
// File path escaping
const filePath = 'C:\\Users\\John\\Documents\\file.txt';
const escapedPath = escapeRegex(filePath);
const pathRegex = new RegExp(escapedPath);
// Safely matches the literal file path
// URL escaping for regex
const url = 'https://example.com/path?query=value&other=123';
const escapedUrl = escapeRegex(url);
const urlRegex = new RegExp(`^${escapedUrl}$`);
// Matches the exact URL without treating ? and & as regex metacharacters
// Dynamic pattern building
const buildPattern = (literals: string[]) => {
const escapedLiterals = literals.map(escapeRegex);
return new RegExp(escapedLiterals.join('|'), 'g');
};
const pattern = buildPattern(['$price', '[discount]', '(tax)']);
// Creates regex that matches any of the literal stringsEscapes attribute value for use in HTTP header by escaping quotes and backslashes while validating for unsupported characters.
/**
* Escape string for usage as an attribute value in HTTP headers
* @param attribute - The string to be escaped
* @returns The escaped string safe for HTTP header attributes
* @throws Will throw on invalid characters that cannot be escaped
*/
function escapeHeaderAttribute(attribute: string): string;Usage Examples:
import { escapeHeaderAttribute } from "@hapi/hoek";
// Basic header attribute escaping
const filename = 'I said "go w\\o me"';
const escapedFilename = escapeHeaderAttribute(filename);
// Result: 'I said \\"go w\\\\o me\\"'
// Use in Content-Disposition header
const userFilename = 'report "final".pdf';
const safeFilename = escapeHeaderAttribute(userFilename);
const header = `Content-Disposition: attachment; filename="${safeFilename}"`;
// Result: 'Content-Disposition: attachment; filename="report \\"final\\".pdf"'
// Cache-Control with quoted values
const cacheValue = 'private, max-age=3600, custom="value with quotes"';
const safeCacheValue = escapeHeaderAttribute(cacheValue);
// Safely escapes internal quotes for header usage
// Custom header values
const customValue = 'application/json; charset="utf-8"';
const safeCustomValue = escapeHeaderAttribute(customValue);
// Safe for use in custom headers
// Error handling for invalid characters
try {
const invalidValue = 'value\nwith\nnewlines';
escapeHeaderAttribute(invalidValue); // May throw error
} catch (error) {
console.log('Invalid characters in header value');
}Important Notes:
escapeHtml is essential for preventing XSS attacks when inserting user content into HTMLescapeJson prevents MIME-sniffing attacks and ensures safe JSONP/script embeddingescapeRegex is crucial when building RegExp patterns from user input to prevent ReDoS attacksescapeHeaderAttribute validates input and may throw errors for characters that cannot be safely escaped