Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

fix(security): close SVG preview sanitizer bypasses and icon attribute injection

hugohe3514596e51a28
diff --git a/skills/ppt-master/scripts/svg_editor/static/app.js b/skills/ppt-master/scripts/svg_editor/static/app.js
index e06bcc64..e13226d0 100644
--- a/skills/ppt-master/scripts/svg_editor/static/app.js
+++ b/skills/ppt-master/scripts/svg_editor/static/app.js
@@ -732,10 +732,11 @@
waitForSlideRewrite(name);
return;
}
- // Render SVG
+ // Validate before showing the canvas; parse errors use the catch below.
+ var sanitizedSvg = sanitizeSvg(data.content);
svgPlaceholder.style.display = "none";
svgContent.style.display = "block";
- svgContent.innerHTML = sanitizeSvg(data.content);
+ svgContent.innerHTML = sanitizedSvg;
// Empty-canvas guard: surface a clear error if the SVG parsed
// to nothing renderable (issue #115's silent-blank scenario).
@@ -1849,13 +1850,30 @@
// ================================================================
function sanitizeSvg(svgString) {
var doc = new DOMParser().parseFromString(svgString, "image/svg+xml");
- doc.querySelectorAll("script,foreignObject").forEach(function (el) { el.remove(); });
+ if (doc.getElementsByTagName("parsererror").length ||
+ !doc.documentElement || doc.documentElement.localName.toLowerCase() !== "svg") {
+ throw new Error(t("err_empty_svg"));
+ }
doc.querySelectorAll("*").forEach(function (el) {
+ // XML preserves case; the innerHTML sink normalizes HTML/SVG names.
+ var tag = el.localName.toLowerCase();
+ if (tag === "script" || tag === "foreignobject" ||
+ (el.namespaceURI && el.namespaceURI !== "http://www.w3.org/2000/svg" &&
+ el.namespaceURI !== "http://www.w3.org/1999/xlink")) {
+ el.remove();
+ return;
+ }
Array.from(el.attributes).forEach(function (attr) {
- if (attr.name.indexOf("on") === 0) el.removeAttribute(attr.name);
+ var name = attr.name.toLowerCase();
+ var local = attr.localName.toLowerCase();
+ if (local.indexOf("on") === 0 || name.indexOf("on") === 0) {
+ el.removeAttributeNode(attr);
+ return;
+ }
// Strip dangerous URI protocols from href/xlink:href
- if (attr.localName === "href" &&
+ if (local === "href" &&
(/^\s*javascript\s*:/i.test(attr.value) ||
+ /^\s*vbscript\s*:/i.test(attr.value) ||
/^\s*data\s*:/i.test(attr.value))) {
el.removeAttributeNode(attr);
}
diff --git a/skills/ppt-master/scripts/svg_editor/static/index.html b/skills/ppt-master/scripts/svg_editor/static/index.html
index e7bb82e3..a6e77227 100644
--- a/skills/ppt-master/scripts/svg_editor/static/index.html
+++ b/skills/ppt-master/scripts/svg_editor/static/index.html
@@ -2,6 +2,8 @@
<html lang="en">
<head>
<meta charset="UTF-8">
+ <meta http-equiv="Content-Security-Policy"
+ content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="page_title">PPT Master - Live Preview</title>
<link rel="stylesheet" href="/static/style.css">
diff --git a/skills/ppt-master/scripts/svg_finalize/embed_icons.py b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
index bc49c7cf..519a8067 100644
--- a/skills/ppt-master/scripts/svg_finalize/embed_icons.py
+++ b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
@@ -42,10 +42,11 @@ Options:
from __future__ import annotations
+import argparse
+import html
import os
import re
import sys
-import argparse
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit
@@ -72,10 +73,37 @@ ICON_BASE_SIZES = {
_ICON_IDENTIFIER_RE = re.compile(
r'(?P<library>[a-z0-9][a-z0-9-]*)/(?P<name>[A-Za-z0-9][A-Za-z0-9._-]*)'
)
+_ICON_COLOR_RE = re.compile(
+ r'#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})'
+ r'|[a-z]+|(?:rgba?|hsla?)\([0-9\s.,%]+\)',
+ re.IGNORECASE | re.ASCII,
+)
+_NUMBER_PATTERN = r'[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?'
+_TRANSFORM_FUNCTION_PATTERN = (
+ rf'(?:matrix|translate|scale|rotate|skewX|skewY)\(\s*{_NUMBER_PATTERN}'
+ rf'(?:(?:\s*,\s*|\s+){_NUMBER_PATTERN})*\s*\)'
+)
+_ICON_TRANSFORM_RE = re.compile(
+ rf'{_TRANSFORM_FUNCTION_PATTERN}(?:\s*,?\s*{_TRANSFORM_FUNCTION_PATTERN})*',
+ re.ASCII,
+)
+_ICON_STROKE_WIDTH_RE = re.compile(rf'{_NUMBER_PATTERN}(?:px|em|%)?')
DEFAULT_ICON_BASE_SIZE = 24
BaseGeometry = float | tuple[float, float, float, float]
+def _xml_attr(value: object) -> str:
+ """Escape a value for insertion into a quoted SVG attribute."""
+ return html.escape(str(value), quote=True)
+
+
+def _validate_icon_attr(value: str, attr: str, pattern: re.Pattern[str]) -> str:
+ """Reject unsafe icon attributes while preserving legal source spelling."""
+ if pattern.fullmatch(value.strip()) is None:
+ raise ValueError(f'Invalid icon {attr}: {value!r}; use a plain SVG {attr} value')
+ return value
+
+
def _get_viewbox_size(content: str) -> float:
"""Extract the width from viewBox attribute (assumed square). Returns 0 if not found."""
m = re.search(r'viewBox=["\']0 0 ([\d.]+)', content)
@@ -305,7 +333,7 @@ def extract_paths_from_icon(
def _attr_value(tag_text: str, attr: str) -> str | None:
"""Return an attribute value from a raw tag, accepting either quote style."""
match = re.search(
- rf'\b{re.escape(attr)}\s*=\s*(["\'])(.*?)\1',
+ rf'(?<!\S){re.escape(attr)}\s*=\s*(["\'])(.*?)\1',
tag_text,
re.DOTALL,
)
@@ -338,27 +366,27 @@ def parse_use_element(use_match: str) -> dict[str, str | float]:
# Extract fill color
fill_value = _attr_value(use_match, 'fill')
if fill_value is not None:
- attrs['fill'] = fill_value
+ attrs['fill'] = _validate_icon_attr(fill_value, 'fill', _ICON_COLOR_RE)
# Stroke-style icons may be authored with natural SVG semantics:
# fill="none" stroke="#HEX". Keep accepting fill as the canonical color
# carrier, but preserve stroke so outline icons do not collapse to none.
stroke_value = _attr_value(use_match, 'stroke')
if stroke_value is not None:
- attrs['stroke'] = stroke_value
+ attrs['stroke'] = _validate_icon_attr(stroke_value, 'stroke', _ICON_COLOR_RE)
# Live preview direct edits may write an absolute transform matrix back to
# the placeholder. Preserve it so the expanded icon matches the edited
# browser geometry instead of falling back to the original x/y placement.
transform_value = _attr_value(use_match, 'transform')
if transform_value is not None:
- attrs['transform'] = transform_value
+ attrs['transform'] = _validate_icon_attr(transform_value, 'transform', _ICON_TRANSFORM_RE)
# Extract optional stroke-width override (stroke-style icons only).
# Tabler-outline ships at stroke-width=2; passing 1.5 reads thin, 3 reads bold.
stroke_width_value = _attr_value(use_match, 'stroke-width')
if stroke_width_value is not None:
- attrs['stroke-width'] = stroke_width_value
+ attrs['stroke-width'] = _validate_icon_attr(stroke_width_value, 'stroke-width', _ICON_STROKE_WIDTH_RE)
return attrs
@@ -370,6 +398,10 @@ def resolve_icon_color(attrs: dict[str, str | float], style: str) -> str:
fill = str(attrs.get('fill', '')).strip()
stroke = str(attrs.get('stroke', '')).strip()
+ if fill:
+ _validate_icon_attr(fill, 'fill', _ICON_COLOR_RE)
+ if stroke:
+ _validate_icon_attr(stroke, 'stroke', _ICON_COLOR_RE)
if style == 'stroke':
if fill and fill != 'none':
@@ -428,9 +460,9 @@ def generate_icon_group(attrs: dict[str, str | float], elements: list[str], styl
if style == 'preserve':
if min_x or min_y:
inner_transform = f'translate({_format_number(-min_x)}, {_format_number(-min_y)})'
- elements_str = f'<g transform="{inner_transform}">\n {elements_str}\n </g>'
- return f'''<!-- icon: {icon_name} -->
- <g transform="{transform}">
+ elements_str = f'<g transform="{_xml_attr(inner_transform)}">\n {elements_str}\n </g>'
+ return f'''<!-- icon: {_xml_attr(icon_name)} -->
+ <g transform="{_xml_attr(transform)}">
{elements_str}
</g>'''
@@ -439,12 +471,12 @@ def generate_icon_group(attrs: dict[str, str | float], elements: list[str], styl
# (and any other stroke library) so omitting the attribute reproduces
# pre-change visual output.
stroke_width = attrs.get('stroke-width', '2')
- color_attrs = f'fill="none" stroke="{color}" stroke-width="{stroke_width}"'
+ color_attrs = f'fill="none" stroke="{_xml_attr(color)}" stroke-width="{_xml_attr(stroke_width)}"'
else:
- color_attrs = f'fill="{color}"'
+ color_attrs = f'fill="{_xml_attr(color)}"'
- return f'''<!-- icon: {icon_name} -->
- <g transform="{transform}" {color_attrs}>
+ return f'''<!-- icon: {_xml_attr(icon_name)} -->
+ <g transform="{_xml_attr(transform)}" {color_attrs}>
{elements_str}
</g>'''
diff --git a/skills/ppt-master/scripts/tests/test_embed_icons.py b/skills/ppt-master/scripts/tests/test_embed_icons.py
new file mode 100644
index 00000000..8ff7d1c2
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_embed_icons.py
@@ -0,0 +1,122 @@
+#!/usr/bin/env python3
+"""Regression tests for icon attribute validation and SVG markup escaping."""
+
+import sys
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+from xml.etree import ElementTree as ET
+
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+from svg_finalize.embed_icons import ( # noqa: E402
+ generate_icon_group,
+ parse_use_element,
+ process_svg_file,
+ resolve_icon_color,
+)
+
+
+class IconAttributeSecurityTests(unittest.TestCase):
+ def test_rejects_single_quoted_transform_injection_before_write(self) -> None:
+ source = (
+ '<svg xmlns="http://www.w3.org/2000/svg">'
+ '<use data-icon="chunk-filled/rocket" '
+ 'transform=\'translate(10, 10)" ONMOUSEOVER="alert(1)\'/></svg>'
+ )
+ with self.assertRaisesRegex(ValueError, 'Invalid icon transform'):
+ parse_use_element(source)
+ with patch.object(Path, 'exists', return_value=True), \
+ patch.object(Path, 'read_text', return_value=source), \
+ patch.object(Path, 'write_text') as write:
+ with self.assertRaisesRegex(ValueError, 'Invalid icon transform'):
+ process_svg_file(Path('/unused/svg_output/01.svg'), Path('/unused/icons'))
+ write.assert_not_called()
+
+ def test_direct_generation_escapes_attribute_boundaries(self) -> None:
+ payload = 'translate(10, 10)" ONMOUSEOVER="alert(1)'
+ for style, attribute in (
+ ('fill', 'transform'), ('stroke', 'transform'),
+ ('preserve', 'transform'), ('stroke', 'stroke-width'),
+ ):
+ with self.subTest(style=style, attribute=attribute):
+ attrs = {'icon': 'chunk-filled/rocket', 'fill': '#000000', attribute: payload}
+ output = generate_icon_group(attrs, ['<path d="M0 0h1v1z"/>'], style, (1, 2, 16, 16))
+ group = ET.fromstring(output)
+ self.assertEqual(group.get(attribute), payload)
+ self.assertNotIn('" ONMOUSEOVER=', output)
+ self.assertFalse(any(
+ name.lower().startswith('on')
+ for element in group.iter() for name in element.attrib
+ ))
+
+ def test_legal_transforms_remain_authoritative(self) -> None:
+ for transform in (
+ 'translate(10, 10)',
+ 'matrix(1 0 0 1 10 20)',
+ 'matrix(1, 0, 0, 1, -1e2, .5)',
+ 'translate(-10, +.5) scale(2) rotate(45, 10, 20) skewX(5) skewY(-5)',
+ ):
+ with self.subTest(transform=transform):
+ attrs = parse_use_element(
+ '<use data-icon="chunk-filled/rocket" x="99" y="88" width="48" '
+ f"transform='{transform}'/>"
+ )
+ group = ET.fromstring(generate_icon_group(attrs, ['<path d="M0 0h1"/>'], 'fill', 16))
+ self.assertEqual(attrs['transform'], transform)
+ self.assertEqual(group.get('transform'), transform)
+
+ def test_legal_colors(self) -> None:
+ for color in (
+ '#abc', '#abcd', '#123ABC', '#123ABC80', 'none', 'currentColor',
+ 'rebeccapurple', 'rgb(255, 0, 10)', 'rgba(100%, 0%, 20%, .5)',
+ 'hsl(120, 50%, 40%)', 'hsla(120, 50%, 40%, .5)',
+ ):
+ with self.subTest(color=color):
+ attrs = parse_use_element(f'<use data-icon="chunk-filled/rocket" fill="{color}"/>')
+ self.assertEqual(resolve_icon_color(attrs, 'fill'), color)
+ group = ET.fromstring(generate_icon_group(attrs, ['<path d="M0 0h1"/>'], 'fill', 16))
+ self.assertEqual(group.get('fill'), color)
+
+ def test_outline_colors_and_stroke_width_units(self) -> None:
+ for width in ('0', '2', '1.5', '.5px', '0.1em', '10%'):
+ with self.subTest(width=width):
+ attrs = parse_use_element(
+ '<use data-icon="tabler-outline/home" fill="none" '
+ f'stroke="currentColor" stroke-width="{width}"/>'
+ )
+ self.assertNotIn('width', attrs)
+ group = ET.fromstring(generate_icon_group(attrs, ['<path d="M0 0h1"/>'], 'stroke', 24))
+ self.assertEqual(group.get('fill'), 'none')
+ self.assertEqual(group.get('stroke'), 'currentColor')
+ self.assertEqual(group.get('stroke-width'), width)
+
+ def test_rejects_unsafe_attribute_grammars(self) -> None:
+ for attribute, value in (
+ ('fill', '#12'), ('fill', '#12345'), ('fill', '#1234567'),
+ ('fill', 'url(#gradient)'), ('stroke', 'url(https://example.invalid/x)'),
+ ('fill', '#fff" ONMOUSEOVER="alert(1)'),
+ ('stroke', '#fff" ONMOUSEOVER="alert(1)'),
+ ('fill', 'rgb(1, 2, expression(alert(1)))'),
+ ('transform', 'translate(10, 10);alert(1)'),
+ ('transform', 'matrix(1 0 0 1 NaN 0)'), ('transform', 'rotate()'),
+ ('transform', 'translate(1,,2)'), ('transform', 'translate(1.2.3)'),
+ ('stroke-width', '2" ONMOUSEOVER="alert(1)'),
+ ('stroke-width', 'calc(1px + 2px)'), ('stroke-width', '2pt'),
+ ):
+ with self.subTest(attribute=attribute, value=value):
+ with self.assertRaisesRegex(ValueError, f'Invalid icon {attribute}'):
+ parse_use_element(f'<use data-icon="chunk-filled/rocket" {attribute}=\'{value}\'/>')
+
+ def test_direct_color_resolution_rejects_unsafe_values(self) -> None:
+ for style in ('fill', 'stroke'):
+ for attribute in ('fill', 'stroke'):
+ with self.subTest(style=style, attribute=attribute):
+ attrs = {attribute: '#fff" ONMOUSEOVER="alert(1)'}
+ with self.assertRaisesRegex(ValueError, f'Invalid icon {attribute}'):
+ resolve_icon_color(attrs, style)
+ with self.assertRaisesRegex(ValueError, f'Invalid icon {attribute}'):
+ generate_icon_group(attrs, ['<path d="M0 0h1"/>'], style, 16)
diff --git a/skills/ppt-master/scripts/tests/test_native_export_guards.py b/skills/ppt-master/scripts/tests/test_native_export_guards.py
index 3207b0cb..d8100127 100644
--- a/skills/ppt-master/scripts/tests/test_native_export_guards.py
+++ b/skills/ppt-master/scripts/tests/test_native_export_guards.py
@@ -15,7 +15,8 @@ from xml.etree import ElementTree as ET
SCRIPTS_DIR = Path(__file__).resolve().parents[1]
-if str(SCRIPTS_DIR) not in sys.path:
+# Discovery may put svg_to_pptx/ ahead of the same-named animation_config CLI.
+if not sys.path or sys.path[0] != str(SCRIPTS_DIR):
sys.path.insert(0, str(SCRIPTS_DIR))
from pptx_shapes.formula import OOXML_COORDINATE_MAX # noqa: E402