feat(xml parser): Only allow angular syntax extensions if configured.

Configure via the public `angularSyntax` property on EasySAXParser and
the XmlParser wrapper.
This commit is contained in:
Hristo Deshev
2015-06-05 15:51:08 +03:00
parent aa112244fd
commit 748b4f1c99
5 changed files with 650 additions and 622 deletions

View File

@ -5,6 +5,7 @@ declare module "js-libs/easysax" {
parse(xml: string): void; parse(xml: string): void;
on(name: string, cb: Function): void; on(name: string, cb: Function): void;
ns(root: string, ns: any): void; ns(root: string, ns: any): void;
public angularSyntax: boolean;
} }
} }

View File

@ -54,17 +54,11 @@
}; };
*/ */
// << ------------------------------------------------------------------------ >> // // << ------------------------------------------------------------------------ >> //
if (typeof exports === 'object' /*&& this == exports*/) { if (typeof exports === 'object' /*&& this == exports*/) {
module.exports.EasySAXParser = EasySAXParser; module.exports.EasySAXParser = EasySAXParser;
}; };
@ -74,37 +68,53 @@ function EasySAXParser() {
if (!this) return null; if (!this) return null;
this.angularSyntax = false;
function nullFunc() {}; function nullFunc() {};
var onTextNode = nullFunc, onStartNode = nullFunc, onEndNode = nullFunc, onCDATA = nullFunc, onError = nullFunc, onComment, onQuestion, onAttention; this.onTextNode = nullFunc;
var is_onComment, is_onQuestion, is_onAttention; this.onStartNode = nullFunc;
this.onEndNode = nullFunc;
this.onCDATA = nullFunc;
this.onError = nullFunc;
this.onComment = null;
this.onQuestion = null;
this.onAttention = null;
this.is_onComment = this.is_onQuestion = this.is_onAttention = false;
var isNamespace = false, useNS , default_xmlns, xmlns this.isNamespace = false;
, nsmatrix = {xmlns: xmlns} this.useNS = null;
, hasSurmiseNS = false this.default_xmlns = null;
this.xmlns = null;
this.nsmatrix = {xmlns: this.xmlns};
this.hasSurmiseNS = false;
; ;
this.on = function(name, cb) { this.attr_string = ''; // строка атрибутов
this.attr_posstart = 0; //
this.attr_res; // закешированный результат разбора атрибутов , null - разбор не проводился, object - хеш атрибутов, true - нет атрибутов, false - невалидный xml
}
EasySAXParser.prototype.on = function(name, cb) {
if (typeof cb !== 'function') { if (typeof cb !== 'function') {
if (cb !== null) return; if (cb !== null) return;
}; };
switch(name) { switch(name) {
case 'error': onError = cb || nullFunc; break; case 'error': this.onError = cb || nullFunc; break;
case 'startNode': onStartNode = cb || nullFunc; break; case 'startNode': this.onStartNode = cb || nullFunc; break;
case 'endNode': onEndNode = cb || nullFunc; break; case 'endNode': this.onEndNode = cb || nullFunc; break;
case 'textNode': onTextNode = cb || nullFunc; break; case 'textNode': onTextNode = cb || nullFunc; break;
case 'cdata': onCDATA = cb || nullFunc; break; case 'cdata': this.onCDATA = cb || nullFunc; break;
case 'comment': onComment = cb; is_onComment = !!cb; break;
case 'question': onQuestion = cb; is_onQuestion = !!cb; break; // <? .... ?>
case 'attention': onAttention = cb; is_onAttention = !!cb; break; // <!XXXXX zzzz="eeee">
case 'comment': this.onComment = cb; this.is_onComment = !!cb; break;
case 'question': this.onQuestion = cb; this.is_onQuestion = !!cb; break; // <? .... ?>
case 'attention': this.onAttention = cb; this.is_onAttention = !!cb; break; // <!XXXXX zzzz="eeee">
}; };
}; };
this.ns = function(root, ns) { EasySAXParser.prototype.ns = function(root, ns) {
if (!root || typeof root !== 'string' || !ns) { if (!root || typeof root !== 'string' || !ns) {
return; return;
}; };
@ -120,34 +130,35 @@ function EasySAXParser() {
}; };
if (ok) { if (ok) {
isNamespace = true; this.isNamespace = true;
default_xmlns = root; this.default_xmlns = root;
useNS = x; this.useNS = x;
};
}; };
};
this.parse = function(xml) {
EasySAXParser.prototype.parse = function(xml) {
if (typeof xml !== 'string') { if (typeof xml !== 'string') {
return; return;
}; };
if (isNamespace) { if (this.isNamespace) {
nsmatrix = {xmlns: default_xmlns}; this.nsmatrix = {xmlns: this.default_xmlns};
parse(xml); parse(xml);
nsmatrix = false; this.nsmatrix = false;
} else { } else {
parse(xml); parse(xml);
}; };
attr_res = true; this.attr_res = true;
}; };
// ----------------------------------------------------- // -----------------------------------------------------
var xharsQuot={constructor: false, hasOwnProperty: false, isPrototypeOf: false, propertyIsEnumerable: false, toLocaleString: false, toString: false, valueOf: false var xharsQuot={constructor: false, hasOwnProperty: false, isPrototypeOf: false, propertyIsEnumerable: false, toLocaleString: false, toString: false, valueOf: false
, quot: '"' , quot: '"'
, QUOT: '"' , QUOT: '"'
, amp: '&' , amp: '&'
@ -168,10 +179,10 @@ function EasySAXParser() {
, sup3: '\u00B3' , sup3: '\u00B3'
, micro: '\u00B5' , micro: '\u00B5'
, para: '\u00B6' , para: '\u00B6'
}; };
function rpEntities(s, d, x, z) { function rpEntities(s, d, x, z) {
if (z) { if (z) {
return xharsQuot[z] || '\x01'; return xharsQuot[z] || '\x01';
}; };
@ -181,9 +192,9 @@ function EasySAXParser() {
}; };
return String.fromCharCode(parseInt(x, 16)); return String.fromCharCode(parseInt(x, 16));
}; };
function unEntities(s, i) { function unEntities(s, i) {
s = String(s); s = String(s);
if (s.length > 3 && s.indexOf('&') !== -1) { if (s.length > 3 && s.indexOf('&') !== -1) {
if (s.indexOf('&gt;') !== -1) s = s.replace(/&gt;/g, '>'); if (s.indexOf('&gt;') !== -1) s = s.replace(/&gt;/g, '>');
@ -196,11 +207,23 @@ function EasySAXParser() {
}; };
return s; return s;
}; };
var attr_string = ''; // строка атрибутов
var attr_posstart = 0; // EasySAXParser.prototype.allowedAngularAttributeChars = function(w) {
var attr_res; // закешированный результат разбора атрибутов , null - разбор не проводился, object - хеш атрибутов, true - нет атрибутов, false - невалидный xml if (!this.angularSyntax) {
return false;
} else {
return (
w === 40 || // (
w === 41 || // )
w === 91 || // [
w === 93 || // ]
w === 94 || // ^
w === 35 // #
);
}
};
/* /*
парсит атрибуты по требованию. Важно! - функция не генерирует исключения. парсит атрибуты по требованию. Важно! - функция не генерирует исключения.
@ -210,11 +233,9 @@ function EasySAXParser() {
если есть атрибуты то возврашается обьект(хеш) если есть атрибуты то возврашается обьект(хеш)
*/ */
var RGX_ATTR_NAME = /[^\w:-]+/g; EasySAXParser.prototype.getAttrs = function() {
if (this.attr_res !== null) {
function getAttrs() { return this.attr_res;
if (attr_res !== null) {
return attr_res;
}; };
/* /*
@ -231,10 +252,10 @@ function EasySAXParser() {
var u var u
, res = {} , res = {}
, s = attr_string , s = this.attr_string
, i = attr_posstart , i = this.attr_posstart
, l = s.length , l = s.length
, attr_list = hasSurmiseNS ? [] : false , attr_list = this.hasSurmiseNS ? [] : false
, name, value = '' , name, value = ''
, ok = false , ok = false
, noValueAttribute = false , noValueAttribute = false
@ -251,9 +272,10 @@ function EasySAXParser() {
continue continue
}; };
if ((w < 65 && w !== 40 && w !== 41 && w !== 35) || // allow parens () -- used for angular syntax // Check for valid attribute start char
w > 122 || (w === 92 || (w > 93 && w < 97)) ) { // ожидаем символ if ((w < 65 && !this.allowedAngularAttributeChars(w)) ||
return attr_res = false; // error. invalid char w > 122 || (w > 90 && w < 97 && !this.allowedAngularAttributeChars(w)) ) { // ожидаем символ
return this.attr_res = false; // error. invalid char
}; };
for(j = i + 1; j < l; j++) { // проверяем все символы имени атрибута for(j = i + 1; j < l; j++) { // проверяем все символы имени атрибута
@ -268,7 +290,7 @@ function EasySAXParser() {
} }
}; };
if (w === 91 || w === 93 || w === 40 || w === 41 || w === 94 || w === 35) { // Angular special attribute chars:[]()^ if (this.allowedAngularAttributeChars(w)) {
continue; continue;
} }
@ -281,7 +303,7 @@ function EasySAXParser() {
} else { } else {
//console.log('error 2'); //console.log('error 2');
if (!noValueAttribute) if (!noValueAttribute)
return attr_res = false; // error. invalid char return this.attr_res = false; // error. invalid char
}; };
break; break;
@ -292,7 +314,7 @@ function EasySAXParser() {
if (name === 'xmlns:xmlns') { if (name === 'xmlns:xmlns') {
//console.log('error 6') //console.log('error 6')
return attr_res = false; // error. invalid name return this.attr_res = false; // error. invalid name
}; };
w = s.charCodeAt(j+1); w = s.charCodeAt(j+1);
@ -314,14 +336,14 @@ function EasySAXParser() {
j = s.indexOf('\'', i = j+2 ); j = s.indexOf('\'', i = j+2 );
} else { // "'" } else { // "'"
return attr_res = false; // error. invalid char return this.attr_res = false; // error. invalid char
}; };
}; };
} }
if (j === -1) { if (j === -1) {
//console.log('error 4') //console.log('error 4')
return attr_res = false; // error. invalid char return this.attr_res = false; // error. invalid char
}; };
@ -331,7 +353,7 @@ function EasySAXParser() {
if (w > 32 || w < 9 || (w < 32 && w > 13)) { if (w > 32 || w < 9 || (w < 32 && w > 13)) {
// error. invalid char // error. invalid char
//console.log('error 5') //console.log('error 5')
return attr_res = false; return this.attr_res = false;
}; };
}; };
@ -345,32 +367,32 @@ function EasySAXParser() {
//i = j + 1; // след. семвол уже проверен потому проверять нужно следуюший //i = j + 1; // след. семвол уже проверен потому проверять нужно следуюший
i = j; // след. семвол уже проверен потому проверять нужно следуюший i = j; // след. семвол уже проверен потому проверять нужно следуюший
if (isNamespace) { // if (this.isNamespace) { //
if (hasSurmiseNS) { if (this.hasSurmiseNS) {
// есть подозрение что в атрибутах присутствует xmlns // есть подозрение что в атрибутах присутствует xmlns
if (newalias = name === 'xmlns' ? 'xmlns' : name.charCodeAt(0) === 120 && name.substr(0, 6) === 'xmlns:' && name.substr(6) ) { if (newalias = name === 'xmlns' ? 'xmlns' : name.charCodeAt(0) === 120 && name.substr(0, 6) === 'xmlns:' && name.substr(6) ) {
alias = useNS[unEntities(value)]; alias = this.useNS[unEntities(value)];
if (alias) { if (alias) {
if (nsmatrix[newalias] !== alias) { if (this.nsmatrix[newalias] !== alias) {
if (!hasNewMatrix) { if (!hasNewMatrix) {
hasNewMatrix = true; hasNewMatrix = true;
nn = {}; for (n in nsmatrix) nn[n] = nsmatrix[n]; nn = {}; for (n in this.nsmatrix) nn[n] = this.nsmatrix[n];
nsmatrix = nn; this.nsmatrix = nn;
}; };
nsmatrix[newalias] = alias; this.nsmatrix[newalias] = alias;
}; };
} else { } else {
if (nsmatrix[newalias]) { if (this.nsmatrix[newalias]) {
if (!hasNewMatrix) { if (!hasNewMatrix) {
hasNewMatrix = true; hasNewMatrix = true;
nn = {}; for (n in nsmatrix) nn[n] = nsmatrix[n]; nn = {}; for (n in this.nsmatrix) nn[n] = this.nsmatrix[n];
nsmatrix = nn; this.nsmatrix = nn;
}; };
nsmatrix[newalias] = false; this.nsmatrix[newalias] = false;
}; };
}; };
@ -385,7 +407,7 @@ function EasySAXParser() {
w = name.length; w = name.length;
while(--w) { while(--w) {
if (name.charCodeAt(w) === 58) { // ':' if (name.charCodeAt(w) === 58) { // ':'
if (w = nsmatrix[name.substring(0, w)] ) { if (w = this.nsmatrix[name.substring(0, w)] ) {
res[w + name.substr(w)] = value; res[w + name.substr(w)] = value;
}; };
continue aa; continue aa;
@ -401,11 +423,11 @@ function EasySAXParser() {
if (!ok) { if (!ok) {
return attr_res = true; // атрибутов нет, ошибок тоже нет return this.attr_res = true; // атрибутов нет, ошибок тоже нет
}; };
if (hasSurmiseNS) { if (this.hasSurmiseNS) {
bb: bb:
for (i = 0, l = attr_list.length; i < l; i++) { for (i = 0, l = attr_list.length; i < l; i++) {
@ -414,7 +436,7 @@ function EasySAXParser() {
w = name.length; w = name.length;
while(--w) { // name.indexOf(':') while(--w) { // name.indexOf(':')
if (name.charCodeAt(w) === 58) { // ':' if (name.charCodeAt(w) === 58) { // ':'
if (w = nsmatrix[name.substring(0, w)]) { if (w = this.nsmatrix[name.substring(0, w)]) {
res[w + name.substr(w)] = attr_list[i]; res[w + name.substr(w)] = attr_list[i];
}; };
continue bb; continue bb;
@ -426,12 +448,12 @@ function EasySAXParser() {
}; };
}; };
return attr_res = res; return this.attr_res = res;
}; };
// xml - string // xml - string
function parse(xml) { EasySAXParser.prototype.parse = function(xml) {
var u var u
, xml = String(xml) , xml = String(xml)
, nodestack = [] , nodestack = []
@ -465,7 +487,7 @@ function EasySAXParser() {
if (i === -1) { // конец разбора if (i === -1) { // конец разбора
if (nodestack.length) { if (nodestack.length) {
onError('end file'); this.onError('end file');
return; return;
}; };
@ -473,7 +495,7 @@ function EasySAXParser() {
}; };
if (j !== i && !stop) { if (j !== i && !stop) {
ok = onTextNode(xml.substring(j, i), unEntities); ok = this.onTextNode(xml.substring(j, i), unEntities);
if (ok === false) return; if (ok === false) return;
}; };
@ -484,32 +506,30 @@ function EasySAXParser() {
if (w === 91 && xml.substr(i+3, 6) === 'CDATA[') { // 91 == "[" if (w === 91 && xml.substr(i+3, 6) === 'CDATA[') { // 91 == "["
j = xml.indexOf(']]>', i); j = xml.indexOf(']]>', i);
if (j === -1) { if (j === -1) {
onError('cdata'); this.onError('cdata');
return; return;
}; };
//x = xml.substring(i+9, j); //x = xml.substring(i+9, j);
if (!stop) { if (!stop) {
ok = onCDATA(xml.substring(i+9, j), false); ok = this.onCDATA(xml.substring(i+9, j), false);
if (ok === false) return; if (ok === false) return;
}; };
j += 3; j += 3;
continue; continue;
}; };
if (w === 45 && xml.charCodeAt(i+3) === 45) { // 45 == "-" if (w === 45 && xml.charCodeAt(i+3) === 45) { // 45 == "-"
j = xml.indexOf('-->', i); j = xml.indexOf('-->', i);
if (j === -1) { if (j === -1) {
onError('expected -->'); this.onError('expected -->');
return; return;
}; };
if (is_onComment && !stop) { if (this.is_onComment && !stop) {
ok = onComment(xml.substring(i+4, j), unEntities); ok = this.onComment(xml.substring(i+4, j), unEntities);
if (ok === false) return; if (ok === false) return;
}; };
@ -519,12 +539,12 @@ function EasySAXParser() {
j = xml.indexOf('>', i+1); j = xml.indexOf('>', i+1);
if (j === -1) { if (j === -1) {
onError('expected ">"'); this.onError('expected ">"');
return; return;
}; };
if (is_onAttention && !stop) { if (this.is_onAttention && !stop) {
ok = onAttention(xml.substring(i, j+1), unEntities); ok = this.onAttention(xml.substring(i, j+1), unEntities);
if (ok === false) return; if (ok === false) return;
}; };
@ -535,12 +555,12 @@ function EasySAXParser() {
if (w === 63) { // "?" if (w === 63) { // "?"
j = xml.indexOf('?>', i); j = xml.indexOf('?>', i);
if (j === -1) { // error if (j === -1) { // error
onError('...?>'); this.onError('...?>');
return; return;
}; };
if (is_onQuestion) { if (this.is_onQuestion) {
ok = onQuestion(xml.substring(i, j+2)); ok = this.onQuestion(xml.substring(i, j+2));
if (ok === false) return; if (ok === false) return;
}; };
@ -552,11 +572,11 @@ function EasySAXParser() {
j = xml.indexOf('>', i+1); j = xml.indexOf('>', i+1);
if (j == -1) { // error if (j == -1) { // error
onError('...>'); this.onError('...>');
return; return;
}; };
attr_res = true; // атрибутов нет this.attr_res = true; // атрибутов нет
//if (xml.charCodeAt(i+1) === 47) { // </... //if (xml.charCodeAt(i+1) === 47) { // </...
if (w === 47) { // </... if (w === 47) { // </...
@ -569,7 +589,7 @@ function EasySAXParser() {
//console.log() //console.log()
if (xml.substring(i+2, q) !== x) { if (xml.substring(i+2, q) !== x) {
onError('close tagname'); this.onError('close tagname');
return; return;
}; };
@ -581,7 +601,7 @@ function EasySAXParser() {
continue; continue;
}; };
onError('close tag'); this.onError('close tag');
return; return;
}; };
@ -599,7 +619,7 @@ function EasySAXParser() {
}; };
if ( !(w > 96 && w < 123 || w > 64 && w <91) ) { if ( !(w > 96 && w < 123 || w > 64 && w <91) ) {
onError('first char nodeName'); this.onError('first char nodeName');
return; return;
}; };
@ -612,11 +632,11 @@ function EasySAXParser() {
if (w===32 || (w<14 && w > 8)) { // \f\n\r\t\v пробел if (w===32 || (w<14 && w > 8)) { // \f\n\r\t\v пробел
elem = x.substring(0, q) elem = x.substring(0, q)
attr_res = null; // возможно есть атирибуты this.attr_res = null; // возможно есть атирибуты
break; break;
}; };
onError('invalid nodeName'); this.onError('invalid nodeName');
return; return;
}; };
@ -626,12 +646,12 @@ function EasySAXParser() {
}; };
if (isNamespace) { if (this.isNamespace) {
if (stop) { if (stop) {
if (tagend) { if (tagend) {
if (!tagstart) { if (!tagstart) {
if (--stopIndex === 0) { if (--stopIndex === 0) {
nsmatrix = stacknsmatrix.pop(); this.nsmatrix = stacknsmatrix.pop();
}; };
}; };
@ -644,19 +664,19 @@ function EasySAXParser() {
continue; continue;
}; };
_nsmatrix = nsmatrix; _nsmatrix = this.nsmatrix;
if (!tagend) { if (!tagend) {
stacknsmatrix.push(nsmatrix); stacknsmatrix.push(this.nsmatrix);
if (attr_res !== true) { if (this.attr_res !== true) {
if (hasSurmiseNS = x.indexOf('xmlns', q) !== -1) { if (this.hasSurmiseNS = x.indexOf('xmlns', q) !== -1) {
attr_string = x; this.attr_string = x;
attr_posstart = q; this.attr_posstart = q;
getAttrs(); this.getAttrs();
hasSurmiseNS = false; this.hasSurmiseNS = false;
}; };
}; };
}; };
@ -664,25 +684,23 @@ function EasySAXParser() {
w = elem.indexOf(':'); w = elem.indexOf(':');
if (w !== -1) { if (w !== -1) {
xmlns = nsmatrix[elem.substring(0, w)]; xmlns = this.nsmatrix[elem.substring(0, w)];
elem = elem.substr(w+1); elem = elem.substr(w+1);
} else { } else {
xmlns = nsmatrix.xmlns; xmlns = this.nsmatrix.xmlns;
}; };
if (!xmlns) { if (!xmlns) {
if (tagend) { if (tagend) {
if (tagstart) { if (tagstart) {
nsmatrix = _nsmatrix; this.nsmatrix = _nsmatrix;
} else { } else {
nsmatrix = stacknsmatrix.pop(); this.nsmatrix = stacknsmatrix.pop();
}; };
} else { } else {
stopIndex = 1; // первый элемент для которого не определено пространство имен stopIndex = 1; // первый элемент для которого не определено пространство имен
attr_res = true; this.attr_res = true;
}; };
j += 1; j += 1;
@ -694,12 +712,12 @@ function EasySAXParser() {
//string_node = xml.substring(i, j+1); // текст ноды как есть //string_node = xml.substring(i, j+1); // текст ноды как есть
if (tagstart) { // is_onStartNode if (tagstart) { // is_onStartNode
attr_string = x; this.attr_string = x;
attr_posstart = q; this.attr_posstart = q;
ok = onStartNode(elem, getAttrs, unEntities, tagend var that = this;
ok = this.onStartNode(elem, function() { return that.getAttrs() }, unEntities, tagend
, getStringNode , getStringNode
); );
@ -707,11 +725,11 @@ function EasySAXParser() {
return; return;
}; };
attr_res = true; this.attr_res = true;
}; };
if (tagend) { if (tagend) {
ok = onEndNode(elem, unEntities, tagstart ok = this.onEndNode(elem, unEntities, tagstart
, getStringNode , getStringNode
); );
@ -719,21 +737,15 @@ function EasySAXParser() {
return; return;
}; };
if (isNamespace) { if (this.isNamespace) {
if (tagstart) { if (tagstart) {
nsmatrix = _nsmatrix; this.nsmatrix = _nsmatrix;
} else { } else {
nsmatrix = stacknsmatrix.pop(); this.nsmatrix = stacknsmatrix.pop();
}; };
}; };
}; };
j += 1; j += 1;
}; };
};
}; };

View File

@ -15,6 +15,7 @@ describe("angular xml parser", () => {
break; break;
} }
}); });
parser.angularSyntax = true;
}); });
it("parses [property] binding", () => { it("parses [property] binding", () => {
@ -53,7 +54,6 @@ describe("angular xml parser", () => {
assert.equal(last_attrs['text'], 'Name'); assert.equal(last_attrs['text'], 'Name');
}); });
return
it("detects equals without value", () => { it("detects equals without value", () => {
parser.parse("<TextField brokenTag= />"); parser.parse("<TextField brokenTag= />");
@ -71,4 +71,11 @@ describe("angular xml parser", () => {
assert.isFalse(last_attrs); assert.isFalse(last_attrs);
}); });
it("rejects angular properties if syntax disabled", () => {
parser.angularSyntax = false;
parser.parse("<TextField [text]='somevalue' />");
assert.isFalse(last_attrs);
});
}); });

2
xml/xml.d.ts vendored
View File

@ -86,7 +86,7 @@ declare module "xml" {
* @param onError The callback to execute when a parser error occurs. The 'error' parameter contains the error. * @param onError The callback to execute when a parser error occurs. The 'error' parameter contains the error.
* @param processNamespaces Specifies whether namespaces should be processed. * @param processNamespaces Specifies whether namespaces should be processed.
*/ */
constructor(onEvent: (event: ParserEvent) => void, onError?: (error: Error) => void, processNamespaces?: boolean); constructor(onEvent: (event: ParserEvent) => void, onError?: (error: Error) => void, processNamespaces?: boolean, angularSyntax?: boolean);
/** /**
* Parses the supplied xml string. * Parses the supplied xml string.

View File

@ -148,6 +148,14 @@ export class XmlParser implements definition.XmlParser {
} }
} }
public get angularSyntax() : boolean {
return this._parser.angularSyntax;
}
public set angularSyntax(value: boolean) {
this._parser.angularSyntax = value;
}
public parse(xmlString: string): void { public parse(xmlString: string): void {
if (this._processNamespaces) { if (this._processNamespaces) {
this._namespaceStack = []; this._namespaceStack = [];