Skip to content

Commit

Permalink
fix: add validation checks for SVG and encoded data urls
Browse files Browse the repository at this point in the history
  • Loading branch information
ju-Skinner committed Jan 5, 2024
1 parent 6d46d74 commit 0918252
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 14 deletions.
44 changes: 31 additions & 13 deletions src/components/pds-icon/request.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,49 @@
import { validateContent } from './validate';
import { isEncodedDataUrl, isSvgDataUrl, validateContent } from './validate';

export const pdsIconContent = new Map<string, string>();
const requests = new Map<string, Promise<any>>(); // eslint-disable-line @typescript-eslint/no-explicit-any

let parser: DOMParser;

export const getSvgContent = (url: string, sanitize = false) => {
let req = requests.get(url);

if(!req) {
if (typeof fetch != 'undefined' && typeof document !== 'undefined') {
// we don't have a request
req = fetch(url).then((rsp) => {
if (rsp.ok) {
return rsp.text().then((svgContent) => {
if (svgContent && sanitize !== false) {
svgContent = validateContent(svgContent);
}
pdsIconContent.set(url, svgContent || '');
});
if (isSvgDataUrl(url) && isEncodedDataUrl(url)) {
if (!parser) {
parser = new DOMParser();
}

const doc = parser.parseFromString(url, 'text/html');
const svg = doc.querySelector('svg');

if (svg) {
pdsIconContent.set(url, svg.outerHTML);
}
pdsIconContent.set(url, '');
});

requests.set(url, req);
return Promise.resolve();
} else {
// we don't have a request
req = fetch(url).then((rsp) => {
if (rsp.ok) {
return rsp.text().then((svgContent) => {
if (svgContent && sanitize !== false) {
svgContent = validateContent(svgContent);
}
pdsIconContent.set(url, svgContent || '');
});
}
pdsIconContent.set(url, '');
});

requests.set(url, req);
}
} else {
pdsIconContent.set(url, '');
return Promise.resolve();
}
}

return req;
}
5 changes: 4 additions & 1 deletion src/components/pds-icon/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const validateContent = (svgContent: string) => {
const svgElm = div.firstElementChild;
if (svgElm && svgElm.nodeName.toLowerCase() === 'svg') {
const svgClass = svgElm.getAttribute('class') || '';
svgElm.setAttribute('class', (svgClass + ' s-ion-icon').trim());
svgElm.setAttribute('class', (svgClass + ' s-pds-icon').trim());

// root element must be an svg
// lets double check we've got valid elements
Expand Down Expand Up @@ -48,3 +48,6 @@ export const isValid = (elm: HTMLElement) => {
}
return true;
};

export const isSvgDataUrl = (url: string) => url.startsWith('data:image/svg+xml');
export const isEncodedDataUrl = (url: string) => url.indexOf(';utf8,') !== -1;

0 comments on commit 0918252

Please sign in to comment.