Starting off, I am aware of the security risks storing JavaScript functions in JSON strings, however that is not what is happening here.
Now I am working on a JS multi-threading model using web workers and blob strings. However as I'm sure you are aware you cannot use custom objects or prototypes from said custom objects in web workers so I developed a system for serializing a custom object with functions into an anonymous object that can be used in the web worker however I am getting a syntax error when calling JSON.parse
over the serialized object.
Serialize function:
AjaxHandler.prototype.getEmbedded = function(stringify) {
"use strict";
let embMembers = this.metaData.embeddedMembers; // an array of function names to add
let embeddedObj = {};
let stringifyArray = stringify ? new Array(embMembers.length) : [];
if (stringify) {
for (let i = 0; i < embMembers.length; i++) {
stringifyArray[i] = ('"' + embMembers[i] + '":"' + AjaxHandler.prototype[embMembers[i]].toString().replace(/[\n\r]+/gi, '').replace(/[\t]+/gi, '')).replace(/\/\*\*\/this.\/\*\*\//gi, '') + '"';
}
} else {
for (let mem of embMembers) {
embeddedObj[mem] = AjaxHandler.prototype[mem];
}
}
if (stringify) {
return ("{" + stringifyArray.join(",") + "}");
} else {
return embeddedObj;
}
};
All functions being embedded are syntactically correct however when I try to parse it:
!function TestAction() {
"use strict";
let tHandler = new AjaxHandler();
let eme = tHandler.getEmbedded();
let stf = tHandler.getEmbedded(true);
let ptf = JSON.parse(stf); // Throws syntax error
debugger;
}();
It throws an error (Uncaught SyntaxError: Unexpected string) as noted in the code.
Is there a way to parse out the object containing functions?
Notes:
No JSON data is being sent to or from the client so I don't think it's a security risk to store and send a function in JSON.
I have researched previous questions on the matter and none of the leads I found produced any valid solution aside from "don't do it, it's a security risk".