Compare commits

...
3 Commits
Author SHA1 Message Date
ionitron 89cba595a7 8.1.1 2026-11-19 20:46:43 +00:00
Shane 02456263e0 Merge commit from fork 2026-11-19 12:31:02 -08:00
Shane a00f3134a5 chore(release): sync package version with published 8.1.0 release (#1521) 2026-11-19 12:30:04 -08:00
13 changed files with 573 additions and 88 deletions
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "ionicons",
"version": "8.0.13",
"version": "8.1.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "ionicons",
"version": "8.0.13",
"version": "8.1.1",
"license": "MIT",
"dependencies": {
"@stencil/core": "^4.43.5"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "ionicons",
"version": "8.0.13",
"version": "8.1.1",
"description": "Premium icons for Ionic.",
"files": [
"components/",
+2 -2
View File
@@ -42,7 +42,7 @@ export namespace Components {
*/
"name"?: string;
/**
* When set to `false`, SVG content that is HTTP fetched will not be checked if the response SVG content has any `<script>` elements, or any attributes that start with `on`, such as `onclick`.
* When `true`, SVG content, including SVG `data:` URLs, is checked before it renders. SVGs with `<script>` elements, attributes that start with `on` (like `onclick`), `javascript:` URLs, or non-SVG elements aren't rendered, and `<foreignObject>` elements are removed. Only set this to `false` for SVG content from a trusted source.
* @default true
*/
"sanitize": boolean;
@@ -104,7 +104,7 @@ declare namespace LocalJSX {
*/
"name"?: string;
/**
* When set to `false`, SVG content that is HTTP fetched will not be checked if the response SVG content has any `<script>` elements, or any attributes that start with `on`, such as `onclick`.
* When `true`, SVG content, including SVG `data:` URLs, is checked before it renders. SVGs with `<script>` elements, attributes that start with `on` (like `onclick`), `javascript:` URLs, or non-SVG elements aren't rendered, and `<foreignObject>` elements are removed. Only set this to `false` for SVG content from a trusted source.
* @default true
*/
"sanitize"?: boolean;
+10 -7
View File
@@ -1,5 +1,5 @@
import { Build, Component, Element, Host, Prop, State, Watch, h } from '@stencil/core';
import { getSvgContent, ioniconContent } from './request';
import { getCacheKey, getSvgContent, ioniconContent } from './request';
import { getName, getUrl, inheritAttributes, isRTL } from './utils';
@Component({
@@ -74,9 +74,11 @@ export class Icon {
@Prop() lazy = false;
/**
* When set to `false`, SVG content that is HTTP fetched will not be checked
* if the response SVG content has any `<script>` elements, or any attributes
* that start with `on`, such as `onclick`.
* When `true`, SVG content, including SVG `data:` URLs, is checked before it
* renders. SVGs with `<script>` elements, attributes that start with `on`
* (like `onclick`), `javascript:` URLs, or non-SVG elements aren't rendered,
* and `<foreignObject>` elements are removed. Only set this to `false` for
* SVG content from a trusted source.
* @default true
*/
@Prop() sanitize = true;
@@ -175,12 +177,13 @@ export class Icon {
const url = getUrl(this);
if (url) {
if (ioniconContent.has(url)) {
const cacheKey = getCacheKey(url, this.sanitize);
if (ioniconContent.has(cacheKey)) {
// sync if it's already loaded
this.svgContent = ioniconContent.get(url);
this.svgContent = ioniconContent.get(cacheKey);
} else {
// async if it hasn't been loaded
getSvgContent(url, this.sanitize).then(() => (this.svgContent = ioniconContent.get(url)));
getSvgContent(url, this.sanitize).then(() => (this.svgContent = ioniconContent.get(cacheKey)));
}
this.didLoadIcon = true;
}
+13 -13
View File
@@ -7,19 +7,19 @@
## Properties
| Property | Attribute | Description | Type | Default |
| ---------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | -------------- |
| `color` | `color` | The color to use for the background of the item. | `string \| undefined` | `undefined` |
| `flipRtl` | `flip-rtl` | Specifies whether the icon should horizontally flip when `dir` is `"rtl"`. | `boolean \| undefined` | `undefined` |
| `icon` | `icon` | A combination of both `name` and `src`. If a `src` url is detected it will set the `src` property. Otherwise it assumes it's a built-in named SVG and set the `name` property. | `any` | `undefined` |
| `ios` | `ios` | Specifies which icon to use on `ios` mode. | `string \| undefined` | `undefined` |
| `lazy` | `lazy` | If enabled, ion-icon will be loaded lazily when it's visible in the viewport. Default, `false`. | `boolean` | `false` |
| `md` | `md` | Specifies which icon to use on `md` mode. | `string \| undefined` | `undefined` |
| `mode` | `mode` | The mode determines which platform styles to use. | `string` | `getIonMode()` |
| `name` | `name` | Specifies which icon to use from the built-in set of icons. | `string \| undefined` | `undefined` |
| `sanitize` | `sanitize` | When set to `false`, SVG content that is HTTP fetched will not be checked if the response SVG content has any `<script>` elements, or any attributes that start with `on`, such as `onclick`. | `boolean` | `true` |
| `size` | `size` | The size of the icon. Available options are: `"small"` and `"large"`. | `string \| undefined` | `undefined` |
| `src` | `src` | Specifies the exact `src` of an SVG file to use. | `string \| undefined` | `undefined` |
| Property | Attribute | Description | Type | Default |
| ---------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | -------------- |
| `color` | `color` | The color to use for the background of the item. | `string \| undefined` | `undefined` |
| `flipRtl` | `flip-rtl` | Specifies whether the icon should horizontally flip when `dir` is `"rtl"`. | `boolean \| undefined` | `undefined` |
| `icon` | `icon` | A combination of both `name` and `src`. If a `src` url is detected it will set the `src` property. Otherwise it assumes it's a built-in named SVG and set the `name` property. | `any` | `undefined` |
| `ios` | `ios` | Specifies which icon to use on `ios` mode. | `string \| undefined` | `undefined` |
| `lazy` | `lazy` | If enabled, ion-icon will be loaded lazily when it's visible in the viewport. Default, `false`. | `boolean` | `false` |
| `md` | `md` | Specifies which icon to use on `md` mode. | `string \| undefined` | `undefined` |
| `mode` | `mode` | The mode determines which platform styles to use. | `string` | `getIonMode()` |
| `name` | `name` | Specifies which icon to use from the built-in set of icons. | `string \| undefined` | `undefined` |
| `sanitize` | `sanitize` | When `true`, SVG content, including SVG `data:` URLs, is checked before it renders. SVGs with `<script>` elements, attributes that start with `on` (like `onclick`), `javascript:` URLs, or non-SVG elements aren't rendered, and `<foreignObject>` elements are removed. Only set this to `false` for SVG content from a trusted source. | `boolean` | `true` |
| `size` | `size` | The size of the icon. Available options are: `"small"` and `"large"`. | `string \| undefined` | `undefined` |
| `src` | `src` | Specifies the exact `src` of an SVG file to use. | `string \| undefined` | `undefined` |
----------------------------------------------
+34 -13
View File
@@ -5,20 +5,39 @@ const requests = new Map<string, Promise<any>>();
let parser: DOMParser;
/**
* Unsanitized content gets its own key so it's never served to an icon that
* sanitizes.
*/
export const getCacheKey = (url: string, sanitize: boolean) =>
`${sanitize !== false ? 'sanitized' : 'unsanitized'}:${url}`;
/**
* Warns when the whole icon is rejected so it doesn't silently render nothing.
*/
const sanitizeSvg = (url: string, svgContent: string) =>
validateContent(svgContent, () => {
const source = url.length > 100 ? `${url.slice(0, 100)}...` : url;
console.warn(
`[Ionicons Warning]: The SVG from "${source}" was not rendered because it failed sanitization. Only set sanitize="false" for SVG content from a trusted source.`,
);
});
/**
* Safely fallback to an empty svg
*/
function safeFallback(url: string) {
function safeFallback(cacheKey: string) {
const svg = '';
ioniconContent.set(url, svg);
ioniconContent.set(cacheKey, svg);
return svg;
}
export const getSvgContent = (url: string, sanitize: boolean): Promise<string> => {
const cacheKey = getCacheKey(url, sanitize);
/**
* See if we already have a request for this url
*/
const req = requests.get(url);
const req = requests.get(cacheKey);
if (req) {
return req;
}
@@ -29,16 +48,16 @@ export const getSvgContent = (url: string, sanitize: boolean): Promise<string> =
* with the DOMParser. This works with content security policies enabled.
*/
if (isSvgDataUrl(url) && isEncodedDataUrl(url)) {
return Promise.resolve(getSvgByUrl(url));
return Promise.resolve(getSvgByUrl(url, sanitize));
}
return fetchSvg(url, sanitize);
}
return Promise.resolve(safeFallback(url));
return Promise.resolve(safeFallback(cacheKey));
};
function getSvgByUrl(url: string): string {
function getSvgByUrl(url: string, sanitize: boolean): string {
if (!parser) {
/**
* Create an instance of the DOM parser. This creates a single
@@ -49,14 +68,16 @@ function getSvgByUrl(url: string): string {
const doc = parser.parseFromString(url, 'text/html');
const svg = doc.querySelector('svg');
if (svg) {
ioniconContent.set(url, svg.outerHTML);
return svg.outerHTML;
const svgContent = sanitize !== false ? sanitizeSvg(url, svg.outerHTML) : svg.outerHTML;
ioniconContent.set(getCacheKey(url, sanitize), svgContent);
return svgContent;
}
throw new Error(`Could not parse svg from ${url}`);
}
function fetchSvg(url: string, sanitize: boolean): Promise<string> {
const cacheKey = getCacheKey(url, sanitize);
/**
* We don't already have a request
*/
@@ -71,20 +92,20 @@ function fetchSvg(url: string, sanitize: boolean): Promise<string> {
.text()
.then((svgContent) => {
if (svgContent && sanitize !== false) {
svgContent = validateContent(svgContent);
svgContent = sanitizeSvg(url, svgContent);
}
const svg = svgContent || '';
ioniconContent.set(url, svg);
ioniconContent.set(cacheKey, svg);
return svg;
})
.catch(() => safeFallback(url));
.catch(() => safeFallback(cacheKey));
})
.catch(() => safeFallback(url));
.catch(() => safeFallback(cacheKey));
/**
* Cache for the same requests
*/
requests.set(url, req);
requests.set(cacheKey, req);
return req;
}
@@ -1,6 +1,40 @@
import { expect } from '@playwright/test';
import type { E2EPage } from '@utils/test/playwright';
import { test } from '@utils/test/playwright';
/**
* An SVG whose handler pushes `label` to `window.xssFired` if it ever runs.
*/
const imageOnErrorSvg = (label: string) =>
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><image href="x" onerror="window.xssFired.push('${label}')"/></svg>`;
const utf8DataUrl = (svg: string) => `data:image/svg+xml;utf8,${svg}`;
/**
* Sets `sanitize` before `src` so the icon loads with the intended setting.
*/
const addIcon = (page: E2EPage, id: string, src: string, sanitize?: boolean) =>
page.evaluate(
([id, src, sanitize]) => {
const icon = document.createElement('ion-icon') as any;
icon.id = id;
if (sanitize !== undefined) {
icon.sanitize = sanitize;
}
icon.src = src;
document.body.appendChild(icon);
},
[id, src, sanitize] as const,
);
/**
* Waits for the unsanitized control icon's handler to fire. Any `data:` URL
* payload added before it has had at least as long to fire.
*/
const waitForControl = (page: E2EPage) => page.waitForFunction(() => (window as any).xssFired.includes('control'));
const getFired = (page: E2EPage) => page.evaluate(() => (window as any).xssFired as string[]);
test.describe('icon: sanitization', () => {
test('should not have visual regressions', async ({ page }) => {
await page.goto(`/icon/test/sanitization/`);
@@ -11,3 +45,240 @@ test.describe('icon: sanitization', () => {
await expect(main).toHaveScreenshot(`icon-sanitization.png`);
});
});
test.describe('icon: sanitization: unsafe content', () => {
test.beforeEach(async ({ page }) => {
await page.setContent(`<script>window.xssFired = [];</script>`);
});
test('should not run handlers from a utf8 svg data url', async ({ page }) => {
await addIcon(page, 'attack', utf8DataUrl(imageOnErrorSvg('attack')));
await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false);
await waitForControl(page);
expect(await getFired(page)).not.toContain('attack');
await expect(page.locator('#attack .icon-inner svg')).toHaveCount(0);
});
test('should render a clean utf8 svg data url', async ({ page }) => {
const clean = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M0 0h24v24H0z"/></svg>`;
await addIcon(page, 'clean', utf8DataUrl(clean));
await expect(page.locator('#clean .icon-inner svg path')).toHaveCount(1);
});
test('should warn when an svg is rejected', async ({ page }) => {
const warnings: string[] = [];
page.on('console', (msg) => {
if (msg.type() === 'warning') {
warnings.push(msg.text());
}
});
await addIcon(page, 'attack', utf8DataUrl(imageOnErrorSvg('attack')));
await expect.poll(() => warnings.some((warning) => warning.includes('[Ionicons Warning]'))).toBe(true);
});
test('should not warn about sanitizing when the response is not an svg', async ({ page }) => {
const warnings: string[] = [];
page.on('console', (msg) => {
if (msg.type() === 'warning') {
warnings.push(msg.text());
}
});
await page.route('**/missing.svg', (route) =>
route.fulfill({ status: 404, contentType: 'text/html', body: '<html><body>Not found</body></html>' }),
);
await page.route('**/rejected.svg', (route) =>
route.fulfill({ contentType: 'image/svg+xml', body: imageOnErrorSvg('attack') }),
);
const missingLoaded = page.waitForResponse('**/missing.svg');
await addIcon(page, 'missing', '/missing.svg');
await missingLoaded;
// This takes the same fetch and sanitize steps, so once it warns the 404 has been handled
await addIcon(page, 'rejected', '/rejected.svg');
await expect.poll(() => warnings.some((warning) => warning.includes('rejected.svg'))).toBe(true);
expect(warnings.filter((warning) => warning.includes('missing.svg'))).toHaveLength(0);
});
test('should not run handlers from a fetched svg while sanitizing it', async ({ page }) => {
await page.route('**/xss/*.svg', (route) => {
const label = route.request().url().includes('control') ? 'control' : 'attack';
route.fulfill({
contentType: 'image/svg+xml',
body: `<img src="x" onerror="window.xssFired.push('${label}')">${imageOnErrorSvg(label)}`,
});
});
// Fetches resolve independently, so let the attack load before the control starts
const attackLoaded = page.waitForResponse('**/xss/attack.svg');
await addIcon(page, 'attack', '/xss/attack.svg');
await attackLoaded;
await addIcon(page, 'control', '/xss/control.svg', false);
await waitForControl(page);
expect(await getFired(page)).not.toContain('attack');
await expect(page.locator('#attack .icon-inner svg')).toHaveCount(0);
});
test('should reject a fetched svg with more than one root svg', async ({ page }) => {
await page.route('**/xss/*.svg', (route) => {
const label = route.request().url().includes('control') ? 'control' : 'attack';
route.fulfill({
contentType: 'image/svg+xml',
body: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M0 0h24v24H0z"/></svg>${imageOnErrorSvg(label)}`,
});
});
const attackLoaded = page.waitForResponse('**/xss/attack.svg');
await addIcon(page, 'attack', '/xss/attack.svg');
await attackLoaded;
await addIcon(page, 'control', '/xss/control.svg', false);
await waitForControl(page);
expect(await getFired(page)).not.toContain('attack');
await expect(page.locator('#attack .icon-inner svg')).toHaveCount(0);
});
const htmlInSvgPayloads = [
{
name: 'noscript',
inner: `<desc><noscript><p title="</noscript><img src=x onerror=top.xssFired.push('attack')>"></p></noscript></desc>`,
},
{
name: 'template',
inner: `<desc><template><img src="x" onerror="top.xssFired.push('attack')"></template></desc>`,
},
];
htmlInSvgPayloads.forEach(({ name, inner }) => {
test(`should reject an svg containing an html ${name} element`, async ({ page }) => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">${inner}<path d="M0 0h24v24H0z"/></svg>`;
await addIcon(page, 'attack', utf8DataUrl(svg));
await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false);
await waitForControl(page);
expect(await getFired(page)).not.toContain('attack');
await expect(page.locator('#attack .icon-inner svg')).toHaveCount(0);
});
});
const foreignObjectPayloads = [
{
name: 'iframe srcdoc',
inner: `<iframe xmlns="http://www.w3.org/1999/xhtml" srcdoc="&lt;script&gt;top.xssFired.push('attack')&lt;/script&gt;"></iframe>`,
},
{
name: 'iframe javascript: src',
inner: `<iframe xmlns="http://www.w3.org/1999/xhtml" src="javascript:top.xssFired.push('attack')"></iframe>`,
},
];
foreignObjectPayloads.forEach(({ name, inner }) => {
test(`should remove a foreignObject containing an ${name}`, async ({ page }) => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><foreignObject width="24" height="24">${inner}</foreignObject><path d="M0 0h24v24H0z"/></svg>`;
await addIcon(page, 'attack', utf8DataUrl(svg));
await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false);
await waitForControl(page);
expect(await getFired(page)).not.toContain('attack');
await expect(page.locator('#attack .icon-inner svg path')).toHaveCount(1);
await expect(page.locator('#attack .icon-inner svg > :not(path)')).toHaveCount(0);
});
});
test('should render an illustrator export that uses a switch with a foreignObject', async ({ page }) => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:i="http://ns.adobe.com/AdobeIllustrator/10.0/" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24"><switch><foreignObject requiredExtensions="http://ns.adobe.com/AdobeIllustrator/10.0/" x="0" y="0" width="1" height="1"><i:pgfRef xlink:href="#adobe_illustrator_pgf"></i:pgfRef></foreignObject><g i:extraneous="self"><path d="M0 0h24v24H0z"/></g></switch></svg>`;
await addIcon(page, 'illustrator', utf8DataUrl(svg));
await expect(page.locator('#illustrator .icon-inner svg path')).toHaveCount(1);
});
const javascriptUrlPayloads = [
{ name: 'an anchor href', inner: `<a href="javascript:top.xssFired.push('attack')"><path d="M0 0h24v24H0z"/></a>` },
{
name: 'an obfuscated xlink:href',
inner: `<a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href=" JaVa&#x09;ScRiPt:top.xssFired.push('attack')"><path d="M0 0h24v24H0z"/></a>`,
},
{
name: 'an animate element',
inner: `<a><animate attributeName="href" values="https://ionic.io;javascript:top.xssFired.push('attack')"/><path d="M0 0h24v24H0z"/></a>`,
},
{
name: 'a set element',
inner: `<a><set attributeName="href" to="javascript:top.xssFired.push('attack')"/><path d="M0 0h24v24H0z"/></a>`,
},
];
javascriptUrlPayloads.forEach(({ name, inner }) => {
test(`should reject an svg with a javascript: url in ${name}`, async ({ page }) => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">${inner}</svg>`;
await addIcon(page, 'attack', utf8DataUrl(svg));
await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false);
await waitForControl(page);
await expect(page.locator('#attack .icon-inner svg')).toHaveCount(0);
});
});
test('should not reuse unsanitized content cached for the same data url', async ({ page }) => {
const shared = utf8DataUrl(imageOnErrorSvg('shared'));
await addIcon(page, 'unsanitized', shared, false);
await page.waitForFunction(() => (window as any).xssFired.includes('shared'));
await addIcon(page, 'sanitized', shared);
await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false);
await waitForControl(page);
await expect(page.locator('#sanitized .icon-inner svg')).toHaveCount(0);
expect((await getFired(page)).filter((label) => label === 'shared')).toHaveLength(1);
});
test('should not reuse sanitized content cached for the same data url', async ({ page }) => {
const shared = utf8DataUrl(imageOnErrorSvg('shared'));
await addIcon(page, 'sanitized', shared);
await addIcon(page, 'unsanitized', shared, false);
await expect(page.locator('#unsanitized .icon-inner svg')).toHaveCount(1);
});
test('should not let a src forge the unsanitized cache key', async ({ page }) => {
const shared = utf8DataUrl(imageOnErrorSvg('shared'));
await addIcon(page, 'unsanitized', shared, false);
await page.waitForFunction(() => (window as any).xssFired.includes('shared'));
await addIcon(page, 'sanitized', `unsanitized:${shared}`);
await addIcon(page, 'control', utf8DataUrl(imageOnErrorSvg('control')), false);
await waitForControl(page);
await expect(page.locator('#sanitized .icon-inner svg')).toHaveCount(0);
expect((await getFired(page)).filter((label) => label === 'shared')).toHaveLength(1);
});
test('should not reuse an unsanitized in-flight fetch for the same url', async ({ page }) => {
await page.route('**/xss/*.svg', (route) => {
const label = route.request().url().includes('control') ? 'control' : 'shared';
// Sanitizing drops the <img> sibling and keeps the clean <svg>
route.fulfill({
contentType: 'image/svg+xml',
body: `<img src="x" onerror="window.xssFired.push('${label}')"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M0 0h24v24H0z"/></svg>`,
});
});
await addIcon(page, 'unsanitized', '/xss/shared.svg', false);
await addIcon(page, 'sanitized', '/xss/shared.svg');
await addIcon(page, 'control', '/xss/control.svg', false);
await waitForControl(page);
await page.waitForFunction(() => (window as any).xssFired.includes('shared'));
await expect(page.locator('#sanitized .icon-inner svg path')).toHaveCount(1);
await expect(page.locator('#sanitized .icon-inner img')).toHaveCount(0);
expect((await getFired(page)).filter((label) => label === 'shared')).toHaveLength(1);
});
});
+94 -33
View File
@@ -1,54 +1,65 @@
import { isEncodedDataUrl, isSvgDataUrl, isValid } from '../validate';
import { readFileSync, readdirSync } from 'fs';
import { join } from 'path';
import { isEncodedDataUrl, isSvgDataUrl, isValid, validateContent } from '../validate';
const SVG_NS = 'http://www.w3.org/2000/svg';
const elm = (nodeName: string, attributes: { name: string; value?: string }[] = [], childNodes: any[] = []) =>
({ nodeType: 1, namespaceURI: SVG_NS, nodeName, attributes, childNodes }) as any;
describe('isValid', () => {
it('invalid onload attr', () => {
const el = {
nodeType: 1,
nodeName: 'svg',
attributes: [{ name: 'onload' }],
childNodes: [],
} as any;
expect(isValid(el)).toBe(false);
expect(isValid(elm('svg', [{ name: 'onload' }]))).toBe(false);
});
it('invalid onclick attr', () => {
const el = {
nodeType: 1,
nodeName: 'svg',
attributes: [{ name: 'OnClIcK' }],
childNodes: [],
} as any;
expect(isValid(el)).toBe(false);
expect(isValid(elm('svg', [{ name: 'OnClIcK' }]))).toBe(false);
});
it('invalid child SCRIPT elm', () => {
const el = {
nodeType: 1,
nodeName: 'svg',
attributes: [],
childNodes: [{ nodeType: 1, nodeName: 'SCRIPT', attributes: [], childNodes: [] }],
} as any;
expect(isValid(el)).toBe(false);
expect(isValid(elm('svg', [], [elm('SCRIPT')]))).toBe(false);
});
it('invalid script elm', () => {
const el = { nodeType: 1, nodeName: 'script', attributes: [], childNodes: [] } as any;
expect(isValid(el)).toBe(false);
expect(isValid(elm('script'))).toBe(false);
});
it('invalid foreignObject elm', () => {
expect(isValid(elm('svg', [], [elm('foreignObject')]))).toBe(false);
});
it.each(['iframe', 'embed', 'object'])('invalid %s elm', (name) => {
expect(isValid(elm('svg', [], [elm(name)]))).toBe(false);
});
it('invalid html namespace elm', () => {
const noscript = { ...elm('noscript'), namespaceURI: 'http://www.w3.org/1999/xhtml' };
expect(isValid(elm('svg', [], [elm('desc', [], [noscript])]))).toBe(false);
});
it('invalid javascript: url', () => {
expect(isValid(elm('a', [{ name: 'href', value: 'javascript:alert(1)' }]))).toBe(false);
});
it('invalid obfuscated javascript: url', () => {
expect(isValid(elm('a', [{ name: 'xlink:href', value: ' JaVa\tScRiPt:alert(1)' }]))).toBe(false);
});
it('invalid javascript: url in a value list', () => {
expect(isValid(elm('animate', [{ name: 'values', value: 'https://ionic.io;javascript:alert(1)' }]))).toBe(false);
});
it('is valid circle elm', () => {
const el = { nodeType: 1, nodeName: 'circle', attributes: [], childNodes: [] } as any;
expect(isValid(el)).toBe(true);
expect(isValid(elm('circle'))).toBe(true);
});
it('is valid SVG elm', () => {
const el = {
nodeType: 1,
nodeName: 'SVG',
attributes: [],
childNodes: [{ nodeType: 1, nodeName: 'line', attributes: [], childNodes: [] }],
} as any;
expect(isValid(el)).toBe(true);
expect(isValid(elm('SVG', [], [elm('line')]))).toBe(true);
});
it('is valid href', () => {
expect(isValid(elm('a', [{ name: 'href', value: 'https://ionic.io' }]))).toBe(true);
});
it('is valid text node', () => {
@@ -57,6 +68,56 @@ describe('isValid', () => {
});
});
describe('validateContent', () => {
it('removes foreignObject and keeps the artwork', () => {
const onRejected = jest.fn();
const result = validateContent(
`<svg xmlns="${SVG_NS}"><switch><foreignObject><iframe></iframe></foreignObject><g><path d="M0 0"></path></g></switch></svg>`,
onRejected,
);
expect(result).toContain('<path');
expect(result).not.toContain('foreignObject');
expect(onRejected).not.toHaveBeenCalled();
});
it('strips non-svg siblings', () => {
const result = validateContent(
`<img src="x" onerror="alert(1)"><svg xmlns="${SVG_NS}"><path d="M0 0"></path></svg>`,
);
expect(result).toContain('<path');
expect(result).not.toContain('<img');
});
it('rejects html inside desc and calls onRejected', () => {
const onRejected = jest.fn();
expect(validateContent(`<svg xmlns="${SVG_NS}"><desc><noscript><p></p></noscript></desc></svg>`, onRejected)).toBe(
'',
);
expect(onRejected).toHaveBeenCalledTimes(1);
});
it('rejects more than one root svg', () => {
const onRejected = jest.fn();
const svg = `<svg xmlns="${SVG_NS}"><path d="M0 0"></path></svg>`;
expect(validateContent(svg + svg, onRejected)).toBe('');
expect(onRejected).toHaveBeenCalledTimes(1);
});
it('accepts every shipped icon', () => {
const svgDir = join(__dirname, '../../../svg');
const rejected = readdirSync(svgDir)
.filter((file) => file.endsWith('.svg'))
.filter((file) => !validateContent(readFileSync(join(svgDir, file), 'utf8')));
expect(rejected).toEqual([]);
});
it('does not call onRejected when there is no svg', () => {
const onRejected = jest.fn();
expect(validateContent('<html><body>Not found</body></html>', onRejected)).toBe('');
expect(onRejected).not.toHaveBeenCalled();
});
});
it('isSvgDataUrl', () => {
expect(isSvgDataUrl('data:image/svg+xml;base64,xxx')).toBe(true);
expect(isSvgDataUrl('data:image/svg+xml;utf8,<svg></svg>')).toBe(true);
+64 -16
View File
@@ -1,43 +1,91 @@
import { isStr } from './utils';
export const validateContent = (svgContent: string) => {
const div = document.createElement('div');
div.innerHTML = svgContent;
/**
* Calls `onRejected` only when an `<svg>` was found and failed validation,
* not when there's no `<svg>` at all (like an HTML 404 page).
*/
export const validateContent = (svgContent: string, onRejected?: () => void) => {
/**
* Parse into a template so nothing loads or runs yet. Parsing into a live
* element would fire handlers like `<img onerror>` before validation.
*/
const template = document.createElement('template');
template.innerHTML = svgContent;
const content = template.content;
// setup this way to ensure it works on our buddy IE
for (let i = div.childNodes.length - 1; i >= 0; i--) {
if (div.childNodes[i].nodeName.toLowerCase() !== 'svg') {
div.removeChild(div.childNodes[i]);
for (let i = content.childNodes.length - 1; i >= 0; i--) {
if (content.childNodes[i].nodeName.toLowerCase() !== 'svg') {
content.removeChild(content.childNodes[i]);
}
}
// must only have 1 root element
const svgElm = div.firstElementChild;
const svgElm = content.firstElementChild;
if (svgElm && svgElm.nodeName.toLowerCase() === 'svg') {
const svgClass = svgElm.getAttribute('class') || '';
svgElm.setAttribute('class', (svgClass + ' s-ion-icon').trim());
// root element must be an svg
// lets double check we've got valid elements
// do not allow scripts
if (isValid(svgElm as any)) {
return div.innerHTML;
/**
* Illustrator exports keep editor data in a `<foreignObject>` next to the
* artwork, so remove it instead of rejecting the icon.
*/
removeForeignObjects(svgElm);
// every root is serialized, so a second <svg> would skip validation
if (content.children.length === 1 && isValid(svgElm as any)) {
return template.innerHTML;
}
onRejected?.();
}
return '';
};
const removeForeignObjects = (elm: Element) => {
for (let i = elm.children.length - 1; i >= 0; i--) {
const child = elm.children[i];
if (child.nodeName.toLowerCase() === 'foreignobject') {
child.remove();
} else {
removeForeignObjects(child);
}
}
};
/**
* Elements that can run script or load a document without an `on*` attribute.
*/
const disallowedElements = new Set(['script', 'foreignobject', 'iframe', 'embed', 'object']);
/**
* Browsers ignore whitespace and control characters in a URL scheme, so strip
* them first. Checking the whole value also catches lists like
* `<animate values="a;javascript:...">`.
*/
const hasJavascriptUrl = (value: string) =>
value
.replace(/[\u0000-\u0020]/g, '')
.toLowerCase()
.includes('javascript:');
const SVG_NS = 'http://www.w3.org/2000/svg';
export const isValid = (elm: HTMLElement) => {
if (elm.nodeType === 1) {
if (elm.nodeName.toLowerCase() === 'script') {
/**
* HTML inside `<desc>` or `<title>` (like `<noscript>`) can parse
* differently when it renders than it did here, so only allow SVG elements.
*/
if (elm.namespaceURI !== SVG_NS || disallowedElements.has(elm.nodeName.toLowerCase())) {
return false;
}
for (let i = 0; i < elm.attributes.length; i++) {
const name = elm.attributes[i].name;
const { name, value } = elm.attributes[i];
if (isStr(name) && name.toLowerCase().indexOf('on') === 0) {
return false;
}
if (isStr(value) && hasJavascriptUrl(value)) {
return false;
}
}
for (let i = 0; i < elm.childNodes.length; i++) {
@@ -1 +1,2 @@
export * from './goto';
export * from './set-content';
@@ -0,0 +1,73 @@
import type { Page, TestInfo } from '@playwright/test';
import type { E2EPage } from '@utils/test/playwright';
/**
* Overwrites the default Playwright page.setContent method.
*
* Navigates to a blank page, sets the content, and waits for the
* Stencil components to be hydrated before proceeding with the test.
*
* Ported from Ionic Framework's fixture. Ionicons has no mode, direction,
* or palette config, so only the ionicons build is injected.
*
* @param page The Playwright page object.
* @param html The HTML content to set on the page body.
* @param testInfo The TestInfo associated with the current test run.
* @param options Navigation options passed to page.goto.
*/
export const setContent = async (
page: Page,
html: string,
testInfo: TestInfo,
options?: Parameters<E2EPage['goto']>[1],
) => {
if (page.isClosed()) {
throw new Error('setContent unavailable: page is already closed');
}
const baseUrl = testInfo.project.use.baseURL;
if (!baseUrl) {
throw new Error('setContent requires a baseURL in the Playwright config');
}
const output = `
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<title>Ionicons Playwright Test</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0" />
<script type="module" src="${baseUrl}/build/ionicons.esm.js"></script>
</head>
<body>
${html}
</body>
</html>
`;
await page.route(baseUrl, (route) => {
if (route.request().url() === `${baseUrl}/`) {
/**
* Intercepts the empty page request and returns the
* HTML content that was passed in.
*/
route.fulfill({
status: 200,
contentType: 'text/html',
body: output,
});
} else {
// Allow all other requests to pass through
route.continue();
}
});
/**
* URL query parameters cause the custom Playwright `page.route`
* interceptor to fail, which is necessary to inject the test HTML.
*
* To avoid this, the final navigation URL is kept simple by using
* hash params to ensure the route interceptor always works.
*/
await page.goto(`${baseUrl}#`, options);
};
@@ -54,4 +54,10 @@ export interface E2EPage extends Page {
waitUntil?: 'load' | 'domcontentloaded' | 'networkidle' | 'commit';
},
) => Promise<null | Response>;
/**
* Replaces the page content with the given HTML, loads the ionicons build,
* and waits for the Stencil components to be hydrated.
*/
setContent: (html: string, options?: Parameters<E2EPage['goto']>[1]) => Promise<void>;
}
+2 -1
View File
@@ -7,7 +7,7 @@ import type {
} from '@playwright/test';
import { test as base } from '@playwright/test';
import { goto as goToPage } from './page/utils';
import { goto as goToPage, setContent } from './page/utils';
import type { E2EPage } from './playwright-declarations';
type CustomTestArgs = PlaywrightTestArgs &
@@ -43,6 +43,7 @@ export async function extendPageFixture(page: E2EPage, testInfo: TestInfo) {
})();`);
// Overridden Playwright methods
page.goto = (url: string, options) => goToPage(page, url, options, testInfo, originalGoto);
page.setContent = (html: string, options) => setContent(page, html, testInfo, options);
return page;
}