Add escapeHtml function for HTML context escaping - #1263
Conversation
The escapeString function is used for generic string escaping (likely for embedding JS/JSON string literals in generated code), not for HTML output. Overloading it with HTML escaping would break existing callers that depend on the un-escaped characters passing through. Added a separate escapeHtml function that explicitly escapes HTML-unsafe characters (<, >, &, ') to prevent XSS attacks and HTML injection when embedding user-controlled strings in HTML contexts. Also added comprehensive test coverage for both functions to document the distinction and prevent regressions.
|
Thanks for the tests and the clear intent to separate JSON-escaping from HTML-escaping — that's the right instinct, and the docstring is clear. The problem is this PR only adds Also: there's a stray double-blank-line introduced in To make this portable, please grep for where user-controlled strings are actually interpolated into HTML/script tags in this codebase, and change those call sites to use |
Overview
Add a dedicated
escapeHtmlfunction for escaping strings in HTML contexts, separate from the existingescapeStringfunction.Problem
The previous PR (#1231) modified
escapeStringto escape HTML-unsafe characters, but this could break existing callers that depend on the un-escaped characters passing through (e.g., building strings for JSON parsing or non-HTML contexts).Fix
Added a separate
escapeHtmlfunction that explicitly escapes HTML-unsafe characters (<,>,&,') to prevent XSS attacks and HTML injection. The existingescapeStringfunction remains unchanged for backward compatibility.Testing
Added comprehensive test coverage for both functions:
escapeStringtests verify it still escapes JSON special characters but NOT HTML-unsafe onesescapeHtmltests verify it properly escapes<script>,&,',>to prevent XSSAll 24 tests pass (19 existing + 5 new).
Files Changed
common/src/util/string.ts- Added escapeHtml functioncommon/src/util/__tests__/string.test.ts- Added test coverage for both functionsScope
This change only touches
common/which is an approved contribution area per the Contributing Guide.