Skip to content

Commit

Permalink
fix: better element sanitization
Browse files Browse the repository at this point in the history
  • Loading branch information
natemoo-re committed Dec 16, 2022
1 parent 0db847e commit dbcfad0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
9 changes: 8 additions & 1 deletion packages/astro/src/runtime/server/render/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { extractDirectives, generateHydrateScript } from '../hydration.js';
import { serializeProps } from '../serialize.js';
import { shorthash } from '../shorthash.js';
import { isPromise } from '../util.js';
import { escapeHTML } from '../escape.js';
import {
createAstroComponentInstance,
isAstroComponentFactory,
Expand Down Expand Up @@ -240,7 +241,7 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr
// as a string and the user is responsible for adding a script tag for the component definition.
if (!html && typeof Component === 'string') {
// Sanitize tag name because some people might try to inject attributes 🙄
const Tag = Component.trim().split(/\s+/)[0].trim();
const Tag = sanitizeElementName(Component);
const childSlots = Object.values(children).join('');
const iterable = renderAstroTemplateResult(
await renderTemplate`<${Tag}${internalSpreadAttributes(props)}${markHTMLString(
Expand Down Expand Up @@ -324,6 +325,12 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr
return renderAll();
}

function sanitizeElementName(tag: string) {
const unsafe = /[&<>'"\s]+/g;
if (!unsafe.test(tag)) return tag;
return tag.trim().split(unsafe)[0].trim();
}

async function renderFragmentComponent(result: SSRResult, slots: any = {}) {
const children = await renderSlot(result, slots?.default);
if (children == null) {
Expand Down
8 changes: 6 additions & 2 deletions packages/astro/test/units/render/components.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ describe('core/render components', () => {
{
'/src/pages/index.astro': `
---
const Tag = 'p style=color:red;'
const TagA = 'p style=color:red;'
const TagB = 'p><script id="pwnd">console.log("pwnd")</script>'
---
<html>
<head><title>testing</title></head>
<body>
<Tag id="target" />
<TagA id="target" />
<TagB />
</body>
</html>
`,
Expand Down Expand Up @@ -55,6 +57,8 @@ describe('core/render components', () => {
expect(target).not.to.be.undefined;
expect(target.attr('id')).to.equal('target');
expect(target.attr('style')).to.be.undefined;

expect($('#pwnd').length).to.equal(0);
}
);
});
Expand Down

0 comments on commit dbcfad0

Please sign in to comment.