Skip to content

Commit 757c77c

Browse files
authored
Merge pull request #1121 from mathjax/verify-styles
Better validation of style values
2 parents 20f4674 + 2c1f3de commit 757c77c

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

ts/util/Styles.ts

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,9 @@ export class Styles {
319319
* Patterns for style values and comments
320320
*/
321321
public static pattern: {[name: string]: RegExp} = {
322-
style: /([-a-z]+)[\s\n]*:[\s\n]*((?:'[^']*'|"[^"]*"|\n|.)*?)[\s\n]*(?:;|$)/g,
322+
sanitize: /['";]/,
323+
value: /^((:?'(?:\\.|[^'])*(?:'|$)|"(?:\\.|[^"])*(?:"|$)|\n|\\.|[^'";])*?)(?:;|$).*/,
324+
style: /([-a-z]+)[\s\n]*:[\s\n]*((?:'(?:\\.|[^'])*(?:'|$)|"(?:\\.|[^"])*(?:"|$)|\n|\\.|[^';])*?)[\s\n]*(?:;|$)/g,
323325
comment: /\/\*[^]*?\*\//g
324326
};
325327

@@ -394,6 +396,23 @@ export class Styles {
394396
this.parse(cssText);
395397
}
396398

399+
/**
400+
* @param {string} text The value to be sanitized
401+
* @return {string} The sanitized value (removes ; and anything past that, and balances quotation marks)
402+
*/
403+
protected sanitizeValue(text: string): string {
404+
let PATTERN = (this.constructor as typeof Styles).pattern;
405+
if (!text.match(PATTERN.sanitize)) {
406+
return text;
407+
}
408+
text = text.replace(PATTERN.value, '$1');
409+
const test = text.replace(/\\./g, '').replace(/(['"]).*?\1/g, '').replace(/[^'"]/g, '');
410+
if (test.length) {
411+
text += test.charAt(0);
412+
}
413+
return text;
414+
}
415+
397416
/**
398417
* @return {string} The CSS string for the styles currently defined
399418
*/
@@ -402,7 +421,7 @@ export class Styles {
402421
for (const name of Object.keys(this.styles)) {
403422
const parent = this.parentName(name);
404423
if (!this.styles[parent]) {
405-
styles.push(name + ': ' + this.styles[name] + ';');
424+
styles.push(name + ': ' + this.sanitizeValue(this.styles[name]) + ';');
406425
}
407426
}
408427
return styles.join(' ');
@@ -524,10 +543,10 @@ export class Styles {
524543
protected parse(cssText: string = '') {
525544
let PATTERN = (this.constructor as typeof Styles).pattern;
526545
this.styles = {};
527-
const parts = cssText.replace(PATTERN.comment, '').split(PATTERN.style);
546+
const parts = cssText.replace(/\n/g, ' ').replace(PATTERN.comment, '').split(PATTERN.style);
528547
while (parts.length > 1) {
529548
let [space, name, value] = parts.splice(0, 3);
530-
if (space.match(/[^\s\n]/)) return;
549+
if (space.match(/[^\s\n;]/)) return;
531550
this.set(name, value);
532551
}
533552
}

0 commit comments

Comments
 (0)