Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,17 @@ export function patchHostValidationMiddleware(middlewares: Connect.Server): void
};
}

function escapeHtml(value: string): string {
return value
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
Comment on lines +45 to +51

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current implementation of escapeHtml uses multiple chained .replace calls with regular expressions, which results in multiple string allocations and full-string scans. Additionally, it does not escape the single quote ('), which is a standard HTML entity that should be escaped to prevent potential XSS vulnerabilities in attribute contexts.

Using a single regular expression with a character class and a map lookup is more efficient and allows us to easily include the single quote (') in the escaped characters.

function escapeHtml(value: string): string {
  const entityMap: Record<string, string> = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;',
  };
  return value.replace(/[&<>"']/g, (s) => entityMap[s]);
}


function html403(hostname: string): string {
const safeHostname = escapeHtml(hostname);

return `<!doctype html>
<html>
<head>
Expand All @@ -61,12 +71,12 @@ function html403(hostname: string): string {
</head>
<body>
<main>
<h1>Blocked request. This host ("${hostname}") is not allowed.</h1>
<h1>Blocked request. This host ("${safeHostname}") is not allowed.</h1>
<p>To allow this host, add it to <code>allowedHosts</code> under the <code>serve</code> target in <code>angular.json</code>.</p>
<pre><code>{
"serve": {
"options": {
"allowedHosts": ["${hostname}"]
"allowedHosts": ["${safeHostname}"]
}
}
}</code></pre>
Expand Down
Loading