Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: improve html escaping of element attributes #11411

Merged
merged 4 commits into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 5 additions & 0 deletions .changeset/young-ads-roll.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"svelte": patch
---

fix: improve html escaping of element attributes
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,7 @@ import {
unwrap_optional
} from '../../../../utils/ast.js';
import { binding_properties } from '../../../bindings.js';
import {
clean_nodes,
determine_namespace_for_children,
escape_html,
infer_namespace
} from '../../utils.js';
import { clean_nodes, determine_namespace_for_children, infer_namespace } from '../../utils.js';
import { DOMProperties, PassiveEvents, VoidElements } from '../../../constants.js';
import { is_custom_element_node, is_element_node } from '../../../nodes.js';
import * as b from '../../../../utils/builders.js';
Expand All @@ -36,7 +31,8 @@ import {
TEMPLATE_USE_IMPORT_NODE,
TRANSITION_GLOBAL,
TRANSITION_IN,
TRANSITION_OUT
TRANSITION_OUT,
escape_html
} from '../../../../../constants.js';
import { regex_is_valid_identifier } from '../../../patterns.js';
import { javascript_visitors_runes } from './javascript-runes.js';
Expand Down Expand Up @@ -1984,7 +1980,7 @@ export const template_visitors = {
` ${attribute.name}${
DOMBooleanAttributes.includes(name) && literal_value === true
? ''
: `="${literal_value === true ? '' : escape_html(String(literal_value), true)}"`
: `="${literal_value === true ? '' : escape_html(literal_value, true)}"`
}`
);
continue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import {
import {
clean_nodes,
determine_namespace_for_children,
escape_html,
infer_namespace,
transform_inspect_rune
} from '../utils.js';
Expand All @@ -27,8 +26,8 @@ import { regex_starts_with_newline, regex_whitespaces_strict } from '../../patte
import {
DOMBooleanAttributes,
HYDRATION_END,
HYDRATION_END_ELSE,
HYDRATION_START
HYDRATION_START,
escape_html
} from '../../../../constants.js';
import { sanitize_template_string } from '../../../utils/sanitize_template_string.js';
import { BLOCK_CLOSE, BLOCK_CLOSE_ELSE } from '../../../../internal/server/hydration.js';
Expand Down
49 changes: 0 additions & 49 deletions packages/svelte/src/compiler/phases/3-transform/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,55 +6,6 @@ import {
import * as b from '../../utils/builders.js';
import { walk } from 'zimmerframe';

/**
* @param {string} s
* @param {boolean} [attr]
*/
export function escape_html(s, attr) {
if (typeof s !== 'string') return s;
const delimiter = attr ? '"' : '<';
const escaped_delimiter = attr ? '&quot;' : '&lt;';
let i_delimiter = s.indexOf(delimiter);
let i_ampersand = s.indexOf('&');

if (i_delimiter < 0 && i_ampersand < 0) return s;

let left = 0,
out = '';

while (i_delimiter >= 0 && i_ampersand >= 0) {
if (i_delimiter < i_ampersand) {
if (left < i_delimiter) out += s.substring(left, i_delimiter);
out += escaped_delimiter;
left = i_delimiter + 1;
i_delimiter = s.indexOf(delimiter, left);
} else {
if (left < i_ampersand) out += s.substring(left, i_ampersand);
out += '&amp;';
left = i_ampersand + 1;
i_ampersand = s.indexOf('&', left);
}
}

if (i_delimiter >= 0) {
do {
if (left < i_delimiter) out += s.substring(left, i_delimiter);
out += escaped_delimiter;
left = i_delimiter + 1;
i_delimiter = s.indexOf(delimiter, left);
} while (i_delimiter >= 0);
} else if (!attr) {
while (i_ampersand >= 0) {
if (left < i_ampersand) out += s.substring(left, i_ampersand);
out += '&amp;';
left = i_ampersand + 1;
i_ampersand = s.indexOf('&', left);
}
}

return left < s.length ? out + s.substring(left) : out;
}

/**
* @param {import('estree').Node} node
* @returns {boolean}
Expand Down
27 changes: 27 additions & 0 deletions packages/svelte/src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -273,3 +273,30 @@ export function is_tag_valid_with_parent(tag, parent_tag) {

return true;
}

const ATTR_REGEX = /["<]/g;
const CONTENT_REGEX = /[&<]/g;

/**
* @template V
* @param {V} value
* @param {boolean} [is_attr]
*/
export function escape_html(value, is_attr) {
trueadm marked this conversation as resolved.
Show resolved Hide resolved
const str = String(value ?? '');

const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX;
pattern.lastIndex = 0;

let escaped = '';
let last = 0;

while (pattern.test(str)) {
const i = pattern.lastIndex - 1;
const ch = str[i];
escaped += str.substring(last, i) + (ch === '&' ? '&amp;' : ch === '"' ? '&quot;' : '&lt;');
last = i + 1;
}

return escaped + str.substring(last);
}
36 changes: 6 additions & 30 deletions packages/svelte/src/internal/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
RawTextElements,
disallowed_paragraph_contents,
interactive_elements,
is_tag_valid_with_parent
is_tag_valid_with_parent,
escape_html
} from '../../constants.js';
import { DEV } from 'esm-env';
import { current_component, pop, push } from './context.js';
Expand Down Expand Up @@ -39,8 +40,6 @@ import { validate_store } from '../shared/validate.js';
* }} Payload
*/

const ATTR_REGEX = /[&"]/g;
const CONTENT_REGEX = /[&<]/g;
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
// https://infra.spec.whatwg.org/#noncharacter
const INVALID_ATTR_NAME_CHAR_REGEX =
Expand Down Expand Up @@ -214,31 +213,6 @@ export function render(component, options) {
};
}

/**
* @template V
* @param {V} value
* @param {any} is_attr
* @returns {string}
*/
export function escape(value, is_attr = false) {
const str = String(value ?? '');

const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX;
pattern.lastIndex = 0;

let escaped = '';
let last = 0;

while (pattern.test(str)) {
const i = pattern.lastIndex - 1;
const ch = str[i];
escaped += str.substring(last, i) + (ch === '&' ? '&amp;' : ch === '"' ? '&quot;' : '&lt;');
last = i + 1;
}

return escaped + str.substring(last);
}

/**
* @param {Payload} payload
* @param {(head_payload: Payload['head']) => void} fn
Expand All @@ -260,7 +234,7 @@ export function head(payload, fn) {
*/
export function attr(name, value, boolean) {
if (value == null || (!value && boolean) || (value === '' && name === 'class')) return '';
const assignment = boolean ? '' : `="${escape(value, true)}"`;
const assignment = boolean ? '' : `="${escape_html(value, true)}"`;
return ` ${name}${assignment}`;
}

Expand Down Expand Up @@ -381,7 +355,7 @@ export function stringify(value) {
function style_object_to_string(style_object) {
return Object.keys(style_object)
.filter(/** @param {any} key */ (key) => style_object[key])
.map(/** @param {any} key */ (key) => `${key}: ${escape(style_object[key], true)};`)
.map(/** @param {any} key */ (key) => `${key}: ${escape_html(style_object[key], true)};`)
.join(' ');
}

Expand Down Expand Up @@ -654,3 +628,5 @@ export {
validate_snippet,
validate_void_dynamic_element
} from '../shared/validate.js';

export { escape_html as escape };
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { test } from '../../test';

export default test({
test({ assert, logs }) {
assert.deepEqual(logs, []);
trueadm marked this conversation as resolved.
Show resolved Hide resolved
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<script>
const x = `</noscript><script>console.log('should not run')<` + `/script>`
</script>

<noscript>
<a href={x}>test</a>
</noscript>

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { test } from '../../test';

export default test({
test({ assert, logs }) {
assert.deepEqual(logs, []);
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<noscript>
<a href="</noscript><script>console.log('should not run')</script>">test</a>
</noscript>

2 changes: 1 addition & 1 deletion playgrounds/sandbox/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ for (const generate of ['client', 'server']) {

try {
const migrated = migrate(source);
fs.writeFileSync(`${cwd}/output/${file}.migrated.svelte`, migrated);
fs.writeFileSync(`${cwd}/output/${file}.migrated.svelte`, migrated.code);
Conduitry marked this conversation as resolved.
Show resolved Hide resolved
} catch (e) {
console.warn(`Error migrating ${file}`, e);
}
Expand Down
Loading